text
stringlengths
64
81.1k
meta
dict
Q: Best way to design a database for a bakery store? I am building an application that will be used as a Sales Management system for a bakery store. I have built the following tables: Products has a single row per product. This is a Master Data definition only. It has somethings like 'Pizza`. Ingredients has rows like Flour and Tomatoes . These are raw input materials required to prepare different products. The bakery store needs to keep track of how much the raw input materials cost. Product_Ingredients describes what raw materials go in a final product. It could have something like Pizza | Tomatoes and Pizza | Green Peppers, Cup Cake|Strawberry Mix etc. My question is this: As a final product, the bakery offers Strawberry Mix for sale. But in the database it is considered as an ingredient. I can also add it as a separate Product but here is what makes this case complicated: In case the bakery runs out of Strawberry mix, they want to grab one from the shelf and convert it from a final product into an ingredient that will be used to make other final products. How can I go about turning this logic into database objects that make sense? Here is what I tried: I created an Inventory table that has a row for each raw material. When the bakery buys raw material, these are stored in the inventory table normally. The strawbery mix is inserted into the Products table to get the same treatment as the other final products (sale / discount / tax, etc). When the bakery staff want to use the mix from the shelf, they will have to "convert" it from final to raw material. Meaning, the application will mark the product unfit for sale, and will also insert a row in the inventory table. My solution has problems that can have ways around, but I wanted to know if there are better ways (as I am sure) of solving this problem. A: You have an ingredient; let's call this "strawberry mix, packet, 100g". You also have a product; let's call this "strawberry mix". There is a Product_Ingredients row which maps the product "strawberry mix" to the ingredient "strawberry mix, packet, 100g" with a quantity of 1. No need to convert anything to anything.
{ "pile_set_name": "StackExchange" }
Q: Rewriting code with continuations I have some code that evaluates primitive programs. Program is a list of statements (expression, block, return statement). Result of evaluation is last evaluated expression. Also evaluator should properly treat return statement (i.e. stop evaluation after first occurrence of return). To implement this logic I pass special callback function (NextStep) which make next evaluating step after current statement. I don't call next step when handling return statement: data Statement = Expr Int | Block [Statement] | Return Int deriving (Show, Eq) data Value = Undefined | Value Int deriving (Show, Eq) type NextStep = Value -> Value evalStmt :: Statement -> NextStep -> Value evalStmt (Expr val) next = let res = Value val in next res evalStmt (Block stmts) next = evalBlock stmts next evalStmt (Return val) next = Value val evalBlock :: [Statement] -> NextStep -> Value evalBlock [] next = next Undefined evalBlock [st] next = evalStmt st next evalBlock (st:rest) next = evalStmt st $ \ _ -> evalBlock rest next evalProgram stmts = evalBlock stmts id prog1 = [Expr 1, Block [Return 3, Expr 2], Expr 4] evalProg1 = evalProgram prog1 -- result will be Value 3 The question is how can I rewrite this code with continuation monad? I want to get rid of explicitly passed NextStep callback in evalStmt and evalBlock functions. Is it possible? A: The translation is fairly mechanical. Keep in mind that in the continuation monad, return feeds the value into the continuation. evalStmt :: Statement -> Cont Value Value evalStmt (Expr val) = let res = Value val in return res evalStmt (Block stmts) = evalBlock stmts evalStmt (Return val) = cont $ \_ -> Value val evalBlock :: [Statement] -> Cont Value Value evalBlock [] = return Undefined evalBlock [st] = evalStmt st evalBlock (st:rest) = evalStmt st >> evalBlock rest evalProgram :: [Statement] -> Value evalProgram stmts = runCont (evalBlock stmts) id And to simulate early returns, we just ignore the continuation given to Return val and just return the value we have.
{ "pile_set_name": "StackExchange" }
Q: Logic for inserting form with/without optional inputs into MySQL Using: Brackets Html editor, MySQL Workbench Simplified, I have a database with these tables (main table) person idperson PK NN UN AI *fk_job NN UN (foreign key refering to idjob) fn NN ln NN job idjob PK NN UN AI jobname NN adress idadress PK NN UN AI *fk_person NN UN (foreign key refering to idperson) adress NN and this form. In the form it is required to fill on one adress, and optional to fill in a second one. <?php $con = new mysqli("localhost","user","password","database"); if ($con-> connect_error) { die('Error : ('. $con->connect_errno .') '. $con->connect_error .''); } $job_sql = "SELECT idtype, typename FROM type;"; $job_data = $con->query($job_sql); //insert if(isset()) here $con->close(); ?> <form method="post"> <select name="typeSlc" required> <option disabled selected>_</option> <?php while($row = mysqli_fetch_array($job_data)) { ?> <option value="<?php echo $row['jobid'];?>"><?php echo $row['jobname'];?></option> <?php } ?> </select> <input name="fnTxt" required type="text"> <input name="lnTxt" required type="text"> <input name="adressTxt" required type="text"> <input name="cityTxt" required type="text"> <input name="opt_adressTxt" type="text"> <input name="opt_cityTxt" type="text"> <input name="submit" value="submit" type="submit"> </form Issue: I want to send a transaction with one batch of queries to the server when 'opt_adress' isset and another when it is not, namely: if(isset($_POST['submit'])) { if(isset($_POST['opt_adress'])) { $sql = sprintf ("BEGIN; INSERT INTO person (fk_job, fn, ln) VALUES (%s, '%s', '%s'); SELECT LAST_INSERT_ID() INTO @id; INSERT INTO adress (fk_person, adress) VALUES (@id, '%s'); INSERT INTO adress (fk_person, adress, city) VALUES (@id, '%s', '%s'); COMMIT;", $con->real_escape_string($_POST['jobSlc']), $con->real_escape_string($_POST['fnTxt']), $con->real_escape_string($_POST['lnTxt']), $con->real_escape_string($_POST['adressTxt']), $con->real_escape_string($_POST['cityTxt']), $con->real_escape_string($_POST['opt_adressTxt']), $con->real_escape_string($_POST['opt_cityTxt'])) ; } else { $sql = sprintf ("BEGIN; INSERT INTO person (fk_job, fn, ln) VALUES (%s, '%s', '%s'); INSERT INTO adress (fk_person, adress, city) VALUES (LAST_INSERT_ID(), '%s', '%s'); COMMIT;", $con->real_escape_string($_POST['jobSlc']), $con->real_escape_string($_POST['fnTxt']), $con->real_escape_string($_POST['lnTxt']), $con->real_escape_string($_POST['adressTxt']), $con->real_escape_string($_POST['cityTxt'])) ; } $con->query($sql); header("Location: samepage.php"); When I try to run the query it does not go through to the database (I am using MySQL Workbench). There are no error messages, yet the query is unsuccesful. I want to insert batches if queries in a transaction if there are existing values in the optional inputs. Is this the correct string for that? Or is there a sleeker code I can use? The form and database in this question is a simplified version on the one I use in reality. Thanks in advance, -burrdie A: You have to understand the difference between a query and a batch of queries. Since you have to execute several separate queries, you have to make several separate query() calls as well. So change your code like this $con->query("BEGIN"); $con->query(sprintf ("INSERT INTO person (fk_job, fn, ln)..."); $con->query("SELECT LAST_INSERT_ID() INTO @id"); // ...so on and you'll be set. Besides, it will let you write sleeker code, as you will be able to add your condition in the middle of the execution, thus not duplicating the code.
{ "pile_set_name": "StackExchange" }
Q: Property Bag in javascript I'm investigating some code outside my scope that's written in a style I've never seen before. I'm trying to understand the inner workings of the following property bag: Setter: props.Property(name) = val; Getter: val = props.Property(name); What would you need to instantiate for the setter to function as above? EDIT: Less simplification, this code IS successfully running on a BrowserWindow within a frame (similar to a phone environment). var UI = { ready: function(oProps) { try { if (oProps) { window.external.Property(UI.FrameWidth) = '1000'; window.external.Property(UI.FrameHeight) = '900'; } window.external.Ready(); } catch (e) { } } }; Thanks in advance, A: I think it might be just some weird old JScript syntax. Steering away from the "internal function returns a reference" idea from the comments, I found a question about differences between JavaScript and JScript and the only syntax difference listed is this one: The idiom f(x) = y, which is roughly equivalent to f[x] = y. There isn't much too find about this idiom though. However, this book about Jscript.Net briefly mentions that you can access any expando properties using square brackets or parenthesis. "expando" seems to be a modifier for classes which allows you to add dynamic properties. A: The code above is wrapped in a silent try catch block, so it is possible that it seems to be running successfully but actually isn't. Try logging the caught exception in the catch block. You should get a ReferenceError if this line: window.external.Property(UI.FrameWidth) = '1000'; is ever hit (which of course depends on the value of oProps).
{ "pile_set_name": "StackExchange" }
Q: How can I rotate rectangle in Java? My rectangle code: class Rectangle extends JPanel { int x = 105; int y= 100; int width = 50; int height = 100; public void paint(Graphics g) { g.drawRect (x, y, width, height); g.setColor(Color.WHITE); } Rectangle r = new Rectangle(); and I have a button "rotate". When the user presses the button with the mouse, the rectangle must rotate 15 degrees. This is my action code: public void actionPerformed(ActionEvent e){ Object source = e.getSource(); if( source == rotate){ AffineTransform transform = new AffineTransform(); transform.rotate(Math.toRadians(15), r.getX() + r.getWidth()/2, r.getY() + height/2); r.add(transform); } } But the code doesn't work. I don't know why? What do you think? My edited-action-code part: public void actionPerformed(ActionEvent e){ Object source = e.getSource(); if( source == rotate){ Paint p = new Paint(); panel1.add(r); repaint(); } } class Paint extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D)g; g2d.setColor(Color.WHITE); g2d.translate(r.getX()+(r.WIDTH/2), r.getY()+(r.HEIGHT/2)); g2d.rotate(Math.toRadians(15)); r.equals(g2d); repaint(); } } A: Custom painting is done by overriding the paintComponent() method, not paint(). Don't forget the super.paintComponent() at the start. The paintComponent() method is where the painting is done so that is were you need the rotation code. So you could set a variable to indicate if you need to do the rotation or not. So all the ActionListener does is set the variable and then invoke repaint(). Or, I've never tried applying a rotation directly to the Rectangle (I've always applied it to the Graphics object in the painting method). Maybe you just need to invoke repaint() on the panel in your ActionListener. The panel won't know you've changed the Rectangle, so you need to tell it to repaint itself.
{ "pile_set_name": "StackExchange" }
Q: How do I get PointToScreen in UWP In WPF something like this would tell me where the border top left corner: var point = myBorder.PointToScreen(new Point()); How do I get the same in UWP? I can't find any way to get it. Thank you :) A: You can get the screen coordinates of UIElement in following steps: Get the coordinates of UIElement relative to current application window by following codes: GeneralTransform transform = myBorder.TransformToVisual(Window.Current.Content); Point coordinatePointToWindow = transform.TransformPoint(new Point(0, 0)); Get the Rect information of current application window: Rect rect = Window.Current.CoreWindow.Bounds; Calculate the coordinates of your UIElement: var left = coordinatePointToWindow.X + rect.Left; var top = coordinatePointToWindow.Y + rect.Top; A: You can use TransformToVisual method. Use the following code var transformToVisual = myBorder.TransformToVisual(Window.Current.Content); var borderCoordinats = transformToVisual .TransformPoint(new Point(0, 0));
{ "pile_set_name": "StackExchange" }
Q: How to type check recursive definitions using Algorithm W? I am implementing Algorithm W (the Hindley-Milner type system) in JavaScript: The function which implements the above rules is typecheck and it has the following signature: typecheck :: (Context, Expr) -> Monotype It is defined as follows: function typecheck(context, expression) { switch (expression.type) { case "Var": var name = expression.name; var type = context[name]; return inst(type); case "App": var fun = typecheck(context, expression.fun); var dom = typecheck(context, expression.arg); var cod = new Variable; unify(fun, abs(dom, cod)); return cod; case "Abs": var param = expression.param; var env = Object.create(context); var dom = env[param] = new Variable; var cod = typecheck(env, expression.result); return abs(dom, cod); case "Let": var assignments = expression.assignments; var env = Object.create(context); for (var name in assignments) { var value = assignments[name]; var type = typecheck(context, value); env[name] = gen(context, type); } return typecheck(env, expression.result); } } A little bit about the data types: A context is an object which maps identifiers to polytypes. type Context = Map String Polytype An expression is defined by the following algebraic data type: data Expr = Var { name :: String } | App { fun :: Expr, arg :: Expr } | Abs { param :: String, result :: Expr } | Let { assignments :: Map String Expr, result :: Expr } | Rec { assignments :: Map String Expr, result :: Expr } In addition, we have the following functions which are required by the algorithm but are not essential to the question: inst :: Polytype -> Monotype abs :: (Monotype, Monotype) -> Monotype gen :: (Context, Monotype) -> Polytype The inst function specializes a polytype and the gen function generalizes a monotype. Anyway, I want to extend my typecheck function to allow recursive definitions as well: Where: However, I am stuck with a chicken and egg problem. Context number one has the assumptions v_1 : τ_1, ..., v_n : τ_n. Furthermore, it implies e_1 : τ_1, ..., e_n : τ_n. Hence, you first need to create the context in order to find the types of e_1, ..., e_n but in order to create the context you need to find the types of e_1, ..., e_n. How do you solve this problem? I was thinking of assigning new monotype variables to the identifiers v_1, ..., v_n and then unifying each monotype variable with its respective type. This is the method that OCaml uses for its let rec bindings. However, this method does not yield the most general type as is demonstrated by the following OCaml code: $ ocaml OCaml version 4.02.1 # let rec foo x = foo (bar true) and bar x = x;; val foo : bool -> 'a = <fun> val bar : bool -> bool = <fun> However, GHC does compute the most general type: $ ghci GHCi, version 7.10.1: http://www.haskell.org/ghc/ :? for help Prelude> let foo x = foo (bar True); bar x = x Prelude> :t foo foo :: Bool -> t Prelude> :t bar bar :: t -> t As you can see, OCaml infers the type val bar : bool -> bool while GHC infers the type bar :: t -> t. How does Haskell infer the most general type of the function bar? I understand from @augustss' answer that type inference for recursive polymorphic functions is undecidable. For example, Haskell cannot infer the type of the following size function without additional type annotations: data Nested a = Epsilon | Cons a (Nested [a]) size Epsilon = 0 size (Cons _ xs) = 1 + size xs If we specify the type signature size :: Nested a -> Int then Haskell accepts the program. However, if we only allow a subset of algebraic data types, inductive types, then the data definition Nested becomes invalid because it is not inductive; and if I am not mistaken then the type inference of inductive polymorphic functions is indeed decidable. If so, then what is the algorithm used to infer the type of polymorphic inductive functions? A: You could type check it using explicit recursion with a primitive fix having type (a -> a) -> a. You can insert the fix by hand or automatically. If you want to extend the type inferences then that's quite easy too. When encountering a recursive function f, just generate a new unification variable and put f with this type in the environment. After type checking the body, unify the body type with this variable and then generalize as usual. I think this is what you suggest. It will not allow you to infer polymorphic recursion, but this in general undecidable.
{ "pile_set_name": "StackExchange" }
Q: Lambda expression usage with Selenium2 ExpectedCondition? After reading an article about JDK1.8 and Lambda expressions, I realized that the ExpectedCondition block that I have been using for the last few years is probably suitable to be expressed as a Lambda expression. Given this wait object: Wait<WebDriver> wait = new FluentWait<WebDriver>( driver ) .withTimeout(30, SECONDS) .pollingEvery(5, SECONDS) .ignoring( NoSuchElementException.class ); Can anyone tell me how I can convert this ExpectedCondition expression, for Selenium, into a Lambda expression? WebElement foo = wait.until( new ExpectedCondition<Boolean>() { public WebElement apply( WebDriver webDriver ) { return webDriver.findElement( By.id("foo") ); } } ); A: From Selenium version 3.2.0 the until() method will only accept Function<T,K> as parameter and taking in Predicate<T> as a parameter is deprecated. The above decision is to make use of lambda expressions. So to answer you question: Wait<WebDriver> wait = new FluentWait<WebDriver>( driver ) .withTimeout(30, SECONDS) .pollingEvery(5, SECONDS) .ignoring(NoSuchElementException.class); //lamda expression: WebElement foo = wait.until(d -> d.findElement(By.id("foo")));
{ "pile_set_name": "StackExchange" }
Q: Accidentally added solution to wrong Team Foundation Service project I created a new project, and accidentally added it to the wrong TFS folder. I went to Change Source Control and clicked Unbind. It gave this warning and I said okay: You are about to unbind one or more of your projects. After this operation, you will no longer be able to access source control for these projects. But now, when I try Add solution to source control... again, it automatically gets added to the wrong TFS project. I also tried deleting the solution and recreating it, but if I use the name name it still automatically gets added to the incorrect TFS project. I could just start a new project with a different name, but I'd like to know how to fix this. How can I change which TFS project I'm using. A: To correct this I had to goto File > Source Control > Advanced > Workspaces... and click Edit for my account. That brings up the Edit Workspace window, which lists all of the controlled projects, their source control folders and local folders. From there the paths can be edited or the projects can be removed completely.
{ "pile_set_name": "StackExchange" }
Q: Why won't my 12v 2.5A LCD driver board run when powered from a 12v 6A supply? I recently put together a portable RetroPie project with an LCD from an old laptop, it runs fine off an old ps2 power supply drawing around 1A. However, I decided to try running it off 8 LiPo cells (18650) I had lying around. I put the 8 cells in parallel, and connected them to a 6A DC to DC step up converter setting it to 12v. The red LED on the driver board lit up telling me the board was receiving power, but when I hit the power button the LED turned green, which indicates that it is turning on, then backlight flickered and the whole thing reset, the LED also went back to red, this will repeat as many times as I push the power button. I am assuming that the culprit is the CCFL needing more current than the DC to DC converter can provide, however the specs say that the board needs at most 2.5A so I am uncertain. If anyone knows what I can do to get this working, any help would be greatly appreciated. DC to DC converter: http://a.co/aEGWhaY LCD Driver: http://a.co/b3kLdwH A: The converter (or batteries) can't keep up with the in rush current, dipping down too much or is too noisy for the driver. Try adding a 1000 uF capacitor to the power input of the Driver. Other option is to put the cells in series and regulate them down to 12V instead. Or use 3 in series with a regulator. The driver likely still works at less than 12V input.
{ "pile_set_name": "StackExchange" }
Q: Vector of Vectors. Remove duplicates based on specific index of inner vectors I have been using a combination of different variables and data structures for this, I am not sure which is best in practice. I don't care much how long it takes to run these calculations, I just care about the end result. I have a combination of values. V - W - X - Y : Z. V,W,X, and Y are used to calculate Z. V, W, X, and Y each have 256 different possibilities. So I believe I am working with a combination. V - W - X - Y : Z So long as all my values are the same, the order doesn't matter, I still get the same result. 0 - 52 - 115 - 249 : 0.059784 52 - 249 - 0 - 114 : 0.059784 249 - 52 - 114 - 0 : 0.059784 0 - 52 - 115 - 250 : 0.057423 0 - 250 - 115 - 52 : 0.057423 250 - 0 - 52 - 115 : 0.057423 0 - 52 - 115 - 251 : 0.055006 115 - 251 - 52 - 0 : 0.055006 251 - 0 - 52 - 115 : 0.055006 I need my end result to be a list of these values that are unique to Z. I don't really care which combination gets saved to achieve said unique value for Z. I just need to retain the value of Z which is a float (though in the end result I can store it as a string I suppose), and the values of V, W, X, Y. So if I start with this: 250 - 0 - 52 - 115 : 0.057423 0 - 52 - 115 - 249 : 0.059784 0 - 52 - 115 - 250 : 0.057423 52 - 249 - 0 - 114 : 0.059784 0 - 52 - 115 - 251 : 0.055006 0 - 250 - 115 - 52 : 0.057423 251 - 0 - 52 - 115 : 0.055006 249 - 52 - 114 - 0 : 0.059784 115 - 251 - 52 - 0 : 0.055006 I would end with something similar to this: 250 - 0 - 52 - 115 : 0.057423 0 - 52 - 115 - 249 : 0.059784 115 - 251 - 52 - 0 : 0.055006 Any help/advice would be appreciated. Many thanks! EDIT: Adding more to this to help decipher some issues. So the idea of the entire project I am working on is to calculate every possible resistance for a quad digital potentiometer when you wire each of the four potentiometers in parallel. I may calculate series later, but for right now parallel is what I am after. The potentiometer itself has an A terminal, B terminal, and Wiper terminal. We are looking for the resistance between the A terminal and the wiper terminal. This is a 1k ohm 8 bit potentiometer. That means we have 256 steps of resolution to work with. To calculate the resistance for a certain step, we figure out: trim = (((( (ohmRatingOfDigiPot)*(numberofPossibleSteps - stepToCalculate) )/numberofPOssileSteps)+wiperResistance)/1000); So, our equation turns out to be trim = (((( (1000)*(256-index) )/256)+50)/1000) Where index is the step (out of 256 total steps) we are on. So I figure out the possible values of each of these steps and I pass them into an array. One for each of the four potentiometers in the quad potentiometer. for(int i = 0; i < 256; i++) { trim = (((( (1000)*(256-index) )/256)+50)/1000); index++; potOneSteps[i] = trim; potTwoSteps[i] = trim; potThreeSteps[i] = trim; potFourSteps[i] = trim; } Yes, I know there is probably a much better way to do that. Like I said, it has been so long since I've used C++. This worked and I knew I had other things to worry about so it ended up staying. Ha. So now I need to figure out every possible value for these four potentiometers in every different combination available. 4 potentiometers with 256 possible value for each? Bring on the for loops! To calculate the resistance of resistors in parallel, we use: Total Resistance = ( 1 / ( (1/R1) + (1/R2) + (1/R3) + ... + (1/Rn)) For our four arrays I figured this: for (int A1W1 = 0; A1W1 < 256; A1W1++) { for (int A2W2 = 0; A2W2 < 256; A2W2++) { for (int A3W3 = 0; A3W3 < 256; A3W3++) { for (int A4W4 = 0; A4W4 < 256; A4W4++) { rTrim = (1/((1/potOneSteps[A1W1]) + (1/potTwoSteps[A2W2]) + (1/potThreeSteps[A3W3]) + (1/potFourSteps[A4W4]))); } } } } Very long. Very processor and memory intensive. Very poor. I know. I know. This was the only way I could think to go through all of the values to do the calculations. Not sure if there is a better way, open to any and all suggestions. So in my original post, V - W - Y - X correspond with the index where Z was calculated. And Z is the the actual resistance that we calculated using the values at said indices. Since all of the arrays are the same we get repeat values like I spoke about in the original post. So I only need to know the unique values for Z/rTrim and the step(s) at which it was found in order to have all of the possible values and be able to set the digital pots to said values. I am open to any and all variables/data structures/etc for this. Nothing really has to be set to a certain type so I can deal with doubles, floats, ints, arrays, vectors, sets, linked lists (oh please no!), etc. I hope that makes sense. Kind of long winded but I figured it would be beneficial to have all of the information available for what I am trying to go for. Many thanks!! EDIT2: I may have solved this problem with PHP and mySQL, my "native" languages. If you guys still want to lend a hand, I am all ears and willing to learn best practices, but don't feel obligated. Much appreciated for the help you did provide! A: You can do the following: 1) define a class that holds the 4 values and the floating point value. 2) Define an operator < for this class that compares the floating point value. 3) Define a std::set of this class and populate it. Here is an example: #include <set> #include <vector> #include <array> #include <algorithm> #include <iterator> #include <ostream> #include <iostream> typedef std::vector<int> IntVector; struct MyValueClass { IntVector m_vals; double m_finalVal; bool operator < (const MyValueClass& c2) const { return (m_finalVal < c2.m_finalVal); } MyValueClass(const IntVector& v, double val) : m_vals(v), m_finalVal(val) {} }; typedef std::set<MyValueClass> ValueClassSet; using namespace std; int main() { vector<MyValueClass> mc; // Sample data mc.push_back(MyValueClass(IntVector{ 250, 0, 52, 115 }, 0.057423)); mc.push_back(MyValueClass(IntVector{ 0, 52, 115, 249 }, 0.059784)); mc.push_back(MyValueClass(IntVector{ 0, 52, 115, 250 }, 0.057423)); mc.push_back(MyValueClass(IntVector{ 52, 249, 0, 114 }, 0.059784)); mc.push_back(MyValueClass(IntVector{ 0, 52, 115, 251 }, 0.055006)); mc.push_back(MyValueClass(IntVector{ 0, 250, 115, 52 }, 0.057423)); mc.push_back(MyValueClass(IntVector{ 251, 0, 52, 115 }, 0.055006)); mc.push_back(MyValueClass(IntVector{ 249, 52, 114, 0 }, 0.059784)); mc.push_back(MyValueClass(IntVector{ 115, 251, 52, 0 }, 0.055006)); // populate set with sample data from vector ValueClassSet ms; ValueClassSet::iterator it = ms.begin(); copy(mc.begin(), mc.end(), inserter(ms, it)); // output results ValueClassSet::iterator it2 = ms.begin(); while (it2 != ms.end()) { copy(it2->m_vals.begin(), it2->m_vals.end(), ostream_iterator<int>(cout, " ")); cout << " : " << it2->m_finalVal << "\n"; ++it2; } } Output: 0 52 115 251 : 0.055006 250 0 52 115 : 0.057423 0 52 115 249 : 0.059784 So basically, we populate a vector of your information, and then we populate the set with the vector. Since a std::set only stores unique values, only the unique Z items will be stored. The operator < that we set up for the MyValueClass type is what std::set will use to determine if an item is already in the set. Note: I used C++11 initialization syntax to populate the vector. If you're using a compiler that is pre C++11, populate the vector the "old-fashioned way".
{ "pile_set_name": "StackExchange" }
Q: How can I have a user specific hosts file Is it possible to configure user specific hosts file instead of a common /etc/hosts. For example if user "user1" tries to get the name for the IP: "127.0.0.1", he gets "dev.user1" and if user "user2" tries to get the name for the same IP, he gets "dev.user2". A: What problem are you trying to solve? You certainly can't have two different entries in a hosts file, that are somehow toggled depending on which user you are. If you tell us what you're trying to do, rather than ask us about your specific implementation, we may be able to help more. A: No, you cannot have a per-user /etc/hosts file, or anything like /home/user1/.hosts , etc. You are using gethostbyaddr which is hardcoded to follow the instructions in nsswitch.conf, which itself tells gethostbyaddr to look in /etc/hosts . You might be able to do something like add additional loopback IPs on the 127.0.0.0/8 network, like 127.0.0.2 , 127.0.0.3, 127.1.2.3, and then assign a local hostname to one of these local IPs. We did this at one job, but I remember that this really confused our engineers. Also, if I remember right some loadbalancers actually do this internally. Here's an example /etc/hosts to illustrate my point: 127.0.0.1 u1.localhost u1 127.0.0.2 u2.localhost u2 # And if you wanted QA servers on the same host, add them to 127.0.8.0/24 127.0.8.1 qa1.localhost qa1 As @blacklotus suggested earlier, the more common way to do this is to designate part of your local network as a "Developer LAN".
{ "pile_set_name": "StackExchange" }
Q: Use [...new Set()] to get only uniques based off inner Array? Is it possible to use [...new Set()] to return an array of unique objects based on the inner id value? If this isn't possible, is there any other clever ES6 ways to achieve this output? Reference: Unique Values in an Array var arr = [ {email: '[email protected]', id: 10} ] var arr2 = [ {email: '[email protected]', id: 10}, {email: '[email protected]', id: 13} ] mergedArray = arr.concat(arr2); console.log( [...new Set(mergedArray)] ); // output would be: // [ // {email:'[email protected]', id: 10}, // {email:'[email protected]', id: 13} // ] A: To get the unique objects based on ID, you could create a Map instead of a Set, pass it a 2-element Array as iterator, and it will have unique keys, and then get it's values var arr = [ {email: '[email protected]', id: 10} ] var arr2 = [ {email: '[email protected]', id: 10}, {email: '[email protected]', id: 13} ] var mergedArray = arr.concat(arr2); var map = new Map(mergedArray.map(o => [o.id,o])); var unique = [...map.values()]; console.log(unique);
{ "pile_set_name": "StackExchange" }
Q: Stuck with dependencies in an AppX from Desktop App Converter I have finally succeeded converting my desktop app to AppX with Desktop App Converter, and to sign it with the insight from Franklin Chen. Step by step, I am getting closer to completion. But I am now bumping into a new hurdle (hopefully the last). I tried to follow the advice at https://blogs.msdn.microsoft.com/vcblog/2016/07/07/using-visual-c-runtime-in-centennial-project/ I did install on my machine vc_uwpdesktop.110.exe, vc_uwpdesktop.120.exe and vc_uwpdesktop.140.exe. But still not joy. When I try to install the AppX, I get this error message : Ask the developer for a new app package. This package may conflict with a package already installed, or it depends on things not installed here (package dependencies), or is made for a different architecture (0x80073CF3) 20161015 - More information : I tried to use add-appxpackage as instructed. PS C:\Windows\system32> add-appxpackage –register C:\output\CheckWriterIII\PackageFiles\AppxManifest.xml Here is the result on the command line : add-appxpackage : Deployment failed with HRESULT: 0x80073CF3, Package failed updates, dependency or conflict validation. Windows cannot install package CheckWriterIII_3.2.0.0_x86__eqr0y32pbpypt because this package depends on a framework that could not be found. Provide the framework "Microsoft.VCLibs.120.00.UWPDesktop" published by "CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US", with neutral or x86 processor architecture and minimum version 12.0.40652.5, along with this package to install. The frameworks with name "Microsoft.VCLibs.120.00.UWPDesktop" currently installed are: {} NOTE: For additional information, look for [ActivityId] 147c2bae-26c2-0005-268c-7c14c226d201 in the Event Log or use the command line Get-AppxLog -ActivityID 147c2bae-26c2-0005-268c-7c14c226d201 At line:1 char:1 + add-appxpackage –register C:\output\CheckWriterIII\PackageFiles\AppxM ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : WriteError: (C:\output\Check...ppxManifest.xml:String) [Add-AppxPackage], IOException + FullyQualifiedErrorId : DeploymentError,Microsoft.Windows.Appx.PackageManager.Commands.AddAppxPackageCommand As instructed, I have fetched the log : PS C:\Windows\system32> Get-AppxLog -ActivityID 147c2bae-26c2-0005-268c-7c14c226d201 Time ID Message ---- -- ------- 10/15/2016 5:41:58 PM 301 The calling process is powershell.exe 10/15/2016 5:41:58 PM 603 Started deployment Register operation on a package with main parameter: AppxManifest.xml and Options: DevelopmentModeOption. See http://go.microsoft.com/fwlink/?LinkId=235160 for help diagnosing app deployment issues. 10/15/2016 5:41:58 PM 10002 Creating Resiliency File C:\ProgramData\Microsoft\Windows\AppRepository\76c1ec66-a626-417f-be 73-95fd9ce4b88f_S-1-5-21-2501171662-860024267-76414939-1001_1.rslc for Register Operation on Package CheckWriterIII_3.2.0.0_x86__eqr0y32pbpypt. 10/15/2016 5:41:58 PM 607 Deployment Register operation on package CheckWriterIII_3.2.0.0_x86__eqr0y32pbpypt has been de-queued and is running for user DESKTOP-V1EBBS5\mitch. 10/15/2016 5:41:58 PM 613 Adding uri to the list of Uris: C:\output\CheckWriterIII\PackageFiles\AppxManifest.xml. 10/15/2016 5:41:58 PM 628 Windows cannot install package CheckWriterIII_3.2.0.0_x86__eqr0y32pbpypt because this package depends on a framework that could not be found. Provide the framework "Microsoft.VCLibs.120.00.UWPDesktop" published by "CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US", with neutral or x86 processor architecture and minimum version 12.0.40652.5, along with this package to install. The frameworks with name "Microsoft.VCLibs.120.00.UWPDesktop" currently installed are: {} 10/15/2016 5:41:58 PM 605 The last successful state reached was Indexed. Failure occurred before reaching the next state Resolved. hr: 0x80073CF3 10/15/2016 5:41:58 PM 401 Deployment Register operation with target volume C: on Package CheckWriterIII_3.2.0.0_x86__eqr0y32pbpypt from: (AppxManifest.xml) failed with error 0x80073CF3. See http://go.microsoft.com/fwlink/?LinkId=235160 for help diagnosing app deployment issues. 10/15/2016 5:41:58 PM 404 AppX Deployment operation failed for package CheckWriterIII_3.2.0.0_x86__eqr0y32pbpypt with error 0x80073CF3. The specific error text for this failure is: Windows cannot install package CheckWriterIII_3.2.0.0_x86__eqr0y32pbpypt because this package depends on a framework that could not be found. Provide the framework "Microsoft.VCLibs.120.00.UWPDesktop" published by "CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US", with neutral or x86 processor architecture and minimum version 12.0.40652.5, along with this package to install. The frameworks with name "Microsoft.VCLibs.120.00.UWPDesktop" currently installed are: {} Now I don't understand why it does not find Microsoft.VCLibs.120.00.UWPDesktop. I have downloaded and installed vc_uwpdesktop.120.exe 12.0.40653.00 and double verify it as not only in programs and features, but on the disk where it is supposed to be. A: Thanks for the update. That confirms what the problem is. It was actually described in your original post, but it's quite subtle: I did install on my machine vc_uwpdesktop.110.exe, vc_uwpdesktop.120.exe and vc_uwpdesktop.140.exe. Unfortunately this did not do what you think. It installed the .appx files that can be used to redistribute the framework dependencies. It did not actually install the framework dependencies themselves. To install them, you have to find the .appx files they installed (or at least the 120 x86 version) and ensure they are also installed. You can do so directly with the App Installer, with Add-AppxPackage separately (and ahead of time), or, I believe, as part of your package's installation by referencing the framework dependency in a -DependencyPath argument. The path to the .appx file in question looks something like this; tweak the version numbers and platform for your case as required. Just make sure you don't accidentally use a variant without "Desktop" in its name. C:\Program Files (x86)\Microsoft SDKs\Windows Kits\10\ExtensionSDKs\Microsoft.VCLibs.Desktop.110\14.0\Appx\Retail\x86 Once you install or reference the correct package here, your main package should install (or register) successfully.
{ "pile_set_name": "StackExchange" }
Q: Display hourly based data for 24 hour in SQL Server I want to display the hourly based report for the last 24 hour. I have tried but the problem is that it will display count only where particular hour contains data. But I want to display count for an hour and if count not found then display 0 over there. select datepart(hour, upload_date) as [hour], count(*) from tbl_stories where upload_date > getdate() - 1 group by datepart(hour, upload_date) Output: hour count ------------- 11 2 16 1 17 1 but I want to get a record in the following way. hour count ------------- 1 0 2 0 3 5 . . . . 24 1 A: You can use a value() clause to generate all the hours and then use left join: select v.hh, count(s.upload_date) from (values (0), (1), . . . (23) ) v(hh) left join tbl_stories s on datepart(hour, s.upload_date) = v.hh and s.upload_date > getdate() - 1 group by v.hh order by v.hh; Note that hours go from 0 to 23. If you don't want to list out the hours, a convenient generation method is a recursive CTE: with hours as ( select 1 as hh union all select hh + 1 from hours where hh < 23 ) select h.hh, count(s.upload_date) from hours h tbl_stories s on datepart(hour, s.upload_date) = h.hh and s.upload_date > getdate() - 1 group by h.hh order by h.hh;
{ "pile_set_name": "StackExchange" }
Q: C++ - function pointers and class While I was trying to compile this piece of code to implement the concept of function pointer using classes in C++: #include <iostream> using namespace std; class sorting { public: void bubble_sort(int *arr, int size, bool (*compare)(int,int)) { int i,j,temp = 0; for(i = 0; i < size - 1; i++) { for(j = i+1; j < size; j++) { if(compare(arr[i],arr[j])) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } } bool ascending(int x,int y) { return x > y; } bool descending(int x,int y) { return x < y; } void display(int *arr,int size) { for(int index = 0; index < size; index++) { cout<<"arr["<<index<<"]:"<<arr[index]<<endl; } } }; int main() { int arr[10] = {99,77,22,33,88,55,44,66,11,100}; sorting s; cout<<"Ascending order"<<endl; s.bubble_sort(arr,10,&sorting::ascending); s.display(arr,10); cout<<"Descending order"<<endl; s.bubble_sort(arr,10,&sorting::descending); s.display(arr,10); return 0; } I got errors in these lines: s.bubble_sort(arr,10,&sorting::ascending); s.bubble_sort(arr,10,&sorting::descending); The errors are: error C2664: 'sorting::bubble_sort' : cannot convert parameter 3 from 'bool (__thiscall sorting::* )(int,int)' to 'bool (__cdecl *)(int,int)' for both the lines. Can somebody help me to eliminate these errors? A: The easiest method is to make the definitions of ascending and descending static functions either inside or outside the class definition, or by moving the function declaration/definition outside of the class' scope: static bool ascending(int x,int y) { return x > y; } static bool descending(int x,int y) { return x < y; } The compiler sees the functions defined in the class as member functions using the __thiscall calling convention, while normal C++ function pointers use the __cdecl calling convention by default (it can be modified manually). Moving the definitions outside of the class gives the functions the __cdecl modifier automatically. Marking the functions as static also gives them the __cdecl modifier.
{ "pile_set_name": "StackExchange" }
Q: How do you adjust a windshield sprayer? One of the sprayers on my car misses the windshield completely. How can I adjust it to point in the right direction? My car is a 2002 Subaru Legacy GT, but I've run into this problem with many cars. A: I use a pin board, needle, a finish nail or whatever I have in the garage. Put in the sprayers holes and correct alignment. Done! Make sure to not push any object to far as it can damage inner tube and start to leak!
{ "pile_set_name": "StackExchange" }
Q: Why does initramfs mount the root filesystem read-only What is the reason for the root filesystem being mounted ro in the initramfs (and in initrd). For example the Gentoo initramfs guide mounts the root filesystem with: mount -o ro /dev/sda1 /mnt/root Why not the following? mount -o rw /dev/sda1 /mnt/root I can see that there is a probably a good reason (and it probably involves switchroot), however it does not seem to be documented anywhere. A: The initial ramdisk (initrd) is typically a stripped-down version of the root filesystem containing only that which is needed to mount the actual root filesystem and hand off booting to it. The initrd exists because in modern systems, the boot loader can't be made smart enough to find the root filesystem reliably. There are just too many possibilities for such a small program as the boot loader to cover. Consider NFS root, nonstandard RAID cards, etc. The boot loader has to do its work using only the BIOS plus whatever code can be crammed into the boot sector. The initrd gets stored somewhere the boot loader can find, and it's small enough that the extra bit of space it takes doesn't usually bother anyone. (In small embedded systems, there usually is no "real" root, just the initrd.) The initrd is precious: its contents have to be preserved under all conditions, because if the initrd breaks, the system cannot boot. One design choice its designers made to ensure this is to make the boot loader load the initrd read-only. There are other principles that work toward this, too, such as that in the case of small systems where there is no "real" root, you still mount separate /tmp, /var/cache and such for storing things. Changing the initrd is done only rarely, and then should be done very carefully. Getting back to the normal case where there is a real root filesystem, it is initially mounted read-only because initrd was. It is then kept read-only as long as possible for much the same reasons. Any writing to the real root that does need to be done is put off until the system is booted up, by preference, or at least until late in the boot process when that preference cannot be satisfied. The most important thing that happens during this read-only phase is that the root filesystem is checked to see if it was unmounted cleanly. That is something the boot loader could certainly do instead of leaving it to the initrd, but what then happens if the root filesystem wasn't unmounted cleanly? Then it has to call fsck to check and possibly fix it. So, where would initrd get fsck, if it was responsible for this step instead of waiting until the handoff to the "real" root? You could say that you need to copy fsck into the initrd when building it, but now it's bigger. And on top of that, which fsck will you copy? Linux systems regularly use a dozen or so different filesystems. Do you copy only the one needed for the real root at the time the initrd is created? Do you balloon the size of initrd by copying all available fsck.foo programs into it, in case the root filesystem later gets migrated to some other filesystem type, and someone forgets to rebuild the initrd? The Linux boot system architects wisely chose not to burden the initrd with these problems. They delegated checking of the real root filesystem to the real root filesystem, since it is in a better position to do that than the initrd. Once the boot process has proceeded far enough that it is safe to do so, the initrd gets swapped out from under the real root with pivot_root(8), and the filesystem is remounted in read-write mode.
{ "pile_set_name": "StackExchange" }
Q: In the card crafting UI, is it possible to search for cards that I do not own Generally, I feel like the search capabilities in your card collection are rather good. I have however not yet figured out a way to search for all cards that I do not own. Is this possible? For example, lets say the only cards that I do not have are Ragnaros and Molten Giant. Also, I only have one Azure Drake (so I am missing one). In this particular scenario, is it possible to formulate a search query which finds Ragnaros, Molten Giant and Azure Drake? A: No, the tools are too limited. You have only 5 filter options available: the mana gem cost: 0, 1, 2, 3, 4, 5, 6 or 7+ the search box (finds all cards with the word, so "murloc" finds Hungry Crab) the set (more on this later) Show Only Golden Cards Include Soulbound Cards (shows more cards) If you want to find cards you can craft which you are not yet able to play, you need to do the following: Set filters to: all mana gems, empty search box, Expert Set, do not Show Only Golden Cards, do not Include Soulbound Cards. examine each card. If you have 0, the card will appear blue. If you have 1, there will not be a x2 tag. There should be a x2 tag on all the non-golden cards unless (a) the card is legendary (you only get one) or (b) you have additional gold versions of the card bringing you to 2 total. Change filter to Promo Set repeat step 2 There is no need to check the Basic Set, Reward Set or the Naxxramas Set as all non-golden cards in these sets are Soulbound (cannot be crafted). Do check the Include Soulbound Cards filter if you are examining these sets. A: With the new patch 4.2.0 (released in middle March 2016) many new filtering options have been added. If you click on the crafting button and type the following in the search box: owned:0-1 then you'll only see all craftable cards for which you only own 0 or 1 cards. If you also want to include uncraftable/adventure cards select the "Include uncraftable cards" checkbox. More details about all the new filtering options are detailed in this Hearthstone blog article.
{ "pile_set_name": "StackExchange" }
Q: Machine Learning/Statistics - Factor Analysis Proof, Stuck I'm currently following this guide from stanford's CS229 machine learning class for Factor Analysis. I followed through every point except for the following: http://cs229.stanford.edu/notes/cs229-notes9.pdf , page 7-8. It states that $\mu = E_{z|x}[z]$ after the proof using maximum likelihood. For my attempt of the proof, consider the equation (6) on page 7: The only terms that rely on $\mu$ is: $\sum_n\sum_{z_n}p(z_n|x_n)[-\frac{1}{2}(x-\mu-\Lambda)^T\Psi^{-1}(x-\mu-\Lambda)]$, or even more concisely: $\sum_n\sum_{z_n}p(z_n|x_n)[-\frac{1}{2}(-2x^T\Psi^{-1}\mu+\mu\Psi^{-1}\mu + 2z_n^T\Lambda^T\Psi^{-1}\mu)]$ We then can express it as an expectation after taking gradient with respect to $\mu$: $\sum_nE_{z|x}[-(\Psi^{-1}\mu + \Psi^{-1}(\Lambda z_n + x_n))] = 0$ Then we get: $\sum_n\mu = \sum_nx_n + E(\Lambda z_n)$ Thus we get: $\mu = \frac{\sum_nx_n + E(\Lambda z_n)}{N}$. The answer in the notes, says that it is actually: $\mu = \frac{\sum_nx_n}{N}$. So I am a little bit off. I can't find exactly where I could drop the expected value. Is there some argument for which $E(\Lambda z_n) = 0$? A: First your notation $\sum_{z_n}$ seems to suggest that $z_n$ has discrete support and is better left as either the usual expectation symbol or an integral. Also I think a minus has gone missing somewhere in your expression, taking the derivative through the expectation and differentiating the quadratic form and setting equal to zero I get \begin{align} 0 &= \sum_i \mathbb{E} \left( \mathbf{x}^{(i)} - \mu - \Lambda \mathbf{z}^{(i)} \right)^T \Psi^{-1} \\ &= \sum_i \left( \mathbf{x}^{(i)} - \mu - \Lambda \mu_{z^{(i)}|x^{(i)}}\right)^T\Psi^{-1}, \end{align} then you can write this system as \begin{align} \sum_i (\mathbf{x}^{(i)} - \mu) &= \sum_i \Lambda \mu_{z^{(i)}|x^{(i)}} \\ &= \sum_i \Lambda \Lambda^{T}\left( \Lambda \Lambda^T + \Psi \right)^{-1} (\mathbf{x}^{(i)} - \mu) \end{align} or $$ \mathbf{y} = \Lambda \Lambda^{T}\left(\Lambda \Lambda^T + \Psi \right)^{-1} \mathbf{y}. $$ Now let $C = \Lambda \Lambda^T$, then $$ \left(C (C + \Psi)^{-1} - I \right) \mathbf{y} = \mathbf{0}, $$ has only the trivial solution $\mathbf{y} = \mathbf{0}$ if $\mbox{det}(C (C+\Psi)^{-1} - I) \neq 0$, but $$ \begin{align} C(C+\Psi)^{-1} - I &= C(C+\Psi)^{-1} - (C+\Psi)(C+\Psi)^{-1} \\ &= \left( C - C +\Psi \right) \cdot (C + \Psi)^{-1} \\ &= \Psi \cdot (C+\Psi)^{-1}, \end{align} $$ and presumably at some point previously we have made the assumption that we have a nonsingular covariance matrix so that $\mbox{det}(\Psi) \neq 0$. Therefore the only solution is the trivial one and we can conclude that $$ \sum_i \mathbf{x}^{(i)} - N \mathbf{\mu} = \mathbf{0}. $$
{ "pile_set_name": "StackExchange" }
Q: Is this a bug in dotnet Regex-Parser? I just wrote a regexp to do a basic syntax checking if a string is a valid math formular. I just define a group of valid chars and check if a string matches (I shortend the regex a little: private static readonly String validFormuar = @"^[\d\+-\*\/]+$"; private static bool IsValidFormular(String value) { return Regex.IsMatch(value, validFormuar); } I will only allow digits, +, -, * and / in this example. Because +,* and / are special chars in regular expressions I escaped them. However this code throws an ArgumentException (translated from german) "^[\d\+-\*\/]+$" is beeing analyzed - [x-y]-area in reversed Order. If I double escape the * private static readonly String validFormuar = @"^[\d\+-\\*\/]+$"; the result is as expected. Is this a bug in the System.Text.RegularExpressions parser? Because I consider my first regexp as correct. If not, why do I have to escape the "*" twice? A: I think you'll find "-" is a special character in regexes as well (at least within the "[]" bits). It specifies a range of characters, as in "[0-9]" meaning and of "0123456789". The reason your second one works but your first doesn't is because: + comes after * (error in range). + comes before \ (no error in range). To clarify, your second regex (@"^[\d\+-\\*\/]+$") actually means: "\d" ; or "\+" thru "\\" (quite a large range, including digits and uppercase letters) ; or "*" ; or "\/" Although it compiles, it's not what you want (because of that second bullet point). I'd try this instead: @"^[\d\+\-\*\/]+$" A: With @"" strings, you don't have to double-escape. In your sample, you also forgot to escape the "-". So the correct one would be: @"^[\d\+\-\*\/]+$" On the other hand, when inside [], you don't need to escape those (only "-"): @"^[\d+\-*/]+$"
{ "pile_set_name": "StackExchange" }
Q: Strange behaviour in for loop with System.Threading.Tasks I'm creating System.Threading.Tasks from within a for loop, then running a ContinueWith within the same loop. int[,] referencedArray = new int[input.Length / 4, 5]; for (int i = 0; i <= input.Length/4; i += 2048) { int[,] res = new int[input.Length / 4, 5]; int[,] arrayToReference = new int[input.Length / 4, 5]; Array.Clear(arrayToReference, 0, arrayToReference.Length); Array.Copy(input, i, arrayToReference, 0, input.Length / 4); Task<Tuple<int[,], int>> test = Task.Factory.StartNew(() => addReferences(arrayToReference, i)); test.ContinueWith(t => { Array.Copy(t.Result.Item1, 0, referencedArray, t.Result.Item2, input.Length / 4); MessageBox.Show("yai", t.Result.Item2.ToString()); }); Array.Copy(res, 0, referencedArray, i, input.Length / 4); where the addReference sbroutine is: public Tuple<int[,],int> addReferences(int[,] input, int index) { for (int i = 0; i < 2048; i++) { for (int j = 0; j < i; j++) { if ((input[i, 0] == input[j, 0]) && (input[i, 1] == input[j, 1]) && (input[i, 2] == input[j, 2]) && (input[i, 3] == input[j, 3])) { input[i, 4] = (j - i); } } } } return new Tuple<int[,],int>(input,index); } However, I am getting really strange results: 1.The index (generated from the loop counter when the task is started) somehow becomes too large. I initially thought that this was because the loop counter had incremented past its maximum, stopping the loop, but when the continueWith executed it used the new value. However, even when I send the loop counter's value to the task as index when it starts, the error persists. Edit: Solved I made I mistake in the original count 2.For some reason fewer than expected tasks are actually completed (e.g. even though 85 tasks are expected to be created, based on a loop counter maximum of 160,000 divided by a iteration of 2,048 = 78, only 77 pop ups appeared) - Edit Checking the console, it's apparent that the loop counter got up until about 157,696 before suddenly stopping. I'm really confused by Tasks and Threading, so if you could be of any assistance that would be really useful - thanks in advance. Edit I've made the changes suggested by Douglas, which solved my first problem - I'm still stuck on the second. A: This might not completely resolve the issues you're having, but as a starting point, you need to avoid the closure issue by copying your loop counter to an inner variable before referencing it in your anonymous method: for (int i = 0; i <= input.Length/4; i += 2048) { // ... int iCopy = i; var test = Task.Factory.StartNew(() => addReferences(arrayToReference, iCopy)); // ... } See Jon Skeet's answer (particularly the linked article) for an explanation of why this is necessary. Edit: Regarding your second problem, I suspect it might have to do with integer division. What is the value of input.Length for which you're expecting 85 iterations? You say that 174,000 divided by 2,048 should give 85, but in practice, it will give 84, since integer division causes results to be truncated. Edit2: Another reason you're not seeing all expected iterations could be that your program is terminating without waiting for the tasks (which typically execute on background threads) to complete. Check whether waiting on the tasks resolves your issue: List<Task> tasks = new List<Task>(); for (int i = 0; i <= input.Length/4; i += 2048) { // ... var test = Task.Factory.StartNew(() => addReferences(arrayToReference, iCopy)); tasks.Add(test); // ... } Task.WaitAll(tasks);
{ "pile_set_name": "StackExchange" }
Q: Fade background from right to left I managed with the help of the ScrollMagic library to change my background img for my section three-section-container depending on scroll position. Additionally, I managed to add an overlay that will appear only when I am on a certain section of my page. My issue now is that I would like to animate how background image changes (I want to come from right to left and stay positioned in the middle/ as you can see in code the background is changing 2 times). I tried with `transform: translateY(40px); property in CSS but the result was inconsistent because the image would not be 100% of my screen. Also, I want my overlay to come from left to right, and I am quite confused how. HTML <div id="bigSection" class="three-section-container "> <div id="target-overlay" class=" "></div> <div class="sec1 " id="project01"></div> <div class="sec2 " id="project02"></div> <div class="sec3" id="project03"></div> </div> CSS .three-section-container{ position: relative; background-color: black; transition: all 3s ease; background-image: url('../../Assets/Images/graphic/last/poza-augmented-reality.png'); background-repeat: no-repeat; background-color: black; background-size: 100% 100vh; background-attachment: fixed; } .fade-img1{ transition: all 1s ease; background-image: url('../../Assets/Images/graphic/last/poza-augmented-reality.png'); background-repeat: no-repeat; background-color: black; background-size: 100% 100vh; background-attachment: fixed; // transform: translatey(20px); opacity: 1; margin: 0; z-index: 999; } .fade-img2{ background-image: url('../../Assets/Images/graphic/last/2.png'); background-repeat: no-repeat; background-color: black; background-size: 100% 100vh; background-attachment: fixed; opacity: 1; transition: all 1s ease; margin: 0; z-index: 999; } .fade-img3{ background-image: url('../../Assets/Images/graphic/last/poza-interior.png'); background-repeat: no-repeat; background-color: black; background-size: 100% 100vh; background-attachment: fixed; // transform: translateY(40px); opacity: 1; transition: all 0.3s ease; margin: 0; z-index: 999; } .sec1, .sec2, .sec3{ height: 100vh; } .overlay { transition: 0.3s linear all; position: absolute; /* Sit on top of the page content */ width: 40%; /* Full width (cover the whole page) */ height: 100%; /* Full height (cover the whole page) */ top: 0; left: 0; right: 0; background-color: rgba(0, 0, 0, 0.5); /* Black background with opacity */ z-index: 999; /* Specify a stack order in case you're using a different order for other elements */ } JS $(document).ready(function(){ var controller=new ScrollMagic.Controller() // build a scene var ourScene= new ScrollMagic.Scene({ triggerElement:'#project01', duration:"100%" }) .setClassToggle('#bigSection', 'fade-img1') .addIndicators({ name:'fade scene', colorTRigger:'black', indent:200, colorStart:'#75c695' }) .addTo(controller) var ourScene= new ScrollMagic.Scene({ triggerElement:'#project02', duration:"100%" }) .setClassToggle('#bigSection', 'fade-img2') .addIndicators({ name:'fade scene', colorTRigger:'black', indent:200, colorStart:'#75c695' }) .addTo(controller) var ourScene= new ScrollMagic.Scene({ triggerElement:'#project03', duration:"200%" }) .setClassToggle('#bigSection', 'fade-img3') .addIndicators({ name:'fade scene', colorTRigger:'black', indent:200, colorStart:'#75c695' }) .addTo(controller) var ourScene= new ScrollMagic.Scene({ triggerElement:'#project01', // duration:"200%" }) .setClassToggle('#target-overlay', 'overlay') .addIndicators({ name:'overlay', colorTRigger:'black', indent:200, colorStart:'#75c695' }) .addTo(controller) }) Any help is welcomed. Thank You A: I'm not familiar with the ScrollMagic API but i think this code snippet can make things a little cleared from the JS and CSS prospective involved in the animation. Infact most of them can be done without the need of externals API but just triggering back an forth a CSS class ! Hope this helps you a little bit: let animationDone = false; window.addEventListener("scroll", () => { /* * IF you scrolled more than a certain ammount: * in this case i choose half a page height's (50vh), * you trigger the slide animation by adding the onscreen class to the background2 div. * Otherwise if you previously triggered the animation and * you scrolled in the opposite direction: the animation is triggered backwards. */ if(window.scrollY > window.innerHeight / 2) { document.getElementsByClassName("background2")[0].classList.add("onscreen"); document.getElementById("secondPage").classList.add("onscreen"); animationDone = true; //We makes sure that we always know the state of our animation } else if(animationDone) { document.getElementsByClassName("background2")[0].classList.remove("onscreen"); document.getElementById("secondPage").classList.remove("onscreen"); animationDone = false; //We makes sure that we always know the state of our animation } }, {passive:true}); body { color:white; margin: 0; width:100vw; height:200vh; /* 200vh is only for demo purposes: it allows to scroll the html body even thought there's nothing inside */ } #mainContent { text-align: center; z-index: 99; position: absolute; } #mainContent > * { display: flex; justify-content: center; align-items: center; } #firstPage { width: 100vw; height: 100vh; } #secondPage { width: 100vw; height: 100vh; opacity: 0; /* This makes our background2 div transparent as soon as its hidden */ transform: translateX(-100vw); /* This shifts our background to the left by 100vw (its width) */ transition: 1s; /* The page content animation's duration */ } #secondPage.onscreen { /* * This cancels the second page's previous shift (to left) when the onscreen class is applied to secondPage div * in 0.3s so that it won't snap-> the left to right transition is realized ! */ transform: translateY(0); opacity: 1; /* This makes our background2 fades from transparent (its original state) to opaque */ } .background1 { z-index: 1; /* Lower stacking index than the other background to hide it */ position: fixed; width: 100vw; height: 100vh; background: red; } .background2 { z-index: 2; /* Higher stacking index than the other background to show it*/ position: fixed; width: 100vw; height: 100vh; background: blue; opacity: 0; /* This makes our background2 div transparent as soon as its hidden */ transform: translateX(100vw); /* This shifts our background to the right by 100vw (its width) */ transition: 0.3s; /* The background2 animation's duration */ } .background2.onscreen { /* * This cancels the background's previous shift when the onscreen class is applied to background2 * in 0.3s so that it won't snap-> the right to left transition is realized ! */ transform: translateY(0); opacity: 1; /* This makes our background2 fades from transparent (its original state) to opaque */ } <body> <div id = "mainContent"> <h1 id = "firstPage">The main content goes here</h1> <h1 id = "secondPage">Animation Triggered !</h1> </div> <div class = "background1"></div> <div class = "background2"></div> </div> </body>
{ "pile_set_name": "StackExchange" }
Q: Looping over pandas DataFrame I have a weird issue that the result doesn't change for each iteration. The code is the following: import pandas as pd import numpy as np X = np.arange(10,100) Y = X[::-1] Z = np.array([X,Y]).T df = pd.DataFrame(Z ,columns = ['col1','col2']) dif = df['col1'] - df['col2'] for gap in range(100): Up = dif > gap Down = dif < -gap df.loc[Up,'predict'] = 'Up' df.loc[Down,'predict'] = 'Down' df_result = df.dropna() Total = df.shape[0] count = df_result.shape[0] ratio = count/Total print(f'Total: {Total}; count: {count}; ratio: {ratio}') The result is always Total: 90; count: 90; ratio: 1.0 when it shouldn't be. Thank you in advance A: Found the root of the problem 5 mins after posting this question. I just needed to reset the dataFrame to the original to fix the problem. import pandas as pd import numpy as np X = np.arange(10,100) Y = X[::-1] Z = np.array([X,Y]).T df = pd.DataFrame(Z ,columns = ['col1','col2']) df2 = df.copy()#added this line to preserve the original df dif = df['col1'] - df['col2'] for gap in range(100): df = df2.copy()#reset the altered df back to the original Up = dif > gap Down = dif < -gap df.loc[Up,'predict'] = 'Up' df.loc[Down,'predict'] = 'Down' df_result = df.dropna() Total = df.shape[0] count = df_result.shape[0] ratio = count/Total print(f'Total: {Total}; count: {count}; ratio: {ratio}')
{ "pile_set_name": "StackExchange" }
Q: please help me for loop c++ i don't to run it i can't to write a code to for loop c++ I want it to be 1 21 321 4321 But I do not write that way. #include <iostream> using namespace std; int main() { int num; cin>>num; for(int i=1;i<=num;i++) { for(int j=1;j<=i;j++) { cout<<j; } cout<<endl; } cin.get(); } it outputs: 1 12 123 1234 12345 123456 1234567 12345678 123456789 A: Just change your second loop like this: for(int j=i; j>=1; j--) and it will work. DEMO
{ "pile_set_name": "StackExchange" }
Q: How to open a network folder from a Mac in an Adobe Air application? I've got an Air application that needs to reference files located in a shared network folder. From within the Air application running on Windows I can access the share through a File object as follows: var folder:File = new File("file:///\\\\server\\share\\parent_folder\\folder"); On a Mac, that doesn't work, and I can't find any variation on the path that does. I can connect to the server through the Finder using the path "smb://server/share/parent_folder/folder", and then I can construct a File object through some (seemingly) convoluted volume mount with a name that seems to vary depending on how many existing mounts there are to "//server/share" (e.g., "/Volumes/share", "/Volumes/share-1", etc.) Is there a way from within an Air application to connect to a shared server folder on a Mac, without the user needing to connect through the Finder first? Worst case, is there a way to execute a console command from within Air? Presumably I could then mount the share myself. I can't think of a work-around other than requiring Mac users to first manually connect to the server through the finder, then supply the app with the share path every time they run the app! Thanks in advance for any workable solution! A: If I remember correctly, you have to mount the network path. But a user can mount a network drive and have it reconnect automatically when the user logs in so they don't have to reconnect every time they use your app. Take a look at http://osxdaily.com/2010/09/20/map-a-network-drive-on-a-mac/ which has instructions for automatically connecting.
{ "pile_set_name": "StackExchange" }
Q: Let $y$ be real, $n$ is natural, and $\varepsilon>0$. For some $\delta>0$, if $u$ is real and $|u-y|<\delta$, then $|u^{n}-y^{n}|<\varepsilon$ I've almost got this problem solved, and I need a(some) pointer(s) as to finishing this problem up (which will be greatly appreciated [!]). Here is the full, problem statement in its exact form. Problem: Given $y\in\mathbb{R}$, $n\in\mathbb{N}$, and $\varepsilon>0$, show that for some $\delta>0$, if $u\in\mathbb{R}$ and $|u-y|<\delta$ then $|u^{n}-y^{n}|<\varepsilon$. Preliminary Notes/Work: Now, the question additionally provides a hint to prove the inequality for $n=1$ and $n=2$, then to use induction on $n$ and use the identity of $u^{n}-y^{n}=(u-y)(u^{n-1}+yu^{n-2}+\cdots+y^{n-2}u+y^{n-1})$. I've made it as far as defining the induction hypothesis for some $n$ and I've used the identity to work the inequalities in order to show the statement holds for $n$, but I can't find a way out from there. So, proceeding by induction, we have for the case when $n=1$ that we can simply let $\delta=\varepsilon$. Then, letting $y\in\mathbb{R}$, and taking $\varepsilon>0$, let $\delta=\varepsilon>0$. When $u\in\mathbb{R}$ this implies that when $|u-y|<\delta=\varepsilon$, then clearly $|u^{1}-y^{1}|=|u-y|<\varepsilon$. For the case when $n=2$, we let $\delta=\min\bigg\{1,\dfrac{\varepsilon}{2|y|+1}\bigg\}$. Now, when $u\in\mathbb{R}$ and $|u-y|<\delta$, then $|u-y|<1$ in particular. Further, by the Reverse Triangle Inequality, we then have that $|u|-|y|\leq |u-y|<1$. Adding $|2y|$ to both sides yields that $|u|+|y|\leq |u-y|+|2y|<1+|2y|$. Again by the Triangle Inequality we have that $|u+y|\leq |u|+|y|<2|y|+1$, and so $|u+y|<2|y|+1$. We now compute $|u^{2}-y^{2}|=|u+y||u-y|<(2|y|+1)\dfrac{\varepsilon}{2|y|+1}=\varepsilon$. Thus, the result hold also when $n=2$, and we can conclude the base case holds. For the inductive hypothesis we have that for $y\in\mathbb{R}$, $n-1\in\mathbb{N}$, and $\varepsilon>0$, there is some $\delta>0$ such that if $u\in\mathbb{R}$ and $|u-y|<\delta$ then $|u^{n-1}-y^{n-1}|<\varepsilon$. We need to show this result holds for $n$. I've been messing around with this, and I keep getting nowhere. We have that when $|u-y|<\delta$ then: $|u^{n}-y^{n}|=|u-y||u^{n-1}+yu^{n-2}+\cdots+y^{n-2}u+y^{n-1}|$ $~~~~~~~~~~~~~~~~\!<\delta|u^{n-1}+yu^{n-2}+\cdots+y^{n-2}u+y^{n-1}|$. I just need to find the $\delta$ in this case, and, at first, I wanted to let $\delta=\dfrac{\varepsilon}{u^{n-1}+yu^{n-2}+\cdots+y^{n-2}u+y^{n-1}}$, but (I think) the problem statement asserts that $\delta$ can't depend on $u$, or can it? If it can, then I'm done...but if not , which $\delta$ will work? Please note, this problem is a homework problem, and if one decides not to provide a solution (which I completely understand), then please provide suggestions, recommendations, hints, etc. I figured since I'm almost done with the problem, providing a solution wouldn't hurt, but anything will be GREATLY appreciated! Thank you for your time reading this. A: The way you're trying to do it doesn't require induction $\delta$ can't depend on $u$ but it can depend on $y$. Note that $|u|<|u-y|+|y|<|y|+\delta$. $$ \Big{|}\sum_{j=0}^{n-1}y^ju^{n-1-j}\Big{|}<\sum_{j=0}^{n-1}|y|^j|u|^{n-1-j}<\sum_{j=0}^{n-1}|y|^{j}(|y|+\delta)^{n-1-j}={(|y|+\delta)^{n}-|y|^{n}\over\delta} $$ So we want to have $$\delta{(|y|+\delta)^{n}-|y|^{n}\over\delta}<\varepsilon \implies (|y|+\delta)^{n}<{\varepsilon}+|y|^n\\ \implies\delta<\left({\varepsilon}+|y|^n\right)^{1\over n}-|y|=:K$$ So picking $\delta=0.5K$ suffices. The inductive way $$|u^{n}-y^n|=|(u^{n-1}-y^{n-1})(u+y)+uy^{n-1}-yu^{n-1}|\\<|u^{n-1}-y^{n-1}||u+y|+|uy||y^{n-2}-u^{n-2}|$$ Now there exists $\delta_1,\delta_2>0:|u^{n-1}-y^{n-1}|<{0.5\varepsilon\over2|y|+1}$ whenever $|u-y|<\delta_1$ and $|u^{n-2}-y^{n-2}|<{0.5\varepsilon\over|y|(|y|+1)}$ whenever $|u-y|<\delta_2$. If we pick $0<\delta<\min\{\delta_1,\delta_2,1\}$ those inequalities still hold if $|u-y|<\delta$, moreover we have $|u|<|y|+\delta<|y|+1$. So $$ |u-y|<\delta\implies|u^{n}-y^n|<0.5\varepsilon{|u+y|\over2|y|+1}+0.5\varepsilon{|u||y|\over|y|(|y|+1)}\\<0.5\varepsilon{|u|+|y|\over2|y|+1}+0.5\varepsilon{|u|\over(|y|+1)}<0.5\varepsilon+0.5\varepsilon=\varepsilon $$ Book's method(?) $$ |u^{m-j}y^{j}+u^jy^{m-j}|=|u|^j|y|^j|u^{m-j}+y^{m-j}|<|u|^j|y|^j(|u^{m-j}-y^{m-j}|+2|y|^{m-j}) $$ For $j=0,1,..,n-1$ we can find $\delta_j>0:|u^{n-1-j}-y^{n-1-j}|<{1\over n\{(|y|+1)|y|\}^j}$ whenever $|u-y|<\delta_j$. Pick $0<\delta<\min(\{\delta_j:0\le j\le n-1\}\cup\{1\})$. $$ |u-y|<\delta\implies|u^n-y^n|<\delta\Big{|}\sum_{j=0}^{n-1}u^{n-1-j}y^j\Big{|}<\delta\sum_{j=0}^{\lfloor {n\over 2}\rfloor}|u^{n-1-j}y^j+y^{n-1-j}u^j|\\ <\delta\sum_{j=0}^{\lfloor {n\over 2}\rfloor}(|u||y|)^j\left({1\over n\{(|y|+1)|y|\}^j}+2|y|^{n-1-j}\right)\\ <\delta\sum_{j=0}^{\lfloor {n\over 2}\rfloor}\left({1\over n}+2|u|^j|y|^{n-1}\right) $$ Now $$\sum_{j=0}^{\lfloor {n\over 2}\rfloor}|u|^j|y|^{n-1}<|y|^{n-1}\sum_{j=0}^{\lfloor {n\over 2}\rfloor}(|y|+1)^j=:S$$ Therefore $$ |u^n-y^n|<\delta\left({{\lfloor {n\over 2}\rfloor}+1\over n}+2S\right)<\delta(1+2S) $$ So picking $0<\delta<\min(\{\delta_j:0\le j\le n-1\}\cup\{1,{\varepsilon\over1+2S}\})$ suffices.
{ "pile_set_name": "StackExchange" }
Q: winusb device driver application not being executed I am developing WinUSB application which does basic reads through Interrupt endpoint with a generic USB device. The device driver has installed fine. But the applications t_main function is not being triggered at all when the device connects. It gets triggered ONLY in visual studio debugger and works fine. What am i missing here? Winusbtrace detects the device and logs entry and exit of WinUSB_InitControlPipe and WinUSB_DOEntry. Logs in Windows/inf/*.log are not helpful as they log only installs. Any other log I can refer to ? I would really appreciate any inputs. Thanks in advance. Below is my INF file and I am using visual studio 2013 on Win 7 x64 ; ; Test.inf ; ; Installs WinUsb ; [Version] Signature = "$Windows NT$" Class = USBDevice ClassGUID = {88BAE032-5A81-49f0-BC3D-A4FF138216D6} Provider = %ManufacturerName% CatalogFile=Test.cat ; ========== Manufacturer/Models sections =========== [Manufacturer] %ManufacturerName% = Standard,NT$ARCH$ [Standard.NT$ARCH$] %DeviceName% =USB_Install, USB\VID_0457&PID_0500 ; ========== Class definition =========== [ClassInstall32] AddReg = ClassInstall_AddReg [ClassInstall_AddReg] HKR,,,,%ClassName% HKR,,NoInstallClass,,1 HKR,,IconPath,%REG_MULTI_SZ%,"%systemroot%\system32\setupapi.dll,-20" HKR,,LowerLogoVersion,,5.2 ; =================== Installation =================== [USB_Install] Include=winusb.inf Needs=WINUSB.NT [USB_Install.Services] Include=winusb.inf AddService=WinUsb,0x00000002,WinUsb_ServiceInstall [WinUsb_ServiceInstall] DisplayName = %WinUsb_SvcDesc% ServiceType = 1 StartType = 3 ErrorControl = 1 ServiceBinary = %12%\WinUSB.sys [USB_Install.HW] AddReg=Dev_AddReg [Dev_AddReg] ; By default, USBDevice class uses iProduct descriptor to name the device in ; Device Manager on Windows 8 and higher. ; Uncomment for this device to use %DeviceName% on Windows 8 and higher: ;HKR,,FriendlyName,,%DeviceName% HKR,,DeviceInterfaceGUIDs,0x10000,"{2753294b-5128-4a42-be6a-d7818234ea9c}" [USB_Install.Wdf] KmdfService=WINUSB, WinUsb_Install [WinUsb_Install] KmdfLibraryVersion=1.9 [USB_Install.CoInstallers] AddReg=CoInstallers_AddReg CopyFiles=CoInstallers_CopyFiles [CoInstallers_AddReg] HKR,,CoInstallers32,0x00010000,"WdfCoInstaller$KMDFCOINSTALLERVERSION$.dll,WdfCoInstaller" [CoInstallers_CopyFiles] WdfCoInstaller$KMDFCOINSTALLERVERSION$.dll [DestinationDirs] CoInstallers_CopyFiles=11 ; ================= Source Media Section ===================== [SourceDisksNames] 1 = %DiskName% [SourceDisksFiles] WdfCoInstaller$KMDFCOINSTALLERVERSION$.dll=1 ; =================== Strings =================== [Strings] ManufacturerName="Test" ClassName="Universal Serial Bus devices" DiskName="Device Installation Disk" WinUsb_SvcDesc="WinUSB Driver" DeviceName="Test Device" REG_MULTI_SZ = 0x00010000 A: The winusb application is not a driver. You have to tell it when to run. If you are trying to get the application to run when the device is plugged in, you can attempt to bind the application to the connection event described in this post: https://superuser.com/questions/219401/starting-scheduled-task-by-detecting-connection-of-usb-drive
{ "pile_set_name": "StackExchange" }
Q: Did the events of First Contact create the Prime Universe? In the Enterprise episode "In a Mirror Darkly", the Mirror Universe's First Contact is shown with the Vulcans acting normally, but Zefram Cochrane pulling a shotgun on them and boarding their ship. The future Enterprise crew (under Picard) are nowhere to be seen. In First Contact, Cochrane tells Riker (taken from IMDB) You wanna know what my vision is? Dollar signs, money! I didn't build this ship to usher in a new era for humanity. You think I wanna see the stars? I don't even like to fly! I take trains! I built this ship so I could retire to some tropical island... filled with [smirks] Dr. Zefram Cochrane: naked women. THAT'S Zefram Cochrane. THAT'S his vision. This other guy you keep talking about, this historical figure? I never met him. I can't imagine I ever will. By the end of the film, Cochrane seems to have been changed, and proves his worth as a great scientist, restoring the original timeline. However, if the Borg and the Enterprise had never been there, would Cochrane have robbed the Vulcans - as shown in the Mirror Universe? This would mean that the Prime Universe is really just an alternate timeline of the Mirror Universe, created by a predestinaton paradox set in motion by the Enterprise-E. Is this possible, or would this contradict existing canon? A: No, because if the mirror universe did split off from the prime universe, it did so centuries ago. Shakespeare's plays over in the mirror universe are different than in the prime universe (cite: ENT: In a Mirror, Darkly, Part 2), so the split would have to be prior to that point in time. By the time of First Contact, they'd been different for a long time. It's worth noting that since that information comes from Enterprise, it's true for both the Prime and 2009 film's timelines. A: Short answer: probably not. But maybe. But probably not. From memory-alpha: Dating divergence The credits sequence for the mirror universe Star Trek: Enterprise television series used footage of battles going back at least to the "Age of Sail". The mirror Phlox noted that the "great works" of literature in both universes were roughly the same, except that their characters were "soft and weak" (except for Shakespeare), pushing back the earliest possible date for a divergence to the 16th century. In mirror-Archer's deleted speech from "In a Mirror, Darkly, Part II", he invokes the favor of the "gods." This, together with Marlena Moreau's statement about "being the woman of a Caesar", in "Mirror, Mirror", suggests that the Terran Imperial tradition extends at least back to ancient Rome. However, given the nature of the mirror universe, these statements should be taken with a grain of salt. Apocrypha The existence of a "point of divergence" from the traditional Star Trek universe has not been confirmed, though according to the novel Fearful Symmetry, the mirror universe is in fact a parallel quantum universe, as quantum signature scans used to match Worf with his USS Enterprise-D in TNG: "Parallels" were also able to differentiate natives of the mirror universe from those of the prime reality. This suggests that even though the two universes were always separate, they shared a similar past up to some point in their history. According to the FASA role-playing games and The Best of Trek, the mirror universe diverges from the prime timeline around the Eugenics Wars, while DC Comics' The Mirror Universe Saga comics speculate the Earth-Romulan War was the point of divergence, with Earth having lost that war, and then embarking on a policy of conquest after overthrowing the Romulans (it is not known what kind of contact Sato's Empire had with the Romulans). Still other works, the novels of William Shatner's Star Trek: The Mirror Universe Trilogy (co-written with Judith and Garfield Reeves-Stevens) and the novelization of Star Trek: First Contact seem to indicate that time travel of the Borg to Zefram Cochrane's era might be responsible. This explanation would tie in with ENT: "In a Mirror, Darkly" when the Vulcans first arrived and were killed by Cochrane. Dark Mirror, a Pocket TNG novel by Diane Duane, places the mirror universe as parallel since at least the end of Homer's Iliad, where the mirror universe parallel of Achilles kills old King Priam after the death of Hector when asked to return Hector's body for funeral rites, instead of showing one moment of Humanity. Picard thought that that moment in the original prime universe version as the one time in the poem when "that terrible man showed mercy... but not here." After this there seems to be some sort of "moral inversion". For instance, according to Plato the perfect government is now one in which fear is meted out to the people in proper proportion by a wise ruler. Picard notes that the ending of Shakespeare's Merchant of Venice is drastically different: Shylock is awarded, and accepts, the owed pound of flesh.
{ "pile_set_name": "StackExchange" }
Q: How to dynamically create partial views I have a table in my database called Programs. I want to display a tab for each program .I am trying to create a partial view to do this and then I want to include the partial view to every view that will need to have those tabs. My partial view looks like below. <div id="tabs"> <ul> <li id="HomeTab">@Html.ActionLink("Dashboard", "Index", "Home")</li> <li id="Program1Tab">@Html.ActionLink("Program1", "Index", "Program")</li> <li id="Program2Tab">@Html.ActionLink("Program2", "Index", "Program")</li> </ul> </div> I am hoping to dynamically create the tabs using something like @foreach (var ptype in Model) { <li id=\"@ptype.Name\"Tab>@Html.ActionLink(ptype.Name, "Index", "Project")</li> } however I am wondering how I can load the tabs without using a controller. Can I use a helper class/method to directly access the model bypassing the controller? update: I also tried by creating a helper method namespace MyProject.Helpers { public class ProgramTypes { public static List<ProgramType> ProgramTypesList() { MyDbContext db = new myDbContext(); return db.ProgramTypes.ToList<Programtype>(); } } } and then accessing them using @foreach (var ptype in MyProject.Helpers.ProgramTypes.ProgramTypesList()) however i am not sure if this is the correct thing to do. A: The best solution is - passing collection of programs to your view @model IQueyrable<Program> <div id="tabs"> <ul> @foreach (var ptype in Model) { <li>@Html.RenderPartial("ProgramTab", ptype)</li> } </ul> </div> so you have to create another partial view where you will display program details. If you want organize this like tabs you should use something like jquery tabs you don't have to use actionlink just RenderPartial or RenderAction
{ "pile_set_name": "StackExchange" }
Q: Which fast growing evergreen will provide the most privacy from the road? There is a ravine behind our house (much of which is our property) with a busy road behind it. The ravine is home to many big leaf maples, alders, and shrubs, with a creek at the bottom. When the trees lose their leaves, the noise from the road carries into our backyard, and you can see cars driving by. The yard and ravine are east/south east facing. This is in Delta, BC, Canada. Which evergreen(s) will grow quickly to a large size, and provide a thick canopy to block the view and noise from the road? Ideally it would also have an extensive root system to help prevent erosion on the slope. Note that this will not be a hedge, as they will need to be quite tall to fully obstruct the view from the road, and the topography does not allow for planting in a straight line. The property is already home to a western redcedar and a beautiful old Atlas cedar, both of which appear healthy and mature. A: Delta, BC is a region known for its fertile soil, as it is in the floodplain of the Fraser River system. I am assuming this being on a slope it is well draining, unlike much of Delta which is standing water 1/2 of the year. If it is wet, you will be somewhat limited to your choices, but if it’s well drained you do have a nice selection of trees available for sale in that region that can fit the bill. Conifers Thuja plicata, Western Red Cedar. You already know this tree grows well at your location. It is native to that region and grow quite fast, easily up 3’ or more a year. Sequoiadendron giganteum, Giant Sequoia, native to Seirra Nevada mountain range in California. It is an extremely fast growing tree up to 4’ or more a year, as long as the soil is well drained. Cryptomeria japonica, Japanese Cedar, native to Japan. It comes in many forms. The fastest grower and fullest is in its natural variety. But, not as fast as the first two. Pseudotsuga menziesii, Douglas Fir, a native to most of BC. It can take root and grow at an extreme rate. These are often in BC as both cut and living Christmas Trees. You might be able to get a deal after Christmas for some of the unsold living Christmas trees. This tree can grow 2-3’ in a year. Abies grandis, Grand Fir, also a native to BC. It is not as fast growing as the Douglas Fir, also not as easy to find at the garden centre and will be considerably more expensive. Cupressus × leylandii, Leyland Cypress, can easily grow more than 3’ a year in BC. It does never very well drained soil, but this and the Western Red Cedar are used most for fast growing privacy. They will not look as full when you buy it, because it gets taller faster than it does get wider when young. For non-confiers you can try; Prunus laurocerasus, English Laurel, once established it can grow 2-3’ a year. Prunus lusitanica, Portuguese Laurel, once established can grow 1-2’ a year. Laurus nobilis, Bay Laurel or Sweet Bay, once established can grow 1-3’ a year. It will may need protection from cold winds when young. Needs well drained soil. Myrica californica, California Wax Myrtle, is also native to BC. It can easily grow 2-3’ in one year. (I ran the nursery at one of the GardenWorks on the Island for many years.)
{ "pile_set_name": "StackExchange" }
Q: Reverse engineering website : cannot find the form inputs in the post request I need to interact with an external website I don't own. This external website requires credentials that I have. My goal is to add a user but the external website does not offer an external API. It looks like they are using Vaadin. So to add a new user I need to manually fill in a form. Yet I have been searching for the route the "form" takes to post the input I give but could not find any. Here is my issue : when I look at the HTML source code in browser I cannot see any form tag. The buttons have all the same id "button". When I fill in the form and look at the network tab in the developer tools, in the "parameters" section I cannot see the inputs I just gave although the POST request does appear. The cookies tab does not show the inputs either. Consequently my questions are : why can't I find the inputs in the POST request and where can they be ? Please note : this external website is a medical site so I prefer not share the url and they don't offer a mobile app, so there is no mobile API I could reverse engineer. Any help appreciated :-) A: Not stating the Vaadin version makes that a tad harder give an exact answer, but at the core both the Vaadin 8 and 10+ behave the same way. And the short answer to your question is: without another entry-point, like an API, this can not simply be done using just some POST-Request. Vaadin is not simply a html-form/request/response-html based framework; it holds the scenegraph on the serverside in a session. All communication is done via a single endpoint to the server and state changes only are communicated back to the client. For what you are after, your best bet is to use test automation frameworks like selenium, geb, cypress, ...
{ "pile_set_name": "StackExchange" }
Q: Scalability 1-way. What does it mean? I have read "Scalability: 1-way" in the specifications of a server. What does it means? The server is : HP ProLiant ML110 G6 TV X3430 2.40GHz 4-core 1P 1GB-U Non-hot Plug 250GB SATA LFF 300W PS A: In old Compaq vernacular the number of CPU sockets was traditionally referred-to as "1-way" for single socket, "2-way" for dual socket, "4-way", etc. I suspect that you're looking at a machine with a single CPU socket.
{ "pile_set_name": "StackExchange" }
Q: Want to write simple program to compare excel CSV's. Outputting to another CSV. Is Java or C++ recommended? as the title suggests, I am trying to determine which language would better suit for the task at hand. I am probably going to include a GUI for the program. Am I okay to proceed with Java for this task or is another language recommended? Thanks A: I can't speak on the pros or cons of writing such a program in C++. However, Java seems well suited to accomplish your task.
{ "pile_set_name": "StackExchange" }
Q: Page load using window.location in turbolinks-ios I am using turbolinks-ios for builder ios app for my rails application. In my application, I am using window.location for loading particular page. On my ios application it is oping the browser instead of using app view. Does any one have idea how can I keep page loading on app view? A: Try Turoblinks.visit instead of window.location. // window.location.href = url; Turbolinks.visit(url);
{ "pile_set_name": "StackExchange" }
Q: Assigning a color according to a floating variable Let's say we have the following dataset: a b c s 1 10 s 2 20 ss 1 30 ss 2 40 We plot it like this: require(ggplot2) data <- read.table("data.stats", sep = "\t", header = TRUE) ggplot(data, aes(b, c, color=a)) + stat_summary(fun.y=median, geom="line") dev.off() And this is the result: However my actual dataset instead of strings for a contains floating numbers. So it might look like this: a b c 0.1 1 10 0.1 2 20 0.5 1 30 0.5 2 40 If I try to run the same code however, I get a straight line as an output. How to make R treat a as if the numbers are strings? A: > data.frame(a = c(0.1,0.1,0.5,0.5), b = c(1,2,1,2), c = c(10,20,30,40) ) %>% dplyr::mutate(a = as.character(a)) %>% ggplot(., aes(b, c, color=a)) + stat_summary(fun.y=median, geom="line")
{ "pile_set_name": "StackExchange" }
Q: The frog problem with negative steps Standard Problem description In this question The Frog Problem (puzzle in YouTube video) a frog has to jump from leaf to leaf on a row of leaves. And the question is how long it takes on average to reach the end. In that specific case the frog only jumps to the leaves in front of him with each leaf having equal probability. It is computed that the expectation value for the number of steps to reach the end is $J_n = \sum_{k=1}^n 1/k $, when the frog has $n$ leaves in front of him. New extended problem But what is the solution when the frog can also remain still and go one step backwards. (there are infinitely many leaves behind the frog, the game only ends when the frog has no leaves in front of him) This would lead to a recurrence relation like: $$J_{n} = (n+1) J_{n-1} - n J_{n-2}-1$$ To make the solution final we need to know $J_0$ and $J_1$. It is trivial that the expected number of steps for a frog with zero leaves in front of him is 0 ($J_0 = 0$). But what is $J_1$? What is the expected number of steps for a frog that has only one leaf to go? Derivation/intuition of the recurrence relation: $$J_{n+1} = (n+2) J_{n} - (n+1) J_{n-1}-1$$ There are $n+2$ leaves to go to. The $n$ leaves in front of the frog and the one leaf on which the frog is sitting is the same situation as the frog who has $n-1$ leaves in front of him/her. The one leaf backwards results in the frog being in the situation of a frog that has $n+1$ leaves in front of him/her but he took an extra step. $$J_{n} = \frac{n+1}{n+2} {J_{n-1}} + \frac{1}{n+2} {(J_{n+1}+1)}$$ Solution attempt 1 It seems like the solution is close to $J_n = c + \sum_{k=1}^n 1/k$ with some constant $c$... but not exactly. When I fill that expression into the recurrence relation then I get to: $$\begin{array}{rcl} J_{n} &=& (n+1) J_{n-1} - n J_{n-2}-1 \\ c + \sum_{k=1}^n \frac{1}{k} &=& (n+1) \left(c + \sum_{k=1}^{n-1} \frac{1}{k} \right) - n \left(c + \sum_{k=1}^{n-2} \frac{1}{k} \right) -1 \\ \sum_{k=1}^n \frac{1}{k} &=& (n+1) \left(\sum_{k=1}^{n-1} \frac{1}{k} \right) - n \left(\sum_{k=1}^{n-2} \frac{1}{k} \right) -1 \\ \frac{1}{n} + \frac{1}{n-1} &=& (n+1)\frac{1}{n -1} -1\\ \frac{1}{n} + \frac{1}{n-1} &=& \frac{2}{n -1} \\ \end{array}$$ which is a contradiction. Solution attempt 2 Simulation by Markov chain (this results into something that looks like $J_n = c + \sum_{k=1}^n 1/k$ but as shown before that can not be true.) nm <- 50 library(expm) for (n in 1:40) { # stochastic Matrix M <- pracma::Toeplitz(c(rep(1,nm+1)),c(1,1,rep(0,nm-1))) / c(2:(nm+2)) M[1,1:2] <- c(1,0) # positions of frogs after k steps V <- c(rep(0,n),1,rep(0,nm-n)) Vm <- sapply(0:nn, FUN = function(k) V %*% (M %^% k)) # mean number of steps by computing 1-F(0) E <- sum(1-Vm[1,]) ev[n] <- E } n <- 1:40 plot(n,ev,xlim=c(0,20)) title("simulated \n expected number of steps",cex.main=1) H <- cumsum(1/n) mod <- lm(ev-H~1) lines(n,H+coef(mod)[1]) coef(mod) legend(0,6.6, c("simulation","2.325547 + H_n") ,cex=0.7, lty=c(NA,1), pch = c(1,NA)) Jn <- ev[-c(1,2)] Jn1 <- ev[-c(1,40)] Jn2 <- ev[-c(39,40)] np <- n[-c(1,2)] plot(Jn, (np+1)*Jn1 - (np) * Jn2 -1, xlab = expression(J[n]), ylab = expression((n+1)%*%J[n-1]-n%*%J[n-2]-1 )) lines(c(0,10),c(0,10)) title("testing recurrence relation", cex.main=1) In this answer to the simpler solution. The motion of the frog is not computed by using the recurrence relation, but instead by writing down the probability distribution where the frog might be after $k$ jumps. In that case the distribution is like a diffusing wave, which will eventually be absorbed completely in the final leaf. In this case we can not compute it because there is a tiny number of frogs that will never reach the goal. But maybe we solve the puzzle with this starting point by finding some explicit solution or by changing the expression to include the backwards leaves? Written by StackExchangeStrike A: Solution for $J_1$ But what is J1? What is the expected number of steps for a frog that has only one leaf to go? The solution is $J_1 = 2(e-1)$ and other terms $J_n$ can be expressed as a sum. Rewriting the recurrence relation as a sum The recurrence relation is not gonna solve the problem entirely (because one term in the initial conditions is not known), but it does allow us to express $J_n$ as an expression in terms of a finite sum. The recurrence relation can be rewritten. (for n>3) $$J_n - J_{n-1} = n (J_{n-1} - J_{n-2})-1 $$ let $D_n = J_n - J_{n-1}$ $$D_n = n D_{n-1}-1 $$ and with starting point $D_2 = 2x $ and we can write (note the recurrence relation is a bit different for $n = 2$ as @quester noted in the comments): $$\begin{array}{rcrcrcrcrcr} D_1 &=& 3 + 2\,x \\\\ D_2 &=& 2\,x\\ D_3 &=& \overbrace{6 \,x}^{\times 3} &-&1\\ D_4 &=& \rlap{\overbrace{\hphantom{\begin{array}5040\,x&-&7\cdot 6\cdot 5\cdot 4 \end{array}}}^{\times 4}} 24\,x&-&4 &-& 1 \\ D_5&=& \rlap{\overbrace{\hphantom{\begin{array}5040\,x&-&7\cdot 6\cdot 5\cdot 4 &-& 7\cdot 6\cdot 5 \end{array}}}^{ \times 5}} 120\,x&-&5\cdot 4 &-& 5 &-& 1 \\\\ D_6&=& 720\,x&-&6\cdot 5\cdot 4 &-& 6\cdot 5 &-& 6 &- & 1 \\\\ D_7&=& 5040\,x&-&7\cdot 6\cdot 5\cdot 4 &-& 7\cdot 6\cdot 5 &-& 7\cdot 6 &- & 7 &-&- 1 \\\\ D_k &=& k! x &-&\rlap{\sum_{l=3}^{k} \frac{k!}{l!}} \\ \end{array}$$ and $$ J_n = x \sum_{k=1}^n k! -\sum_{k=3}^n\sum_{l=3}^{k} \frac{k!}{l!} $$ Closed form expression for $x$ Lets rewrite $D_k$ $$\begin{array}{} D_k &=& k! x - \sum_{l=3}^{k} \frac{k!}{l!}\\ &=& k! \left(x - \sum_{l=0}^k \frac{1!}{l!} - 2.5 \right)\end{array}$$ If we conjecture that $\lim_{k \to \infty }D_k$ is positive and finite then this leads to the requirement $\lim_{k \to \infty }\left(x - \sum_{l=0}^k \frac{1!}{l!} - 2.5 \right)= 0$ and $$x = \lim_{k \to \infty } \left(\sum_{l=0}^k \frac{1!}{l!} - 2.5\right) = e-2.5 \approx 0.2182818 $$ The argument that $\lim_{k \to \infty }D_k$ is finite is still a conjecture but it seems plausible to me. Closed form expression for $D_k$ Filling in $x$ into the expression of $D_k$ will lead to: $$\begin{array}{} J_1 &=& D_1 & = & 2e-2 \\ &&D_2 & = & 2e-5 \\ &&D_k & = & k! \left( e - \sum_{l=0}^k \frac{1}{l!}\right) \\ \end{array}$$ Is $J_n$ finite? We can argue that $J_n$ (the mean number of steps to reach the finish) is finite for any starting point $n$, because the mean position from the finish is decreasing to zero bounded by an exponential decay. The mean distance from the finish: Say a frog starts in position $x$. Then after one jump the frog will be somewhere in position $0 \leq y \leq x+1$ (each option with probability $\frac{1}{x+2}$), and if $y \neq 0$ then after after two jumps the frog will be somewhere in position $0 \leq z \leq y+1$ (each option with probability $\frac{1}{y+2}$). Then the mean position $\bar{z}$ of a frog that started at $x$ and makes two jumps will be: $$ \sum_{y=1}^{x+1}\sum_{z=1}^{y+1}\frac{z}{(x+2)(y+2)} = \frac{x^2+5x+4}{4x+8} \underbrace{\leq\frac{10}{12}x}_{\text{if $x\geq1$}}$$ So whatever the position of the frog, after two jumps, he will be on average at least 1/6 closer to the finish. Probability a frog is still in the game: Note that the probability of a frog still in the game relates to the mean distance of a frog in the game. The mean distance after $k$ jumps is $\mu_{\bar{x},k} \sum_{x=1}^\infty x f(x,k)$, where $f(x,k)$ is the probability of the frog to be in position $x$ after $k$ jumps. The probability of a frog to be still in the game is: $$ 1-F_{(\text{finished at or before jump k})}(k)=\sum_{x=1}^\infty f(x,k) < \mu_{\bar{x},k} \leq x_{start} \left(\frac{10}{12} \right)^{k/2}$$. Finiteness of $J_n$ The mean number of steps necessary can be found by $\sum_{k=0}^\infty k f(k)$ with $f(k)$ the probability that it takes $k$ steps. But you can also take $\sum_{k=0}^\infty 1-F(x)$ with $F(k)$ the probability that it takes $k$ or less steps (note that the integral of the CDF is related to the mean or more generaly the expected value of any quantity is related to the quantile function). And since $1−F(k)$ is smaller than some decreasing exponential function of $k$, so must be the sum smaller than the integral/sum of that function and that is finite. Starting with a simpler problem With the recurrence relation $D_n = n D_{n-1} - 1$ it is problematic to solve the case because the starting condition is not defined. We can instead try to pose a simpler problem (suggested in the comments by @quester and @Hans). Let's say that there are only $m+2$ leaves (instead of infinite), and thus the frog with only $m$ leaves in front of him will not be able to jump backwards. Then $J_m = J_{m-1}$ (the frog in point $m$ has the same options as the frog in point $m-1$) and we will have $$D_{m} = m! \left(x_m - \sum_{l=0}^m \frac{1!}{l!} - 2.5 \right) = 0$$ which gives a solution for $x_{m}$ as: $$x_m = \sum_{l=0}^m \frac{1!}{l!} - 2.5 $$ and the limit of $x_m$ as we start adding leaves is: $$\lim_{m\to \infty} x_m = \lim_{m\to \infty} \sum_{l=0}^m \frac{1!}{l!} -2.5 = e-2.5$$ Written by StackExchangeStrike A: No going back case only I'm addressing the zero-length jumps case only, i.e. no going back and the frog is allowed to remain still at a given step. Without considering a clock-like device and assuming that remaining still in one clock tick counts as one jump means just considering the other's puzzle conditions. It does not have to be a precise clock or stick to equal time intervals, just give a tick every now and then which trigger the need for a jump by the frog. When on leaf 1, there is a probability $\frac12$ to jump to the target leaf 0 and $\frac12$ to remain on leaf 1. The probability of taking exactly $k$ jumps to land on the target has probability $\left(\frac12\right)^k$, that is $\left(\frac12\right)^{k-1}$ of remaining still in the first $k-1$ ticks and $\frac12$ to land on leaf 1 on the $k$-th tick. So the expected value is: $$J_1 = \sum_{k=1}^{\infty}k\left(\frac12\right)^k = \frac{\frac12}{\left(1-\frac12\right)^2} = 2$$ (thanks wikipedia). Generalizing for $n > 1$, we can land on leaf $0..n$ at the next tick, each with probability $\frac1{n+1}$. Each case implies taking the jump of the tick, then taking the average number of jumps from the leaf we land on: $$J_n = \sum_{k=0}^{n}\frac1{n+1}(1+J_k) = \frac1{n+1}\sum_{k=0}^{n}(1+J_k) = 1 + \frac1{n+1}\sum_{k=0}^{n}J_k$$ Interestingly, this allows us to find $J_1 = 1 + \frac12J_1 = 2$ but without much sweating with the harmonic series. Evolving the equation: $$(n+1)J_n = n + 1 + \sum_{k=0}^{n}J_k$$ This relation does not hold for $n = 0$ because it would lead to $0 = 1$. Assuming $n > 1 \Rightarrow n - 1 > 0$: $$nJ_{n-1} = n + \sum_{k=0}^{n-1}J_k$$ Subtracting the last two equations: $$(n+1)J_n - nJ_{n-1} = 1 + J_n$$ $$nJ_n = 1 + nJ_{n-1}$$ $$J_n = \frac1n + J_{n-1}$$ that is exactly the same relation we have if the frog is only allowed to advance, although with different edge conditions ($n > 1$ and $J_1 = 2$). So, the bottom line is: $$ J_0 = 0 $$ $$ n>0 : J_{n} = 1 + \sum_{k=1}^{n}\frac1k $$ i.e. on average there will be exactly 1 jump more than the previous case where the frog can only advance, except for $J_0$ in which case the frog will always just remain still. It is interesting that the recurrent relation holds for $n>1$ but the non-recurrent formula holds also for $n = 1$. A few simulations seem to support the result above.
{ "pile_set_name": "StackExchange" }
Q: Does character creation dictate my role? During character creation, you select race and gender, birthsign and class (or create your own) in addition to cosmetic appearance. No matter what I select, will I be able to play different roles ("fighter", "mage" and "thief" are the character types commonly associated with the game) efficiently, as long as I'm willing to develop role-specific skills? A: PapaStan was right that Race and Birthsign can provide you with some unique bonus that you cannot get otherwise, like the bonus of the Atronach (allows building the strongest possible mage and mage killer at the same time), or that is hard to get otherwise, even though possible: for example, Thief gives you an initial boost of +10 Luck: this attribute is extremely hard to level up, because there are no skills tied to it, so the best you can get is +1 each level. And Luck is very important, determining loot you get in the dungeons and providing a bonus to all other attributes. Class also really does provide you a boost into some attributes and skills, but the important thing is that the skills that get the inital bonus are also leveled a lot faster, especially in the cases like Restoration. So you will be able to take any role while playing your character, but some roles can be harder or easier to fullfil depending on your build. There are some builds based on skills from different groups that are possibly weaker at the beginning, but allow you to develop all of the attributes relatively quickly, thus making your character a stronger "generalist". I strongly suggest you to read an article on efficient leveling to understand what am I talking about. A: I've been playing Oblivion for three years now with different characters so I can share my experiences. Race: Gives you a boost on various skills, also a great power (Adrenaline Rush for Redguards) or an ability (Resist Magick for Bretons) Class: More boosts on skills Birthsign: It can boost a couple of skills or grant you with a great power Take a look at this page for more information, also previous links will help you to understand the leveling system. I do recommend playing with a custom class because default classes are not well balanced, for example the warrior has three combat skills (Blade, Blunt and Hand to Hand) when you will be using mainly only one. But you should play at least a couple of times in order to understand how skills work, with different characters. Then, you should start your roleplaying adventure ;) But once you get used to the game you will realize you can play any class with any character. It will be hard early in the game, for example, to play a warrior with a Breton (due to low Endurance and Strengh) or a mage with a Nord (average Willpower and Intelligence), but in the long run you can maximize your skills to 100 (it can be a little challenging but is possible).
{ "pile_set_name": "StackExchange" }
Q: Is it possible to create a BulletDecorator using the current theme? I'm using the well known technique of styling a list box to look like a radio button group. The style presents a BulletDecorator for each item in the list. In order to do this I need to reference a specific theme assembly such as PresentationFramework.Aero.dll, and then explicitly use that in my style. xmlns:theme="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero" <BulletDecorator.Bullet> <theme:BulletChrome Background="{TemplateBinding Control.Background}" BorderBrush="{TemplateBinding Control.BorderBrush}" IsRound="True" RenderMouseOver="{TemplateBinding UIElement.IsMouseOver}" IsChecked="{TemplateBinding ListBoxItem.IsSelected}" /> </BulletDecorator.Bullet> Is there a way to create a BulletDecorator which is styled using the current or default theme, so that I don't need to reference an explicit theme? A: You don't need to recreate the RadioButton template... why don't you just use a RadioButton in the ItemContainerStyle? <Style x:Key="RadioButtonGroup" TargetType="ListBox"> <Setter Property="ItemContainerStyle"> <Setter.Value> <Style TargetType="ListBoxItem"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBoxItem"> <RadioButton IsChecked="{TemplateBinding IsSelected}" Content="{TemplateBinding Content}" GroupName="ListBoxItems" /> </ControlTemplate> </Setter.Value> </Setter> </Style> </Setter.Value> </Setter> </Style> Note that there's an issue with this approach: if you use this style for several ListBoxes in the same window, all RadioButtons will be mutually exclusive, because they will share the same GroupName. See this article for a workaround.
{ "pile_set_name": "StackExchange" }
Q: RabbitMQ in Docker container doesn't allow my Java app to connect I am running RabbitMQ in the Docker container. In addition to RabbitMQ image I also installed RabbitMQ management plugin. Using plugin I created user 'executor'. I set user permissions to Virtual host / Configure regexp .* Write regexp .* Read regexp .* Here is my code public static void main(String[] argv) throws Exception { String message; ConnectionFactory factory = new ConnectionFactory(); factory.setHost(SERVER); factory.setUsername(RABBIT_USER); factory.setPassword(RABBIT_USER_PASSWORD); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, IS_DURABLE_QUEUE, false, false, null); message = argv.length==1?argv[0]:"Hello World!"; channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); System.out.println(" [x] Sent '" + message + "'"); channel.close(); connection.close(); } When I run this app I get the following exception Exception in thread "main" com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile. at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:362) at com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory.newConnection(RecoveryAwareAMQConnectionFactory.java:64) at com.rabbitmq.client.impl.recovery.AutorecoveringConnection.init(AutorecoveringConnection.java:134) at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:997) at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:956) at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:914) at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1068) at ca.meh.hial.producer.Producer.main(Producer.java:24) Clearly user can't connect due to authentication issues. I am not sure if I need to install some other plugin. Or do I need to configure Docker container to validate credentials? A: Apparently you can't use management console from one Docker container to manage RabbitMQ in another Docker container.
{ "pile_set_name": "StackExchange" }
Q: Deploy rails to Heroku using outside postgres database First off, I'm a total Rails/PostgreSQL noob. I'm trying to deploy a rails app to Heroku. I've gotten it up and running, but every time I deploy, Heroku ignores my database.yml information and generates a new database. Here is my database.yml # SQLite version 3.x # gem install sqlite3 # # Ensure the SQLite 3 gem is defined in your Gemfile # gem 'sqlite3' # default: &default adapter: sqlite3 pool: 5 timeout: 5000 development: # <<: *default # database: db/development.sqlite3 adapter: postgresql pool: 5 host: wwydh.cqqq2sesxkkq.us-east-1.rds.amazonaws.com timeout: 5000 username: wwydh_a_team password: really cool password database: wwydh host: wwydh.cqqq2sesxkkq.us-east-1.rds.amazonaws.com port: 5432 # Warning: The database defined as "test" will be erased and # re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: <<: *default database: db/test.sqlite3 What am I doing wrong? A: Finally solved it! This is what I did, maybe it'll help somebody. Heroku defaults your app to 'production' status, which means it will use the settings defined in your database.yml file under 'production'. Since I didn't have any of those settings, it was creating a database to use. I deleted my Heroku PostgreSQL database (the one that was created for me), and manually switched my RAILS_ENV variable (located under app settings in Heroku) to 'development' and voila! My app connected to my external AWS database no problem. Side note, make sure you define a new security group in AWS to allow incoming connections from any Inbound Source, IE 0.0.0.0/0. Otherwise, the database will deny Heroku access. I went to the VPC dashboard in AWS, clicked security groups, and edited my default group to this, then went and made sure that my database instance was using that security group.
{ "pile_set_name": "StackExchange" }
Q: Java synchronized vs deadlock example I am not familiar with threads and concurrent programming. I was looking for a simple snippet which would result in a deadlock, here it is : public class TestLock { private static class fun { int a,b; void read() {System.out.println(a+b);} void write(int a,int b) {this.a=a;this.b=b;} } public static void main (String[] args) throws java.lang.Exception { final fun d1=new fun(); final fun d2=new fun(); Thread t1=new Thread() { public void run() { for(int i=0;i<5;i++) { synchronized(d2) { d2.read(); try { Thread.sleep(50); } catch (Exception ex) { ex.printStackTrace(); } synchronized(d1) { d1.write(i, i); } } } }; Thread t2=new Thread() { public void run() { for(int i=0;i<5;i++) { synchronized(d1) { d1.read(); try { Thread.sleep(50); } catch (Exception ex) { ex.printStackTrace(); } synchronized(d2) { d2.write(i, i); } } } } }; t1.start(); t2.start(); } } Now I was wondering how I could transform this example, using ReentrantLock instead of synchronized, but I don't see how : does fun need to have a ReentrantLock attribute in order to have something like Thread t1=new Thread() { public void run() { for(int i=0;i<5;i++) { if(d2.lock.tryLock()) { try {d1.read();Thread.sleep(50);} catch(Exception e) {e.printStackTrace();} finally {d1.lock.unlock();} if(d2.lock.tryLock()) { try {d2.write(i, i);} catch(Exception e) {e.printStackTrace();} finally {d2.lock.unlock();} } } } } }; or am I missing something entirely ? A: Transforming the example using ReentrantLocks would indeed mean using two locks: one associated with d1 and the other one associated with d2. And you would replace every entrance in a synchronized block on dX by a call to lockX.lock(), and any exit from a synchronized block on dX by a call to lockX.unlock()`. Using tryLock() defeats the purpose, since it returns instead of waiting if the lock can't be acquired.
{ "pile_set_name": "StackExchange" }
Q: Create a fresh new access token using refresh token using thephpleague/oauth2-server I'm facing some problems to wrap my mind about oAuth 2.0. Particularly, thephpleague/oauth2-server implementation. I managed to set up an endpoint to create access tokens using Password grant type. This is, when someone do a POST /auth, they get the following answer: { "access_token": "hleVw03Fx4hVsaCqEmFqcXeks0hsDTkNSxMN17NR", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "GD8kT7JfGULhUKSTSBsF7AO6NaIXrqPS0dlyQjTm" } What I want to do now, is generate a new token when the access_token gets expired. I understand that I should use the refresh_token to ask for a fresh new token. However, I didn't find any documentation to start with. A: You can use the Refresh Grant type to get a new access token. It is a standardized flow that is described in the spec here: https://tools.ietf.org/html/rfc6749#section-6. An example request to the token endpoint (taken from the spec) would look like: POST /token HTTP/1.1 Host: server.example.com Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW Content-Type: application/x-www-form-urlencoded grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA In this case the client authenticates itself with Basic Authentication to the token endpoint using its client_id and client_secret. In commandline cURL it would look like: curl -u "${CLIENT_ID}:${CLIENT_SECRET}" -d "grant_type=refresh_token&refresh_token=${REFRESH_TOKEN}"
{ "pile_set_name": "StackExchange" }
Q: Problem with mixed CMOS op-amp supply voltages on a square to saw wave converter I am designing a square wave to saw wave converter by first integrating the square wave into a triangle wave, then toggling between the triangle wave and it's inverse, using 2 CMOS 4066 switches triggered by the original square wave. The output is an incomplete saw wave because of the triangle wave going too negative relative to the 4066 supply voltage. I know I could fix this by scaling and adding a DC offset to the triangle waves at the input of each 4066 switch. But for a number of reasons I want to keep the waveforms balanced with no DC offset. I also want to keep the circuit as simple as possible because it will be repeated many times in this project. Can I power the with 4066 and 4069 with -12v to +12v so as not to cause this problem? If so what is a simple way to shift the logic level of the input to the 4069 to the right level? A: You can run the 4000 series parts off a bipolar supply but the voltage is limited (IIRC the limit is 20V total which works out to ±10V) and you need to level shift the input signal, this is perfectly doable with a comparator and a few resistors but it's still an extra part. Or you can use a modern part like the ADG1219. It's a 2:1 mux rather than a plain switch so you don't need an inverter and it has a seperate pin for the logic ground so you can run it off a bipolar supply while controlling it with a unipolar signal.
{ "pile_set_name": "StackExchange" }
Q: Why are integers returning as hex? I am implementing a simple smart contract in Solidity 0.5.9. One of the functions is called getSummary() which basically returns a summarized version of a vote: function getSummary() public view returns (uint, uint, uint, address, bool) { return ( reward, choices.length, votersCount, manager, pollActive ); } I test this in Remix and get the results as I expect: 0: uint256: 9000000000000000 1: uint256: 2 2: uint256: 0 3: address: 0x1d174c79A9Fc825F2d625adEAa7035381D3a413e 4: bool: true So far so good. Now, I am working on a simple JavaScript frontend to display these results to the user, using web3-1.0.0, however I get the results in a weird format: 0: {…} ​​​ _ethersType: "BigNumber" ​​​ _hex: "0x1ff973cafa8000" ​​​ <prototype>: Object { fromTwos: fromTwos(), toTwos: toTwos(), abs: abs() , … } ​​ 1: {…} ​​​ _ethersType: "BigNumber" ​​​ _hex: "0x02" ​​​ <prototype>: Object { fromTwos: fromTwos(), toTwos: toTwos(), abs: abs() , … } ​​ 2: {…} ​​​ _ethersType: "BigNumber" ​​​ _hex: "0x00" ​​​ <prototype>: Object { fromTwos: fromTwos(), toTwos: toTwos(), abs: abs() , … } ​​ 3: "0x1d174c79A9Fc825F2d625adEAa7035381D3a413e" ​​ 4: true It looks like the Boolean and the Address are being returned in the correct format, whereas the integers are being returned as objects with the _hex property. I am pretty sure that I am seeing this for the first time and if I recall correctly, I haven't encountered such issue with previous smart contracts. What am I doing wrong? Is this the expected behaviour? If yes, how can I correctly cast uint values from Solidity to display correctly on the frontend. PS: I tried using web3.utils.toAscii(val) but values were transformed into funny characters, not to mention that this seems like a poor hack to do on every value I return. A: Web3.js returns all uint types as BigNumber objects. If you want to get the decimal string which represents the numeric value embedded in a BigNumber object, then you can call function toFixed on that object. For example: const [reward, length, votersCount, manager, pollActive] = await myContract.methods.getSummary(); console.log('reward:', reward.toFixed()); console.log('length:', length.toFixed()); console.log('votersCount:', votersCount.toFixed());
{ "pile_set_name": "StackExchange" }
Q: What's the best way to show and hide parts of an MVC view based on some logic? I just have something I'm thinking about and something which I've been implementing in a lot of my code which I don't think is the best way of doing things. You know, after you submit a form, you may want to direct back to the same page and display a success message and want to hide the submitted form inputs for example. Other times, you may direct to a page with an optional parameter, like a query string, and based on that parameter, you may want to show and hide certain things on your view. I'm not sure the best way to do this because I like keeping all logic in my controller and not putting logic in my view. You can accomplish this in webforms simply by separating your elements in different panels and setting the hidden property in your cs control. The way I've been doing this in MVC (which I don't like) is, for example, with a ViewBag success message and an if statement in my view which checks if the viewbag is null. If it's not null, it displays the success message; else, it displays some form inputs. Other times, you don't use a viewbag. For example, a checkout page for a shopping cart. In your view, you might check if the cart model is empty. If it is, display a "sorry, your cart is empty" message; else, display the cart table. I don't like handling this with if logic in my view. What is the best solution? Is there another solution? Some example code here. Control: [HttpPost] public ActionResult Edit(Elephants elephants) { // do something with elephants ViewBag.weldone = "Weldone, you have made a wonderful impact by submitting this crucial knformation about elephants to the world"; return View(); } View: @if(ViewBag.weldone != null) { <p>@ViewBag.weldone</p> } else { //something you want to hide from the page on succesfull elephant save } A: Don't use ViewBag, use a view-model instead - its called "Model View Controller" for a reason. public class Elephants { ... public string SuccessMessage { get; set; } } [HttpPost] public ActionResult Edit(Elephants model) { // do something with elephants model.SuccessMessage = "yay"; return View(model); } and in the view @model Elephants @if (model.SuccessMessage != null) { <p>@model.SuccessMessgae</p> } else { // Redisplay Elephants } @Html.ValidationSummary() OR you could avoid all that by redirecting to another page which displays your message. [HttpPost] public ActionResult Edit(Elephants model) { // do something with elephants return RedirectToAction("EditSuccess"); } [HttpGet] public ViewResult EditSuccess() { return View(); // Displays view "EditSuccess.cshtml" }
{ "pile_set_name": "StackExchange" }
Q: Writing normal C++ String to Rapid JSON is resulting in string with backslash string str = {"appId":"com.mymusic.app","Connectivity":True,"DistractionLevel":2,"display":True}; if(!str.empty()) { StringBuffer bf; PrettyWriter<StringBuffer> writer (bf); writer.StartObject(); writer.Key("info")); writer.String(str.c_str()); writer.EndObject(); cout<<"request string is:" , (char *)bf.GetString()); } cout is printing the below line with back slash {"info":"\"appId\":\"com.mymusic.app\",\"checkConnectivity\":True,\"driverDistractionLevel\":2,\"display\":True}"} What i was expecting is {"info": {"appId":"com.mymusic.app","Connectivity":True,"DistractionLevel":2,"display":True} } A: You are using the the wrong function. The String function will add a string value to the json-object and in this context the escaping of " to \" is expected. I think what you actually want to do is add the string as a json-sub-object. From what I found in the rapidjson documentation the function you want to use for that is RawValue.
{ "pile_set_name": "StackExchange" }
Q: Loading 26 letter images from a PNG stripe using BitmapRegionDecoder In a word game app I am trying to load 26 letter tiles from a 6205 x 240 PNG image: private Paint mPaint = new Paint(Paint.FILTER_BITMAP_FLAG); mStripe = BitmapFactory.decodeResource( context.getResources(), R.drawable.big_english); int h = mStripe.getHeight(); mSrc = new Rect(0, 0, h, h); mDst = new Rect(0, 0, h, h); canvas.drawBitmap(mStripe, mSrc, mDst, mPaint); On the real device (Moto G) this fails with (I guess 1.5x downscaled from drawables-xxhdpi): OpenGLRenderer Bitmap too large to be uploaded into a texture (4137 x 160; max=4096x4096) and the letter images aren't displayed (the dragged tile appears to be empty): So I would like to use BitmapRegionDecoder to load 240 x 240 bitmaps, but as an Android programming newbie (and I have searched around too) I still have 2 questions please: How to load a R.drawable.big_english - there is no suitable constructor? Can I somehow use isShareable here - given the fact that I load 26 letters? A: Bitmapfonts for android http://examples.javacodegeeks.com/android/games/canvas/using-bitmap-fonts/ You should also google for bit map fonts. There are a few more implementations and examples. For gl there's an implementation in libgdx http://www.codehead.co.uk/blog/android-bitmap-font-renderer-text-scaling-feature/
{ "pile_set_name": "StackExchange" }
Q: "Multiple Constant Drivers" Error Verilog with Quartus Prime I am working on designing a finite state machine in Verilog to represent a stack. The module is as follows: module state_machine (s, Enable, Clock, Resetn, c, OF_Err, UF_Err); input [2:0] s; input Enable, Clock, Resetn; output reg [1:0] c; output reg OF_Err = 0, UF_Err = 0; reg [2:0] y, Y; parameter [2:0] A = 3'b000, B = 3'b001, C = 3'b010, D = 3'b011, E = 3'b100; always @(s, y, Enable) if (Enable) begin case (y) A: if (s == 3'b000) Y = B; else begin Y = A; UF_Err = 1; end B: if (s == 3'b000) Y = C; else if (s == 3'b001) Y = A; else begin Y = B; UF_Err = 1; end C: if (s == 3'b000) Y = D; else if (s == 3'b100) Y = C; else Y = B; D: if (s == 3'b000) Y = E; else if (s == 3'b100) Y = D; else Y = C; E: if (s == 3'b000) begin Y = E; OF_Err = 1; end else if (s == 3'b100) Y = E; else Y = D; default: Y = 3'bxxx; endcase c[1] = y[1]; c[0] = y[0]; end always @(negedge Resetn, posedge Clock) begin if (Resetn == 0) begin y <= A; OF_Err = 0; //Problem UF_Err = 0; //Problem end else y <= Y; end OF_Err and UF_Err are indicators of overflow and underflow errors, respectively. However, I get the following errors when compiling my project: Error (10028): Can't resolve multiple constant drivers for net "OF_Err" at state_machine.v(59) Error (10029): Constant driver at state_machine.v(10) Error (10028): Can't resolve multiple constant drivers for net "UF_Err" at state_machine.v(59) These only appeared after I added the commented lines. I want to reset the over- and underflow indicators when the FSM is reset, but I can't do it the way I have it. How do I go about doing this? (If it's of any value, this is to be executed on an Altera DE2-115). A: As others have already pointed out, OF_Err and UF_Err were driver by two always blocks which is illegal for synthesis. I recommend creating two additional variables of_Err and uf_Err like Arvind suggested. However I recommend keeping OF_Err and UF_Err as flops. The if (Enable) in the combinational block infers Y,c and the *_Err as level-sensitive latches. I highly doubt this is what you intendeds. I recommend moving the if (Enable) into synchronous always block and keeping the combinational logic as pure combinational. c is a simple assignment, so it might make more sense having it as a wire instead of a reg with a simple assign statement. It can be in the combinational block, but I prefer to separate combinational input from output. You did use @(s, y, Enable) correctly, however @* or the synonymous @(*) is recommenced for combinational block. @* is an auto sensitivity list which saves you typing, maintenance, and removes the risk of forgetting a signal. always @* begin of_Err = OF_Err; // <-- default values uf_Err = UF_Err; case (y) // ... your original case code with OF_Err/UF_Err renamed to of_Err/uf_Err endcase end always @(posedge Clock, negedge Resetn) // style difference, I prefer the clock to be first begin if (Resetn == 1'b0) begin y <= A; OF_Err <= 1'b0; UF_Err <= 1'b0; end else if (Enable) begin y <= Y; OF_Err <= of_Err; UF_Err <= uf_Err; end end assign c[1:0] = y[1:0];
{ "pile_set_name": "StackExchange" }
Q: Why it's impossible to change camera viewport rect while using pixelperfect camera in unity? Why it's impossible to change camera viewport rect while using pixelperfect camera in unity? Is there any specific reason to prevent viewport rect parameter changes? Is there any way to get around it? A: Well, couple minutes after I asked a question i figured it out, and found a solution. It looks like pixel perfect camera script checks every frame if m_Internal.useOffscreenRT is set to true, if not it does change vieport rect to default parameters. So i changed the script, and now it stores choosen viewport rect from camera on awake, and set it to camera every time it needs to, instead of default vieport rect (0,0,1,1); Here is updated code if someone ever needs that: using UnityEngine.Rendering; using UnityEngine.Scripting.APIUpdating; namespace UnityEngine.Experimental.Rendering.Universal { /// <summary> /// The Pixel Perfect Camera component ensures your pixel art remains crisp and clear at different resolutions, and stable in motion. /// </summary> [DisallowMultipleComponent] [AddComponentMenu("Rendering/2D/Pixel Perfect Camera (Experimental)")] [RequireComponent(typeof(Camera))] [MovedFrom("UnityEngine.Experimental.Rendering.LWRP")] public class PixelPerfectCamera : MonoBehaviour, IPixelPerfectCamera { /// <summary> /// Match this value to to the Pixels Per Unit values of all Sprites within the Scene. /// </summary> public int assetsPPU { get { return m_AssetsPPU; } set { m_AssetsPPU = value > 0 ? value : 1; } } /// <summary> /// The original horizontal resolution your Assets are designed for. /// </summary> public int refResolutionX { get { return m_RefResolutionX; } set { m_RefResolutionX = value > 0 ? value : 1; } } /// <summary> /// Original vertical resolution your Assets are designed for. /// </summary> public int refResolutionY { get { return m_RefResolutionY; } set { m_RefResolutionY = value > 0 ? value : 1; } } /// <summary> /// Set to true to have the Scene rendered to a temporary texture set as close as possible to the Reference Resolution, /// while maintaining the full screen aspect ratio. This temporary texture is then upscaled to fit the full screen. /// </summary> public bool upscaleRT { get { return m_UpscaleRT; } set { m_UpscaleRT = value; } } /// <summary> /// Set to true to prevent subpixel movement and make Sprites appear to move in pixel-by-pixel increments. /// Only applicable when upscaleRT is false. /// </summary> public bool pixelSnapping { get { return m_PixelSnapping; } set { m_PixelSnapping = value; } } /// <summary> /// Set to true to crop the viewport with black bars to match refResolutionX in the horizontal direction. /// </summary> public bool cropFrameX { get { return m_CropFrameX; } set { m_CropFrameX = value; } } /// <summary> /// Set to true to crop the viewport with black bars to match refResolutionY in the vertical direction. /// </summary> public bool cropFrameY { get { return m_CropFrameY; } set { m_CropFrameY = value; } } /// <summary> /// Set to true to expand the viewport to fit the screen resolution while maintaining the viewport's aspect ratio. /// Only applicable when both cropFrameX and cropFrameY are true. /// </summary> public bool stretchFill { get { return m_StretchFill; } set { m_StretchFill = value; } } /// <summary> /// Ratio of the rendered Sprites compared to their original size (readonly). /// </summary> public int pixelRatio { get { if (m_CinemachineCompatibilityMode) { if (m_UpscaleRT) return m_Internal.zoom * m_Internal.cinemachineVCamZoom; else return m_Internal.cinemachineVCamZoom; } else { return m_Internal.zoom; } } } /// <summary> /// Round a arbitrary position to an integer pixel position. Works in world space. /// </summary> /// <param name="position"> The position you want to round.</param> /// <returns> /// The rounded pixel position. /// Depending on the values of upscaleRT and pixelSnapping, it could be a screen pixel position or an art pixel position. /// </returns> public Vector3 RoundToPixel(Vector3 position) { float unitsPerPixel = m_Internal.unitsPerPixel; if (unitsPerPixel == 0.0f) return position; Vector3 result; result.x = Mathf.Round(position.x / unitsPerPixel) * unitsPerPixel; result.y = Mathf.Round(position.y / unitsPerPixel) * unitsPerPixel; result.z = Mathf.Round(position.z / unitsPerPixel) * unitsPerPixel; return result; } /// <summary> /// Find a pixel-perfect orthographic size as close to targetOrthoSize as possible. Used by Cinemachine to solve compatibility issues with Pixel Perfect Camera. /// </summary> /// <param name="targetOrthoSize">Orthographic size from the live Cinemachine Virtual Camera.</param> /// <returns>The corrected orthographic size.</returns> public float CorrectCinemachineOrthoSize(float targetOrthoSize) { m_CinemachineCompatibilityMode = true; if (m_Internal == null) return targetOrthoSize; else return m_Internal.CorrectCinemachineOrthoSize(targetOrthoSize); } [SerializeField] Rect defaultRect = new Rect(0.0f, 0.0f, 1.0f, 1.0f); [SerializeField] int m_AssetsPPU = 100; [SerializeField] int m_RefResolutionX = 320; [SerializeField] int m_RefResolutionY = 180; [SerializeField] bool m_UpscaleRT; [SerializeField] bool m_PixelSnapping; [SerializeField] bool m_CropFrameX; [SerializeField] bool m_CropFrameY; [SerializeField] bool m_StretchFill; Camera m_Camera; PixelPerfectCameraInternal m_Internal; bool m_CinemachineCompatibilityMode; internal bool isRunning { get { #if UNITY_EDITOR return (Application.isPlaying || runInEditMode) && enabled; #else return enabled; #endif } } internal FilterMode finalBlitFilterMode { get { if (!isRunning) return FilterMode.Bilinear; else return m_Internal.useStretchFill ? FilterMode.Bilinear : FilterMode.Point; } } internal Vector2Int offscreenRTSize { get { if (!isRunning) return Vector2Int.zero; else return new Vector2Int(m_Internal.offscreenRTWidth, m_Internal.offscreenRTHeight); } } // Snap camera position to pixels using Camera.worldToCameraMatrix. void PixelSnap() { Vector3 cameraPosition = m_Camera.transform.position; Vector3 roundedCameraPosition = RoundToPixel(cameraPosition); Vector3 offset = roundedCameraPosition - cameraPosition; offset.z = -offset.z; Matrix4x4 offsetMatrix = Matrix4x4.TRS(-offset, Quaternion.identity, new Vector3(1.0f, 1.0f, -1.0f)); m_Camera.worldToCameraMatrix = offsetMatrix * m_Camera.transform.worldToLocalMatrix; } void Awake() { m_Camera = GetComponent<Camera>(); defaultRect = m_Camera.rect; m_Internal = new PixelPerfectCameraInternal(this); m_Internal.originalOrthoSize = m_Camera.orthographicSize; } void LateUpdate() { #if UNITY_EDITOR if (!UnityEditor.EditorApplication.isPaused) #endif { // Reset the Cinemachine compatibility mode every frame. // If any CinemachinePixelPerfect extension is present, they will turn this on // at a later time (during CinemachineBrain's LateUpdate(), which is // guaranteed to be after PixelPerfectCamera's LateUpdate()). m_CinemachineCompatibilityMode = false; } } void OnBeginCameraRendering(ScriptableRenderContext context, Camera camera) { if (camera != m_Camera) return; var targetTexture = m_Camera.targetTexture; Vector2Int rtSize = targetTexture == null ? new Vector2Int(Screen.width, Screen.height) : new Vector2Int(targetTexture.width, targetTexture.height); m_Internal.CalculateCameraProperties(rtSize.x, rtSize.y); PixelSnap(); if (m_Internal.useOffscreenRT) m_Camera.pixelRect = m_Internal.CalculateFinalBlitPixelRect(rtSize.x, rtSize.y); else m_Camera.rect = defaultRect; // In Cinemachine compatibility mode the control over orthographic size should // be given to the virtual cameras, whose orthographic sizes will be corrected to // be pixel-perfect. This way when there's blending between virtual cameras, we // can have temporary not-pixel-perfect but smooth transitions. if (!m_CinemachineCompatibilityMode) { m_Camera.orthographicSize = m_Internal.orthoSize; } UnityEngine.U2D.PixelPerfectRendering.pixelSnapSpacing = m_Internal.unitsPerPixel; } void OnEndCameraRendering(ScriptableRenderContext context, Camera camera) { if (camera == m_Camera) UnityEngine.U2D.PixelPerfectRendering.pixelSnapSpacing = 0.0f; } void OnEnable() { RenderPipelineManager.beginCameraRendering += OnBeginCameraRendering; RenderPipelineManager.endCameraRendering += OnEndCameraRendering; #if UNITY_EDITOR if (!UnityEditor.EditorApplication.isPlaying) UnityEditor.EditorApplication.playModeStateChanged += OnPlayModeChanged; #endif } internal void OnDisable() { RenderPipelineManager.beginCameraRendering -= OnBeginCameraRendering; RenderPipelineManager.endCameraRendering -= OnEndCameraRendering; m_Camera.rect = defaultRect; m_Camera.orthographicSize = m_Internal.originalOrthoSize; m_Camera.ResetWorldToCameraMatrix(); #if UNITY_EDITOR if (!UnityEditor.EditorApplication.isPlaying) UnityEditor.EditorApplication.playModeStateChanged -= OnPlayModeChanged; #endif } #if DEVELOPMENT_BUILD || UNITY_EDITOR // Show on-screen warning about invalid render resolutions. void OnGUI() { #if UNITY_EDITOR if (!UnityEditor.EditorApplication.isPlaying && !runInEditMode) return; #endif Color oldColor = GUI.color; GUI.color = Color.red; Vector2Int renderResolution = Vector2Int.zero; renderResolution.x = m_Internal.useOffscreenRT ? m_Internal.offscreenRTWidth : m_Camera.pixelWidth; renderResolution.y = m_Internal.useOffscreenRT ? m_Internal.offscreenRTHeight : m_Camera.pixelHeight; if (renderResolution.x % 2 != 0 || renderResolution.y % 2 != 0) { string warning = string.Format("Rendering at an odd-numbered resolution ({0} * {1}). Pixel Perfect Camera may not work properly in this situation.", renderResolution.x, renderResolution.y); GUILayout.Box(warning); } var targetTexture = m_Camera.targetTexture; Vector2Int rtSize = targetTexture == null ? new Vector2Int(Screen.width, Screen.height) : new Vector2Int(targetTexture.width, targetTexture.height); if (rtSize.x < refResolutionX || rtSize.y < refResolutionY) { GUILayout.Box("Target resolution is smaller than the reference resolution. Image may appear stretched or cropped."); } GUI.color = oldColor; } #endif #if UNITY_EDITOR void OnPlayModeChanged(UnityEditor.PlayModeStateChange state) { // Stop running in edit mode when entering play mode. if (state == UnityEditor.PlayModeStateChange.ExitingEditMode) { runInEditMode = false; OnDisable(); } } #endif } }
{ "pile_set_name": "StackExchange" }
Q: Why is "uncanny" not the opposite of "canny"? If canny means "cunning" Having or showing shrewdness and good judgement, especially in money or business matters. why does uncanny mean "supernatural"? Strange or mysterious, especially in an unsettling way. Uncanny should have meant "slow-witted" or "foolish" which is the opposite of cunning. A: Uncanny: 1590s, "mischievous;" 1773 in the sense of "associated with the supernatural," originally Scottish and northern English, from un- (1) "not" + canny. Canny is from the Anglo-Saxon root ken: "knowledge, understanding, or cognizance; mental perception: an idea beyond one's ken." Thus the uncanny is something outside one's familiar knowledge or perceptions. (Etymonline, Wikipedia) Also from The Word Detective: “Canny” is a very cool word. It first appeared in Scots and Northern English dialects as an adjective meaning “knowing, judicious, prudent, cautious,” and is simply based on the verb “can” in the sense of “to be able” (as in “I can fly”). “Canny” was picked up by English writers in the 17th century, who applied it to the Scots themselves in the sense of “cunning,” “wily” or “thrifty,” in line with the English portrayal of Scots as clever and frugal. The sense of “sharp” and “shrewd” eventually became more generalized, and today we use “canny” to mean “perceptive and wise” (“The canny investor avoids market fads”). One of the other meanings of “canny” back in Scotland in the 16th century, however, was “trustworthy,” and when “uncanny” first appeared it was in the sense of “malicious or incautious” (i.e., not trustworthy). By the 18th century, “uncanny” had come to mean specifically “not safe to trust because of connections to the supernatural,” and eventually the word took on its modern meaning of “supernatural,” “weird” and “strange.” So “uncanny” came to mean something quite different than simply “not smart.”
{ "pile_set_name": "StackExchange" }
Q: Why does my mind naturally wander? Before sitting for meditation I got a few strange questions: why does my mind even wander? What does my mind want, and can it ever be satisfied completely? Can anybody please explain this to me? A: Every life form is born in the world due to craving. Within life forms, there are seeds, such as sperm cells, which are propelled by craving. Parents of children engage in sexual intercourse & reproduce new life propelled by craving. New born children are born with craving to eat, craving to be safe, craving for love, craving for pleasure, etc. The mind wanders due to craving. This 'wandering' is called 'samsara'. A: You ask as to why the mind wanders. But it is there for cognizing thoughts – just as the eye is there to seeing forms, ear for hearing sounds, nose for smelling odours, tongue for tasting flavours, and body for touching tangibles. That is why, the more we watch our mind and see what it does to us and for us, the more we will be inclined to take good care of it and treat it with respect. One of the biggest mistakes we can make is taking the mind for granted. The mind has the capacity to create good and also evil for us, and only when we are able to remain even-minded no matter what conditions arise, can we say that we have gained a little control. Until then we are out of control and our thoughts are our master. Taming this monkey is not an easy thing. So you have to take baby steps in the beginning. Even if your attempt at meditation takes only a few seconds, or a couple of minutes, be happy about it. Left alone the mind behaves like a monkey in a forest. Meditation is a great way to calm the monkey mind. But prior to that we have to learn how to go beyond - being resolved on sensual passion, being resolved on ill will, being resolved on harmfulness—because all these things stir up the mind and interfere with its settling down.
{ "pile_set_name": "StackExchange" }
Q: MYSQL Query with OR I am currently using the following SQL Query: ("SELECT * FROM `form` WHERE '1' IN (show1) AND 'agree' NOT IN (test)") However I can't seem to work out how to add a OR in it.. I need to filter out if it's says 'agree' OR 'disagree' Any ideas? A: Assuming that show1 and test are columns and that this is Mysql related, this should work: "SELECT * FROM `form` WHERE show1 IN ('1') AND test NOT IN ('agree', 'disagree')" I prefer to have the columns to the left of the comparison :)
{ "pile_set_name": "StackExchange" }
Q: AJAX doesn't send back First I want to say that I am a beginner in Ajax. I am just a beginner. I hope you could help me with it. I want to send an id to the ajax script and there I run a query. Then I want to return the output of the page. I have a page quick_view_page.js in wich i set the id and send it to ajax_project_info.php in which I retrieve the id via the link. If I open ajax_project_info.php and set a variable id in the link, it works well. I can't get the output of ajax_project_info returned to quick_view_page.js. My quick_view_page.js. //Quick view show and hide $('a#quick_view').click(function() { var projectId = $(this).find($(".qv_id")).attr('id'); //alert(projectId); xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET","ajax/ajax_project_info.php?projectId=" + projectId); xmlhttp.send(); if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementByClassName("qvp_bg").innerHTML=xmlhttp.responseText; } My ajax_project_info.php <?php require_once("../pages/db.php"); error_reporting(E_ALL); ini_set('display_errors', 1); ob_start(); $projectId = $_GET["projectId"]; $query_getinfo = "SELECT * FROM tblProjecten WHERE id = '".$projectId."'"; $result_query_getinfo = mysqli_query($conn,$query_getinfo); while ($row = mysqli_fetch_array($result_query_getinfo)) { $response = $row['projectnaam']; }; else { $response = "Geen info beschikbaar"; } return $response; ?> Thanks! UPDATE: The problem seems to be in the "if (xmlhttp.readyState==4 && xmlhttp.status==200)" When I set an alert between this, the alert doesn't pop up. UPDATE 2: I now have quick_view_search.js: //Quick view show and hide $('a#quick_view').click(function() { var projectId = $(this).find($(".qv_id")).attr('id'); //xmlhttp request xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementsByClassName("qvp_bg").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","ajax/ajax_project_info.php?projectId=" + projectId, true); xmlhttp.send(); $.ajax({ 'url' : 'ajax/ajax_project_info.php', 'type' : 'GET', 'data' : { 'projectId' : projectId }, 'success' : function(data) { document.getElementsByClassName("qvp_bg").innerHTML=data; } }); $('.quick_view_project').css('display', 'block').hide().fadeIn(); return false; }); ajax_project_info.php: <?php /* require_once("../pages/db.php"); error_reporting(E_ALL); ini_set('display_errors', 1); ob_start(); $projectId = $_GET["projectId"]; if ($projectId) { $query_getinfo = "SELECT * FROM tblProjecten WHERE id = '".$projectId."'"; $result_query_getinfo = mysqli_query($conn,$query_getinfo); while ($row = mysqli_fetch_array($result_query_getinfo)) { $response = $row['projectnaam']; } else { $response = "Geen info beschikbaar"; } } else { $response = "Geen info beschikbaar"; } echo $response; */ echo "test"; ?> It gives me the following error: "xmlhttp is not defined". A: use echo $response instead of return $response try also, xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementByClassName("qvp_bg").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","ajax/ajax_project_info.php?projectId=" + projectId, true); xmlhttp.send(); Using jQuery Include jQuery to the project <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script> GET request $('.myButton').click(function() { $.ajax({ 'url' : 'ajax/ajax_project_info.php', 'type' : 'GET', 'data' : { 'projectId' : projectId }, 'success' : function(data) { document.getElementByClassName("qvp_bg").innerHTML=data; } }); }); hope this helps :-)
{ "pile_set_name": "StackExchange" }
Q: Do not want to repeat myself I have some links and when someone click on those links it will show up a popup which has some info.And then close it when user clicks on x.I have used jquery's show and hide to do this. Different links have different info so i have repeated myself and i want to know is there any way to not repeat myself.This Link will take you to jsbin where my code is and you understand what i am talking about. Thank You. A: if you give the div you are trying to show an id and the links you are clicking the same class and an href of the div id (this makes it more accessible too), you can do something like this: http://jsfiddle.net/GE6fX/1/ html <a class="show" href="#zerotwo">link1</a> <div id="zerotwo"> <h1>Link heading <span>[close x]</span></h1> <p>blah</p> </div> <a class="show" href="#zerothree">link2</a> <div id="zerothree"> <h1>Link heading <span>[close x]</span></h1> <p>blah</p> </div> js $('.show').click(function() { var showDiv = $($(this).attr('href')); showDiv.show(); showDiv.find('h1 span').click(function() { showDiv.hide(); }); });
{ "pile_set_name": "StackExchange" }
Q: Notepad++ - How to change contents of a line? Attempting to get this work, I've tried the other responses and they just don't work. Currently I have a bunch of files that have; "craftgroup" : [ "tool1", "tool2", "tool3" ] I'm attempting to get it to change all the files into "craftgroup" : [ "mastertool" ] but I can't seem to get it to actually work because the regex isn't working and I have over 650 files to change >.> Edit; The Links I tried were; How to delete specific lines on Notepad++? Notepad++ Replace new line inside text Notepad++ Search And Replace Multiple Text Lines None of them have worked, I just need to replace the entire line if that's easier. Thanks m0shit0 that worked, other ones for some reason kept saying "can't find text" A: Your question is not very clear. I understand that you only want to replace lines that have craftgroup. Find: "craftgroup" : \[(.*?)\] Replace: "craftgroup" : \[ "mastertool" \] Note: Notepad++ 6.5
{ "pile_set_name": "StackExchange" }
Q: How to calculate an epipolar line with a stereo pair of images in Python OpenCV How can I take two images of an object from different angles and draw epipolar lines on one based on points from the other? For example, I would like to be able to select a point on the left picture using a mouse, mark the point with a circle, and then draw an epipolar line on the right image corresponding to the marked point. I have 2 XML files which contain a 3x3 camera matrix and a list of 3x4 projection matrices for each picture. The camera matrix is K. The projection matrix for the left picture is P_left. The projection matrix for the right picture is P_right. I have tried this approach: Choose a pixel coordinate (x,y) in the left image (via mouse click) Calculate a point p in the left image with K^-1 * (x,y,1) Calulate the pseudo inverse matrix P+ of P_left (using np.linalg.pinv) Calculate the epipole e' of the right image: P_right * (0,0,0,1) Calculate the skew symmetric matrix e'_skew of e' Calculate the Fundamental matrix F: e'_skew * P_right * P+ Calculate the epipolar line l' on the right image: F * p Calculate a point p' in the right image: P_right * P+ * p Transform p' and l back to pixel coordinates Draw a line using cv2.line through p' and l A: I just did this a few days ago and it works just fine. Here's the method I used: Calibrate camera(s) to obtain camera matricies and distortion matricies (Using openCV getCorners and calibrateCamera, you can find lots of tutorials on this, but it sounds like you already have this info) Perform stereo calibration with openCV stereoCalibrate(). It takes as parameters all of the camera and distortion matricies. You need this to determine the correlation between the two visual fields. You will get back several matricies, the rotation matrix R, translation vector T, essential matrix E and fundamental matrix F. You then want to do undistortion using openCV getOptimalNewCameraMatrix and undistort(). This will get rid of a lot of camera aberrations (it will give you better results) Finally, use openCV's computeCorrespondEpilines to calculate the lines and plot them. I will include some code below you can try out in Python. When I run it, I can get images like this (The colored points have their corresponding epilines drawn in the other image) Heres some code (Python 3.0). It uses two static images and static points, but you could easily select the points with the cursor. You can also refer to the OpenCV docs on calibration and stereo calibration here. import cv2 import numpy as np # find object corners from chessboard pattern and create a correlation with image corners def getCorners(images, chessboard_size, show=True): criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0) objp = np.zeros((chessboard_size[1] * chessboard_size[0], 3), np.float32) objp[:, :2] = np.mgrid[0:chessboard_size[0], 0:chessboard_size[1]].T.reshape(-1, 2)*3.88 # multiply by 3.88 for large chessboard squares # Arrays to store object points and image points from all the images. objpoints = [] # 3d point in real world space imgpoints = [] # 2d points in image plane. for image in images: frame = cv2.imread(image) # height, width, channels = frame.shape # get image parameters gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) ret, corners = cv2.findChessboardCorners(gray, chessboard_size, None) # Find the chess board corners if ret: # if corners were found objpoints.append(objp) corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria) # refine corners imgpoints.append(corners2) # add to corner array if show: # Draw and display the corners frame = cv2.drawChessboardCorners(frame, chessboard_size, corners2, ret) cv2.imshow('frame', frame) cv2.waitKey(100) cv2.destroyAllWindows() # close open windows return objpoints, imgpoints, gray.shape[::-1] # perform undistortion on provided image def undistort(image, mtx, dist): img = cv2.imread(image, cv2.IMREAD_GRAYSCALE) image = os.path.splitext(image)[0] h, w = img.shape[:2] newcameramtx, _ = cv2.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1, (w, h)) dst = cv2.undistort(img, mtx, dist, None, newcameramtx) return dst # draw the provided points on the image def drawPoints(img, pts, colors): for pt, color in zip(pts, colors): cv2.circle(img, tuple(pt[0]), 5, color, -1) # draw the provided lines on the image def drawLines(img, lines, colors): _, c, _ = img.shape for r, color in zip(lines, colors): x0, y0 = map(int, [0, -r[2]/r[1]]) x1, y1 = map(int, [c, -(r[2]+r[0]*c)/r[1]]) cv2.line(img, (x0, y0), (x1, y1), color, 1) if __name__ == '__main__': # undistort our chosen images using the left and right camera and distortion matricies imgL = undistort("2L/2L34.bmp", mtxL, distL) imgR = undistort("2R/2R34.bmp", mtxR, distR) imgL = cv2.cvtColor(imgL, cv2.COLOR_GRAY2BGR) imgR = cv2.cvtColor(imgR, cv2.COLOR_GRAY2BGR) # use get corners to get the new image locations of the checcboard corners (undistort will have moved them a little) _, imgpointsL, _ = getCorners(["2L34_undistorted.bmp"], chessboard_size, show=False) _, imgpointsR, _ = getCorners(["2R34_undistorted.bmp"], chessboard_size, show=False) # get 3 image points of interest from each image and draw them ptsL = np.asarray([imgpointsL[0][0], imgpointsL[0][10], imgpointsL[0][20]]) ptsR = np.asarray([imgpointsR[0][5], imgpointsR[0][15], imgpointsR[0][25]]) drawPoints(imgL, ptsL, colors[3:6]) drawPoints(imgR, ptsR, colors[0:3]) # find epilines corresponding to points in right image and draw them on the left image epilinesR = cv2.computeCorrespondEpilines(ptsR.reshape(-1, 1, 2), 2, F) epilinesR = epilinesR.reshape(-1, 3) drawLines(imgL, epilinesR, colors[0:3]) # find epilines corresponding to points in left image and draw them on the right image epilinesL = cv2.computeCorrespondEpilines(ptsL.reshape(-1, 1, 2), 1, F) epilinesL = epilinesL.reshape(-1, 3) drawLines(imgR, epilinesL, colors[3:6]) # combine the corresponding images into one and display them combineSideBySide(imgL, imgR, "epipolar_lines", save=True) Hopefully this helps!
{ "pile_set_name": "StackExchange" }
Q: I'm trying to install rails and I think I just broke my Ubuntu installation, any help? I am following this guide to install ruby on rails to work with Apache and Passenger. I have followed it step for step and done every command in verbatim. Soon after running sudo nano /etc/apt/sources.list.d/passenger.list and inserting deb https://oss-binaries.phusionpassenger.com/apt/passenger trusty main I received this error on my toolbar: I tried to delete the file but it can't be deleted. Can I fix this? A: Plan A: Running: sudo apt-get update Then: sudo apt-get install -f Installing any unmet dependencies, and possibly then doing a restart should fix it. Plan B: Otherwise you should edit the file with: sudo nano /etc/apt/sources.list.d/passenger.list Once more and remove the line you added, then save the file and run: sudo apt-get update And the error should be gone (although a restart may also be necessary for the error to go away as I often find this is necessary even after the problem itself is fixed). Plan C: And finally if all of that failed, delete the file. As this file will be owned by root, you will need to use sudo to raise your privileges in order to delete it: sudo rm /etc/apt/sources.list.d/passenger.list The file should now have been removed, so run: sudo apt-get update And now the error should be gone.
{ "pile_set_name": "StackExchange" }
Q: How is (non-interfering) data communication possible over the tv spectrum? What is the technology used? I've heard that FCC-US (Federal Communication Commission - United States) has approved the free usage of TV spectrum for wireless communication. How is it possible to enable such data communication over TV bands without interfering the TV channels? What is the technology used? Is it available for unlicensed public use? A news link is given below http://gigaom.com/2012/09/06/need-spectrum-fcc-plans-tv-incentive-auction-for-2014/ A: After some research, i found that the wireless data communication over TV spectrum is made possible through the IEEE 802.22 (Super-Wifi) technology which is a Wireless Regional Area Network (WRAN) standard. It uses the white space available in the TV frequency spectrum. The interference with TV channels are prevented by means of Cognitive Radio (CR) technique as well as other spectrum sensing and allocation methodologies. IEEE 802.22 uses VHF/UHF TV broadcast bands between 54 MHz to 862 MHz. The standard is currently proposed for unlicensed public use. The theoretical range of this network is upto 100km with wired broadband compatible speed (1.5Mbps).
{ "pile_set_name": "StackExchange" }
Q: How to get max value from 2 tables Using Sql Server I want to get max value from two table Table1 ID Total 101 100 102 600 ..... Table2 ID Total 101 300 102 400 .... I want to get a max value from 2 table according to the id Expected Output ID Total 101 300 (max value in table2) 102 600 (max value in table1) .... ... How to make a Query Need Query Help A: SELECT ID, MAX(Total) FROM ( SELECT ID, Total FROM Table1 UNION ALL SELECT ID, Total FROM Table2 ) foo GROUP BY ID
{ "pile_set_name": "StackExchange" }
Q: Virtual Machine: Windows 7 on Ubuntu 11 or Ubuntu 11 on Windows 7? I wanted to begin with Android development. I intend to pursue it as a hobby and it is not my main job as a student. I use softwares like Matlab, COMSOL, MS Office, etc. on my current Windows PC. Therefore I needed isolation between my experimental projects and actual work. For that I am going to format my pc and re-install the OS. I have two options: 1. To install Ubuntu first and then install Windows 7 on top of it (using VirtualBox). 2. Or similarly install Windows 7 first and then install Ubuntu on its top. From a safety standpoint, it's my guess, that it's advisable to make my work OS (Win7) the base OS and then install my experimental OS (Ubuntu 11) on top. But please answer my following question purely from the standpoint of performance. Which is better: (Win + Virtual Ubuntu) or (Ubuntu + Virtual Win)? To frame it better I would ask, which is likely to be faster: a given random high performance software operating on Virtual Ubuntu (with Win base) or the same software operating on Virtual Win (with Ubuntu base)? Assume that the randomly picked high performance software has been designed to function on both operating systems (e.g. Matlab). P.S.: Also if you know a better alternative to VirtualBox, please let me know. A: From my experience Virtualbox performs quite good. For optimal performance and compatibility, you have to install additional packages though (i.e. for accessing USB drives etc, I guess you will need that anyway for android development). So, just use the system you want to use in your everyday work as the base and run the other one in virtualbox. For me, that's Ubuntu. For you it seems like Windows would be the natural choice. However I don't really see the need to isolate on the operating system level at all. It's quite common to have different softwares for different tasks running on the same computer, on the same system. Why do you think that would be a problem?
{ "pile_set_name": "StackExchange" }
Q: H2 Database: Abort Query I have a long running select query on an embedded H2 Database and want to allow the user to cancel the query. How can this be done? I cannot find anything about this. [UPDATE] To be more specific I'm running my query using JPA. How can the query be stopped? A: H2 supports a query timeout setting. You can set this in the database URL as follows: jdbc:h2:~/db/test;query_timeout=10000. (Maybe this is not the right approach for you, but it might be for others that read this question.) You can also cancel a query running in another connection (session) using the cancel_session function. But for this you need to enable the multi-threaded mode, which is currently not recommended for production use (it is still experimental in version 1.3.175).
{ "pile_set_name": "StackExchange" }
Q: Client Authentication Certificate error on Android after installing SSL certificate I've recently installed an SSL certificate for my website fantasyfeeder.com. This appears to be installed correctly when I use the online checker at ssllabs.com (https://www.ssllabs.com/ssltest/analyze.html?d=fantasyfeeder.com). The certificate also works fine in desktop browsers and Apple devices. The problem I have is when testing it on Android (in this case a Samsung Galaxy S4) on both the default Samsung browser and in Chrome. When I view the website using Wifi it works fine, but when I view it over the mobile network it gives the following error: SSL Connection error Unable to make a secure connection to the server. This may be a problem with the server or it may be requiring a client authentication certificate that you don't have. Error code: ERR_SSL_PROTOCOL_ERROR I can't work out why this error only occurs on Android and only when using the mobile network. A: A little NSFW warning would have been nice :D Anyway, your certificate and web server seems to be correct and should work with any browser supporting SNI (anything above Android 2.x). I believe that this is actually problem with the mobile provider of the phone (more so if it works via wifi). From this phone via mobile network are you able accesses https://google.com furthermore you can try other NSFW sites since some counties are keen on filtering those and might be terminating or trying to tamper with the SSL connection.
{ "pile_set_name": "StackExchange" }
Q: django - how to pass multiple values to a templatetag I am trying to pass multiple parameters to my template tag: @register.filter def val_color(val, min_val): if val >= min_val: return 'red' return 'black' template: {% for x in data.vals %} <font color="x|data.min_val|val_color">x</font> {% endfor %} this approach does not work. Any ideas how to do this? Note that it would be too messy if I have to convert x numbers into objects with a value and the min_val properties so I am hoping there is a proper solution for this issue. A: It is not clear what are you trying to do. In your function I don't see any usage of min_val. But let me give an example how filters work. Here is example of filter tags @register.filter def keyvalue(dict, key): """Filter to fetch a dict's value by a variable as key""" return dict.get(key, '') Usage of filter tag {{ weekday_dict|keyvalue:var }} Here weekday_dict is dict and 'var' is key I want to access. In keyvalue filter tag weekday_dict is first argument dict and var is second argument. To pass multiple arguments you can refer to link In short you can not easily pass multiple arguments in filter tag. You can pass it as comma seperated value, or pass them using multiple filters as given by one of answeres at link @register.filter(name='one_more') def one_more(_1, _2): return _1, _2 def your_filter(_1_2, _3) _1, _2 = _1_2 print "now you have three arguments, enjoy" {{ _1|one_more:_2|your_filter:_3 }} Update: As I can seen in your updated question. You do not need to pass multiple arguments Your filter tags is defined as: @register.filter def val_color(val, min_val): if val >= min_val: return 'red' return 'black' To use this tag you can update your template code to {% for x in data.vals %} <font color="{{ x|val_color:data.min_val }}">{{ x }}</font> {% endfor %} You can also set some default value to second argument and then you don't need to pass min value for default cases. Also don't forget to load filter before using them. For more details on tags refer to link
{ "pile_set_name": "StackExchange" }
Q: Print driver installs failing All of the Windows 7 64-bit Enterprise machines in my organization are failing to install a good number of printer drivers that previously installed without issue. This only happens with printer drivers. And not with all printer drivers. Just some. Network drivers, video drivers, etc. have had no problems. Here is part of setupapi.dev.log for a Dymo LabelWriter printer driver that is failing to install: dvi: {Plug and Play Service: Device Install for USBPRINT\DYMOLABELWRITER_450_TURBO\6&538F51D&0&USB001} ump: Creating Install Process: DrvInst.exe 09:36:58.071 ndv: Infpath=C:\Windows\INF\oem0.inf ndv: DriverNodeName=dymo.inf:DYMO.NTamd64.6.0:LW_450_TURBO_VISTA:8.1.0.363:usbprint\dymolabelwriter_450_aa08 ndv: DriverStorepath=C:\Windows\System32\DriverStore\FileRepository\dymo.inf_amd64_neutral_3a631b118b7a5828\dymo.inf ndv: Building driver list from driver node strong name... dvi: Searching for hardware ID(s): dvi: usbprint\dymolabelwriter_450_aa08 dvi: dymolabelwriter_450_aa08 inf: Opened PNF: 'C:\Windows\System32\DriverStore\FileRepository\dymo.inf_amd64_neutral_3a631b118b7a5828\dymo.inf' ([strings]) dvi: Selected driver installs from section [LW_450_TURBO_VISTA] in 'c:\windows\system32\driverstore\filerepository\dymo.inf_amd64_neutral_3a631b118b7a5828\dymo.inf'. dvi: Class GUID of device changed to: {4d36e979-e325-11ce-bfc1-08002be10318}. dvi: Set selected driver complete. ndv: {Core Device Install} 09:36:58.133 inf: Opened INF: 'C:\Windows\INF\oem0.inf' ([strings]) inf: Saved PNF: 'C:\Windows\INF\oem0.PNF' (Language = 0409) dvi: {DIF_ALLOW_INSTALL} 09:36:58.164 dvi: Using exported function 'ClassInstall32' in module 'C:\Windows\system32\ntprint.dll'. dvi: Class installer == ntprint.dll,ClassInstall32 dvi: No CoInstallers found dvi: Class installer: Enter 09:36:58.164 dvi: Class installer: Exit dvi: Default installer: Enter 09:36:58.180 dvi: Default installer: Exit dvi: {DIF_ALLOW_INSTALL - exit(0xe000020e)} 09:36:58.180 ndv: Installing files... dvi: {DIF_INSTALLDEVICEFILES} 09:36:58.180 dvi: Class installer: Enter 09:36:58.180 inf: Opened INF: 'C:\Windows\System32\DriverStore\FileRepository\dymo.inf_amd64_neutral_3a631b118b7a5828\dymo.inf' ([strings]) inf: Opened INF: 'C:\Windows\System32\DriverStore\FileRepository\dymo.inf_amd64_neutral_3a631b118b7a5828\dymo.inf' ([strings]) !!! dvi: Class installer: failed(0x00000490)! !!! dvi: Error 1168: Element not found. dvi: {DIF_INSTALLDEVICEFILES - exit(0x00000490)} 09:37:22.063 ndv: Device install status=0x00000490 ndv: Performing device install final cleanup... ! ndv: Queueing up error report since device installation failed... ndv: {Core Device Install - exit(0x00000490)} 09:37:22.063 dvi: {DIF_DESTROYPRIVATEDATA} 09:37:22.063 dvi: Class installer: Enter 09:37:22.063 dvi: Class installer: Exit dvi: Default installer: Enter 09:37:22.063 dvi: Default installer: Exit dvi: {DIF_DESTROYPRIVATEDATA - exit(0xe000020e)} 09:37:22.063 ump: Server install process exited with code 0x00000490 09:37:22.063 ump: {Plug and Play Service: Device Install exit(00000490)} Notice these lines in particular: !!! dvi: Class installer: failed(0x00000490)! !!! dvi: Error 1168: Element not found. dvi: {DIF_INSTALLDEVICEFILES - exit(0x00000490)} 09:37:22.063 ndv: Device install status=0x00000490 From what I have read, the "Element not found" error should be accompanied by an event describing what element was not found. The error that appears in Device Manager is "The driver cannot be installed because it is either not digitally signed or not signed in the appropriate manner." It appears to be signed fine though. It has an accompanying .CAT file and worked previously. And when installing, the following messages are logged in setupapi.dev.log: sto: {DRIVERSTORE_IMPORT_NOTIFY_VALIDATE} 09:36:56.277 inf: Opened INF: 'C:\Windows\System32\DriverStore\Temp\{272e2305-961c-7942-9ede-966f01047043}\dymo.inf' ([strings]) sig: {_VERIFY_FILE_SIGNATURE} 09:36:56.292 sig: Key = dymo.inf sig: FilePath = C:\Windows\System32\DriverStore\Temp\{272e2305-961c-7942-9ede-966f01047043}\dymo.inf sig: Catalog = C:\Windows\System32\DriverStore\Temp\{272e2305-961c-7942-9ede-966f01047043}\DYMO.CAT sig: Success: File is signed in catalog. sig: {_VERIFY_FILE_SIGNATURE exit(0x00000000)} 09:36:56.355 sto: Validating driver package files against catalog 'DYMO.CAT'. sto: Driver package is valid. sto: {DRIVERSTORE_IMPORT_NOTIFY_VALIDATE exit(0x00000000)} 09:36:56.402 sto: Verified driver package signature: sto: Digital Signer Score = 0x0D000005 sto: Digital Signer Name = Microsoft Windows Hardware Compatibility Publisher Now here's where it gets strange. If I take it off the domain, it installs fine. But it doesn't seem to have anything to do with Group Policy. I moved the machine to an OU that blocks inheritance, ran a gpupdate, ran rsop.msc to verify, and tried again. And it still didn't work. Likewise, I removed a machine from the domain, manually set all of the domain Group Policy settings in gpedit.msc, and tried that way, and it worked fine. So it seems like the Group Policy settings are irrelevant. What other domain-related issue could be causing this though? Any ideas on what to try next would be greatly appreciated. I'm not sure where to go from here. Thanks! A: One of the weirder problems I have dealt with before, for sure. We have a network share filled with driver files added to the DevicePath value under HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion. One of the driver packages that was recently added had an ntprint.inf file in it. The failing driver installs had an include line for ntprint.inf, and instead of using the local one in C:\Windows\INF, it was choosing one in our network driver store. I renamed the other ntprint.inf files to force it to use the one in C:\Windows\INF.
{ "pile_set_name": "StackExchange" }
Q: What is the use of the word "being" in this sentence? I have come across the sentence below from this site. Now, it is difficult, perhaps impossible, to bring forward one case of the hybrid offspring of two animals clearly distinct being themselves perfectly fertile. Is the word "being" used to represent the present progressive tense? Or how can I understand it grammatically? A: Here 'being' is being used as an adjective. The clause 'being themselves perfectly fertile' is describing the hybrid offspring. When we use a verb as an adjective we use the participle of the verb, usually these end with '-ing' (present tense) or '-en' (past tense). There's more information available with some examples at this site.
{ "pile_set_name": "StackExchange" }
Q: I am trying to get all the SQL caseID between two datetimes I am building a webservice in ASP.NET that will call a stored procedure to get all the cases between two dates. I am using SQL Management Studio Here is my code: ALTER PROCEDURE spGetNewCases (@startDate datetime, @endDate datetime) AS BEGIN SELECT caseID FROM tblCases WHERE dateOpened BETWEEN @startDate and @endDate END GO EXEC spGetNewCases However, I get the following error: "Could not find object spGetNewCases". In the IDE , the words "between" and "and" are highlighted in light gray instead of dark blue. Moreover, I would like to test it with two dates, say 2015-01-01 and 2015-01-04. The format of my datetime in my SQL server is datetime2((0),null). E.g. 2015-01-02 00:00:00. I would greatly appreciate the community's feedback. Thank you! EDIT: Thank you everyone for your great help! Here is my new code that works! -- procedure USE [vetDatabase_Wizard] GO ALTER PROCEDURE sp_GetNewCases (@startDate datetime, @endDate datetime) AS BEGIN SELECT caseID FROM tblCases WHERE dateOpened BETWEEN @startDate and @endDate END GO EXEC sp_GetNewCases '2015-01-01', '2015-04-04' A: If your SP is created then check your DB context. In SSMS there is a dropdown menu, you can also USE DBNAME. In ASP code it is in your connection string. If it is not created you will need to Create Procedure first and then you can Alter Procedure. You can call the SP like so : EXEC spGetNewCases '2016-03-01', '2016-05-01' Side note: System Stored Procedures use the sp prefix you probably should choose something different like sp_ or usp.
{ "pile_set_name": "StackExchange" }
Q: How do I unit test socket code with PHPUnit? I currently have a Socket class, which is basically just an OO wrapper class for PHP's socket_* functions: class Socket { public function __construct(...) { $this->_resource = socket_create(...); } public function send($data) { socket_send($this->_resource, $data, ...); } ... } I don't think I can mock the socket resource since I'm using PHP's socket functions, so right now I'm stuck as to how to reliably unit test this class. A: You appear to be missing a small piece to the unit test mindset. Your problem is easily solvable by creating a Stub object. Strangely, I give this answer time and time again, so it must be largely missed by a lot of people. Because I see so much confusion as to the differences between stubs and mocks, let me lay it out here, as well... A mock is a class that extends another class that the test is directly dependent on, in order to change behaviors of that class to make testing easier. A stub is a class that *implements an API or interface** that a test cannot test easily directly on its own, in order to make testing possible. ^-- That is the clearest description of the two I've ever read; I should put it on my site. Sockets have this nice feature where you can bind to port 0 for testing purposes (seriously, it's called the "ephemeral port"). So try this: class ListeningServerStub { protected $client; public function listen() { $sock = socket_create(AF_INET, SOCK_STREAM, 0); // Bind the socket to an address/port socket_bind($sock, 'localhost', 0) or throw new RuntimeException('Could not bind to address'); // Start listening for connections socket_listen($sock); // Accept incoming requests and handle them as child processes. $this->client = socket_accept($sock); } public function read() { // Read the input from the client &#8211; 1024 bytes $input = socket_read($this->client, 1024); return $input; } } Create this object and set it to listen in your test's setUp() and stop listening and destroy it in the tearDown(). Then, in your test, connect to your fake server, get the data back via the read() function, and test that. If this helps you out a lot, consider giving me a bounty for thinking outside the traditional box ;-)
{ "pile_set_name": "StackExchange" }
Q: The difference between indicative conditional and counterfactual I was confused about the difference between indicative conditionals and counterfactuals. Could someone please offer an elaboration? A: The difference is expressed by the late David Lewis in terms of two examples ('Counterfactuals, 1973) : Indicative conditional : 'If Oswald did not kill Kennedy, then someone else did'. Counterfactual conditional : 'If Oswald had not killed Kennedy, then someone else would have.' As Lewis points out, 1. is probably true and 2. may very well be false. Certainly, accepting 1. does not commit us to 2. and accepting 2. does not commit us to 1. Everything to do with counterfactuals soon becomes technical but I hope this note gives some idea of what the difference is.
{ "pile_set_name": "StackExchange" }
Q: To what does laying on of hands refer to in 1 Timothy 5:22? 1 Timothy 5 NASB [22]Do not lay hands upon anyone too hastily and thereby share responsibility for the sins of others; keep yourself free from sin. Does this refer to laying on hands on the sick or ordination into ministry? A: As you may remember, six principles comprise the foundation of the doctrine of Christ, and "laying on of hands" is among them: Hebrews 6:1-2 "Therefore leaving the principles of the doctrine of Christ, let us go on unto perfection; not laying again the foundation of repentance from dead works, and of faith toward God, of the doctrine of baptisms, and of laying on of hands, and of resurrection of the dead, and of eternal judgment." KJV Now we know that after Pentecost and the incident at Cornelius' house, there were no more instantaneous mass Spirit-baptisms: people who had not previously received the Holy Ghost would henceforth receive it through laying on of hands, which became the new norm. For example, Phillip preached to, healed, and water-baptized virtually everyone in the city of Samaria, but the Holy Ghost never fell on the Samaritans as a group. Then Peter and John arrived from Jerusalem and began laying hands on everyone, and they all were filled with the Spirit (Acts 8:18). Paul encountered a dozen of John Baptist's disciples on the coast of Ephesus (Acts 19:1) and likewise, after he preached to them and baptized them in water, laid his hands on them individually until they were all filled with the Spirit. Not only was the Holy Ghost given, but spiritual gifts were also imparted by the laying on of hands (1 Timothy 4:14, 2 Timothy 1:6). And of course the Gospels and the book of Acts record many healings and special blessings given through the laying on of hands by Jesus and the Apostles. So when Paul says in 1 Timothy 5:22 (KJV), "Lay hands suddenly on no man, neither be partaker of other men’s sins," it seems to me he is telling Timothy to exercise caution and discretion in dispensing God's grace by this means. Misusing the power to heal, bless, ordain, impart gifts, and fill with the Spirit by laying hands on a person whose heart is not right in God's sight (Simon for example, in Acts 8:18-21) would amount to giving that which is holy to dogs—which Jesus warned against.
{ "pile_set_name": "StackExchange" }
Q: c language memory management with string segments and fifos Good evening, I need to create a program that will ask for 3 segment names, each segment will ask for a value. my total memory is 2000 units. I need to use structs and fifos to communicate between a client (which will get the input from the user) and a server (which will process the total units). the client will send back the beginning and ending addresses for each segment, as well as any leftover memory. my issue once I run is that I'm getting a segmentation fault. I can't really see where I might be overwriting the memory or if I'm resetting the memory at some point. any observations or suggestions are welcome, thanks. client code: #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <fcntl.h> // creating the struct for the program struct probsiz{ int seg1 [1]; //segment 1 size int seg2 [1]; //segment 2 size int seg3 [1]; //segment 3 size int segsum [7]; //sum for all the segments int leftov [1]; //memory leftovers } ; struct probseg { char segment[64]; //segments }; main (void) { struct probsiz numbs; //defining the structures struct probseg names; int fda; // to write to character server int fdb; // to read response from character server //setting up the memory memset(numbs.seg1, 0, sizeof(struct probsiz)); //setting up memory for the first segment memset(numbs.seg2, 0, sizeof(struct probsiz)); //setting up memory for the second segment memset(numbs.seg3, 0, sizeof(struct probsiz)); //setting up memory for the third segment memset(numbs.segsum, 0, sizeof(struct probsiz));// setting up memory for the sum of all segments memset(numbs.leftov, 0, sizeof(struct probsiz)); //setting up memory for the first segment memset(names.segment, 0, sizeof (struct probseg));// setting up memory for the segments //reading the requested memory and segment name from the user printf("Client: Please enter requested memory 1: "); scanf("%d", &numbs.seg1[0]); while (numbs.seg1 <=0){ printf("Client: please enter a valid request: "); scanf("%d", &numbs.seg1[0]); } printf("Client: Please enter segment 1 name: "); scanf("%s", names.segment[0]); printf("Client: Please enter requested memory 2: "); scanf("%d", &numbs.seg2[0]); while (numbs.seg1 <=0){ printf("Client: please enter a valid request: "); scanf("%d", &numbs.seg2[0]); } printf("Client: Please enter segment 2 name: "); scanf("%s", names.segment[1]); printf("Client: Please enter requested memory 3: "); scanf("%d", &numbs.seg3[0]); while (numbs.seg3 <=0){ printf("Client: please enter a valid request: "); scanf("%d", &numbs.seg3[0]); } printf("Client: Please enter segment 3 name: "); scanf("%s", names.segment[2]); //send and write into the fifos printf("\nClient: Got the sizes sent now waiting for server's response\n"); write(fda, &numbs, sizeof(struct probsiz)); write(fda, &names, sizeof(struct probseg)); //read from the fifos read(fdb, &numbs, sizeof(struct probsiz)); if (numbs.leftov[0] >=0) { printf("\nClient: address for segment 1 is: %d - %d", numbs.segsum[0], numbs.segsum[1]); printf("\nClient: address for segment 2 is: %d - %d", numbs.segsum[2], numbs.segsum[3]); printf("\nClient: address for segment 3 is: %d - %d", numbs.segsum[4], numbs.segsum[5]); printf("\nClient: leftover memory is: %d", numbs.leftov[0]); printf("\nall done!"); } else { printf("\nClient: segment size is over the capacity, please try again"); printf("\nall done!\n"); } //this closes the fifos close(fda); close(fdb); printf ("\nall done!\n"); } server code: #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <fcntl.h> // creating the struct for the program struct probsiz{ int seg1 [1]; //segment 1 size int seg2 [1]; //segment 2 size int seg3 [1]; //segment 3 size int segsum [1]; //sum for all the segments int leftov [1]; //memory leftovers } ; struct probseg { char segment[64]; //for the segments }; main (void) { struct probsiz numbs; // structure definitions struct probseg names; int fda; // to read from client char int fdb; // to write to client char int finish; // lets me know that client is done int i; // because C needs this defined as int int m=2000; //total memory units int mtot; //memory total from the sum of all the segments //setting up the memory memset(numbs.seg1, 0, sizeof(struct probsiz)); //setting up memory for the first segment memset(numbs.seg2, 0, sizeof(struct probsiz)); //setting up memory for the second segment memset(numbs.seg3, 0, sizeof(struct probsiz)); //setting up memory for the third segment memset(numbs.segsum, 0, sizeof(struct probsiz));// setting up memory for the sum of all segments memset(numbs.leftov, 0, sizeof(struct probsiz)); //setting up memory for the first segment memset(names.segment, 0, sizeof (struct probseg));// setting up memory for the segments /* Create the fifos and open them */ if ((mkfifo("FIFO1",0666)<0 && errno != EEXIST)) { perror("cant create FIFO1"); exit(-1); } if ((mkfifo("FIFO2",0666)<0 && errno != EEXIST)) { perror("cant create FIFO2"); exit(-1); } if((fda=open("FIFO1", O_RDONLY))<0) printf("cant open fifo to write"); if((fdb=open("FIFO2", O_WRONLY))<0) printf("cant open fifo to read"); read(fda, &numbs, sizeof(struct probsiz)); //read the sizes read(fda, &names, sizeof(struct probseg)); //read the segments //printing out the characters on the server side to validate the data in strcpy(names.segment, names.segment); mtot=numbs.seg1[0]+numbs.seg2[0]+numbs.seg3[0]; numbs.leftov[0]=m-mtot; printf("Server: just got segment 1: %s", names.segment[0]); printf("Server: just got segment 1 size: %d", numbs.seg1[0]); printf("Server: just got segment 2: %s", names.segment[0]); printf("Server: just got segment 2 size: %d", numbs.seg2[0]); printf("Server: just got segment 3: %s", names.segment[0]); printf("Server: just got segment 3 size: %d", numbs.seg3[0]); //calculation of memory addresses numbs.segsum[0]=0; numbs.segsum[1]= numbs.seg1[0]-1; numbs.segsum[2]= numbs.seg1[0]; numbs.segsum[3]= numbs.segsum[2]+numbs.seg2[0]-1; numbs.segsum[4]= numbs.segsum[3]+1; numbs.segsum[5]= numbs.segsum[4]+numbs.seg3[0]; numbs.segsum[6]=0; write(fdb, &numbs, sizeof(struct probsiz)); if (numbs.leftov[0] >=0) { printf("\nClient: address for segment 1 is: %d - %d", numbs.segsum[0], numbs.segsum[1]); printf("\nClient: address for segment 2 is: %d - %d", numbs.segsum[2], numbs.segsum[3]); printf("\nClient: address for segment 3 is: %d - %d", numbs.segsum[4], numbs.segsum[5]); printf("\nClient: leftover memory is: %d", numbs.leftov[0]); printf("\nall done!"); } else { printf("\nClient: segment size is over the capacity, please try again"); printf("\nall done!\n"); } if(finish == 1) printf("\nServer: This says I am ready to close "); close(fda); close(fdb); unlink("FIFO1"); unlink("FIFO2"); } A: Not sure it is the only issue, but your memset is probably causing the segmentation fault. You have defined: struct probsiz{ int seg1 [1]; //segment 1 size size = sizeof(int) int seg2 [1]; //segment 2 size size = sizeof(int) int seg3 [1]; //segment 3 size size = sizeof(int) int segsum [7]; //sum for all the segments size = sizeof(int*7) int leftov [1]; //memory leftovers size = sizeof(int) } ; total size of probsiz is sizeof(int * 11) Now lets look at this line for example: memset(numbs.leftov, 0, sizeof(struct probsiz)); //setting up memory for the first segment You are telling the computer to fill 0's starting at numbs.leftov to the length of the entire struct. Hope I helped
{ "pile_set_name": "StackExchange" }
Q: how to interact with google bar chart from h-axis labels I'm using google bar charts as a navigational interface to display records with a date range by clicking on the h-axis labels which in my case show month and year. The problem is that there is no interactivity, eg the cursor changing when you roll over the dates on the h-axis. I'm accessing the h-axis label using: google.visualization.events.addListener(chart, 'click', function (e) { var bar_date = e.targetID.match(/hAxis#0#label#(\d+)/); This gets me an object from which I obtain the date associated with the bar in the chart. Can the clicked label on the h-axis be made to change via the same event? update: fiddle with working example as per accepted answer A: you can certainly change the chart labels. first, we must differentiate the h-axis labels from the rest of the chart labels. this can be done by using an attribute on the <text> element. here, the text-anchor attribute is used. when the label is clicked, the color is changed to red. see following working snippet... google.charts.load('current', { packages: ['corechart'] }).then(function () { var data = new google.visualization.arrayToDataTable([ ['date', 'value'], [new Date(2019, 0), 2924], [new Date(2019, 1), 2075], [new Date(2019, 2), 2516], ]); var container = document.getElementById('chart_div'); var chart = new google.visualization.ColumnChart(container); google.visualization.events.addListener(chart, 'click', function (e) { var bar_date = e.targetID.match(/hAxis#0#label#(\d+)/); var labels = container.getElementsByTagName('text'); var bar_labels = []; // get chart labels Array.prototype.forEach.call(labels, function(label) { // find h-axis labels if (label.getAttribute('text-anchor') === 'middle') { bar_labels.push(label); } }); // find label clicked if (bar_date) { bar_labels[bar_date[1]].setAttribute('fill', '#ff0000'); } }); chart.draw(data, { hAxis: { format: 'MM/yy', ticks: data.getDistinctValues(0) } }); }); <script src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div"></div> EDIT the structure of the data table should not make any difference, see following working snippet... google.charts.load('current', { packages: ['corechart'] }).then(function () { var data = new google.visualization.DataTable({ "cols": [ { "id": "Month", "label": "Month", "type": "string" }, { "id": "y0", "label": "y0", "type": "number" }, { "id": "y0", "label": "y0", "type": "number" }, { "id": "y0", "label": "y0", "type": "number" } ], "rows": [{"c": [{"v": "Sep 2014"}, {"v": 100}, {"v": 0}, {"v": 0}]}] }); var container = document.getElementById('chart_div'); var chart = new google.visualization.ColumnChart(container); google.visualization.events.addListener(chart, 'click', function (e) { var bar_date = e.targetID.match(/hAxis#0#label#(\d+)/); var labels = container.getElementsByTagName('text'); var bar_labels = []; // get chart labels Array.prototype.forEach.call(labels, function(label) { // find h-axis labels if (label.getAttribute('text-anchor') === 'middle') { bar_labels.push(label); } }); // find label clicked if (bar_date) { bar_labels[bar_date[1]].setAttribute('fill', '#ff0000'); } }); chart.draw(data, { hAxis: { format: 'MM/yy', ticks: data.getDistinctValues(0) } }); }); <script src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div"></div>
{ "pile_set_name": "StackExchange" }
Q: Passing a delegate as a type parameter and using it throws error CS0314 I'm trying to pass a delegate type as a type parameter so that I can then use it as a type parameter later on in the code, like so: // Definition private static class Register { public static FunctionObject Create<T>(CSharp.Context c, T func) { return new IronJS.HostFunction<T>(c.Environment, func, null); } } // Usage Register.Create<Func<string, IronJS.CommonObject>>(c, this.Require); However, the C# compiler complains: The type 'T' cannot be used as type parameter 'a' in the generic type or method 'IronJS.HostFunction<a>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.Delegate'." I attempted to fix this by appending "where T : System.Delegate" to the function, however, you can't use System.Delegate as a restriction on type parameters: Constraint cannot be special class 'System.Delegate' Does anyone know how to resolve this conflict? DOESN'T WORK (Argument and return type information is lost during cast): Delegate d = (Delegate)(object)(T)func; return new IronJS.HostFunction<Delegate>(c.Environment, d, null); A: If you look at https://github.com/fholm/IronJS/blob/master/Src/IronJS/Runtime.fs you'll see: and [<AllowNullLiteral>] HostFunction<'a when 'a :> Delegate> = inherit FO val mutable Delegate : 'a new (env:Env, delegateFunction, metaData) = { inherit FO(env, metaData, env.Maps.Function) Delegate = delegateFunction } In other words, you cannot use C# or VB to write your function because it requires using System.Delegate as a type constraint. I recommend either writing your function in F# or using reflection, like this: public static FunctionObject Create<T>(CSharp.Context c, T func) { // return new IronJS.HostFunction<T>(c.Environment, func, null); return (FunctionObject) Activator.CreateInstance( typeof(IronJS.Api.HostFunction<>).MakeGenericType(T), c.Environment, func, null); }
{ "pile_set_name": "StackExchange" }
Q: APSW (or SQLite3) very slow INSERT on executemany I have found the following issue with APSW (an SQLite parser for Python) when inserting lines. Lets say my data is data = [[1,2],[3,4]] APSW and SQLite3 allow me to do something like: apsw.executemany("INERT INTO Table VALUES(?,?)", b) or I can write some code that does the following: sql = "BEGIN TRANSACTION; INSERT INTO Table Values('1','2'); INERT INTO Table Values('3','4'); COMMINT;" apsw.execute(sql) When data is a long list/array/table the performance of the first method is extremelly slow compared to the second one (for 400 rows it can be 20 sec vs less than 1!). I do not understand why this is as that is the method shown on all SQLite Python tutorials to add data into a table. Any idea of what may be happening here? A: Thanks to Confuseh I got the following answer: Executing: apsw.execute("BEGIN TRANSACTION;") apsw.executemany("INERT INTO Table VALUES(?,?)", b) apsw.execute("COMMIT;") Speeds up the process by A LOT! This seems to be the right way of adding data (vs using my method of creating multiple INSERT statments). A: (Disclosure: I am the author of APSW). If you do not explicitly have a transaction in effect, then SQLite automatically starts one at the beginning of each statement, and ends at the end of each statement. A write transaction is durable - meaning the contents must end up on storage and fsync called to ensure they will survive an unexpected power or system failure. Storage is slow! I recommend using with rather than BEGIN/COMMIT in your case, because it will automatically rollback on error. That makes sure your data insertion either completely happens or not at all. See the documentation for an example. When you are inserting a lot of data, you will find WAL mode to be more performant.
{ "pile_set_name": "StackExchange" }
Q: Set up and forward mail from linux server to someone's inbox? I just made a website for someone who used to have a yahoo small business account so they could check "[email protected]" mail through their yahoo interface. Now they are not getting their email anymore probably because I changed the DNS records to point the domain to my server. How can I accept the email that he receives and forward to another email account? Is there anyway for me to not even receive the email and direct right to another email account he owns such as his aol account? A: If you have a mail server set up, you could try just adding an entry to the /etc/aliases file, something like: friend:[email protected] would redirect all mail you received address to friend@{any domain you receive mail for} to the new address. This is making a lot of assumptions about the mail setup on your server, and will probably require a little more configuration than that do do what you want. If the problem is DNS related however, you could probably just add an MX record pointing to wherever the DNS records pointed to previously. Then mail would go where it did before you made any changes and you shouldn't need to do anything else.
{ "pile_set_name": "StackExchange" }
Q: How to get the implicit solution of this PDE (Maple can but I don't manage with mathematica)? I asked this question about the analytical solution of the PDE: $$\partial_t c=\partial_x((c-a)(c-b)\partial_xc) $$ And I was given the answer that Maple gives the following implicit form as a solution: $$\eqalign{&{k_{{1}}}^{2}{k_{{2}}}^{2}{c}^{2} + \left( 2\,{k_{{1}}}^{4}k_{{2}}k_{{3 }}-2\,{k_{{1}}}^{2}{k_{{2}}}^{2}a-2\,{k_{{1}}}^{2}{k_{{2}}}^{2}b \right) c\cr &+ \left( 2\,{k_{{1}}}^{6}{k_{{3}}}^{2}-2\,a{k_{{1}}}^{4}k_{{ 2}}k_{{3}}-2\,b{k_{{1}}}^{4}k_{{2}}k_{{3}}+2\,ab{k_{{1}}}^{2}{k_{{2}}} ^{2} \right) \ln \left( -{k_{{1}}}^{2}k_{{3}}+ck_{{2}} \right)\cr & -2\,{k _{{2}}}^{4}t-2\,k_{{1}}{k_{{2}}}^{3}x-2\,{k_{{2}}}^{3}k_{{3}}-2\,k_{{4 }}{k_{{2}}}^{3} =0} $$ But when I'm doing the DSolve on Mathematica (I don't have Maple) and I get no solution! So my question is: can Mathematica give me that implicit solution? Assuming[{Element[a, Reals], Element[b, Reals]}, DSolve[D[f[x, t], t] == D[(f[x, t] - a) (f[x, t] - b) D[f[x, t], x], x], f, {x, t}]] --> DSolve[D[f[x, t], t] == D[(f[x, t] - a) (f[x, t] - b) D[f[x, t], x], x], f, {x, t}] (*meaning it just rewrites the equation with no solution*) A: So my question is: can Mathematica give me that implicit solution? The answer to your question is no. Check again may be in version 13 it will. This is not linear. It is hard enough to solve linear PDE's analytically. For completion, here is the complete Maple code to reproduce it from your Mathematica input, and verification in Maple. ClearAll[f, x, t, a, b]; pde = D[f[x, t], t] == D[(f[x, t] - a) (f[x, t] - b) D[f[x, t], x], x] DSolve[pde, f[x, t], {x, t}] Maple: restart; with(MmaTranslator); mma_input:=`Derivative[0, 1][f][x, t] == (-a + f[x, t])*Derivative[1, 0][f][x, t]^2 + (-b + f[x, t])*Derivative[1, 0][f][x, t]^2 + (-a + f[x, t])*(-b + f[x, t])*Derivative[2, 0][f][x, t]`: pde:=FromMma(mma_input): #translate the PDE from Mathematica to Maple syntax sol:=pdsolve(pde,f(x,t)): #solve the PDE $$ f \left( x,t \right) ={\it RootOf} \left( 2\,{{\it \_C1}}^{6}\ln \left( -{\it \_C3}\,{{\it \_C1}}^{2}+{\it \_C2}\,{\it \_Z} \right) {{ \it \_C3}}^{2}-2\,{{\it \_C1}}^{4}\ln \left( -{\it \_C3}\,{{\it \_C1} }^{2}+{\it \_C2}\,{\it \_Z} \right) a{\it \_C3}\,{\it \_C2}-2\,{{\it \_C1}}^{4}\ln \left( -{\it \_C3}\,{{\it \_C1}}^{2}+{\it \_C2}\,{\it \_Z} \right) b{\it \_C3}\,{\it \_C2}+2\,{{\it \_C1}}^{2}\ln \left( -{ \it \_C3}\,{{\it \_C1}}^{2}+{\it \_C2}\,{\it \_Z} \right) ab{{\it \_C2 }}^{2}+2\,{{\it \_C1}}^{4}{\it \_C2}\,{\it \_C3}\,{\it \_Z}+{{\it \_C1 }}^{2}{{\it \_C2}}^{2}{{\it \_Z}}^{2}-2\,{{\it \_C1}}^{2}{{\it \_C2}}^ {2}{\it \_Z}\,a-2\,{{\it \_C1}}^{2}{{\it \_C2}}^{2}{\it \_Z}\,b-2\,{ \it \_C1}\,{{\it \_C2}}^{3}x-2\,{{\it \_C2}}^{4}t-2\,{{\it \_C2}}^{3}{ \it \_C3}-2\,{\it \_C4}\,{{\it \_C2}}^{3} \right) $$ DEtools:-remove_RootOf(rhs(sol)); #to remove the RootOf in the solution $$ 2\,{{\it \_C1}}^{6}\ln \left( -{\it \_C3}\,{{\it \_C1}}^{2}+{\it \_C2 }\,f \left( x,t \right) \right) {{\it \_C3}}^{2}-2\,{{\it \_C1}}^{4} \ln \left( -{\it \_C3}\,{{\it \_C1}}^{2}+{\it \_C2}\,f \left( x,t \right) \right) a{\it \_C3}\,{\it \_C2}-2\,{{\it \_C1}}^{4}\ln \left( -{\it \_C3}\,{{\it \_C1}}^{2}+{\it \_C2}\,f \left( x,t \right) \right) b{\it \_C3}\,{\it \_C2}+2\,{{\it \_C1}}^{2}\ln \left( -{\it \_C3}\,{{\it \_C1}}^{2}+{\it \_C2}\,f \left( x,t \right) \right) ab{{\it \_C2}}^{2}+2\,{{\it \_C1}}^{4}{\it \_C2}\,{ \it \_C3}\,f \left( x,t \right) +{{\it \_C1}}^{2}{{\it \_C2}}^{2} \left( f \left( x,t \right) \right) ^{2}-2\,{{\it \_C1}}^{2}{{\it \_C2}}^{2}f \left( x,t \right) a-2\,{{\it \_C1}}^{2}{{\it \_C2}}^{2}f \left( x,t \right) b-2\,{\it \_C1}\,{{\it \_C2}}^{3}x-2\,{{\it \_C2}} ^{4}t-2\,{{\it \_C2}}^{3}{\it \_C3}-2\,{\it \_C4}\,{{\it \_C2}}^{3}=0 $$ Verify pdetest(sol,pde) ----> 0 OK
{ "pile_set_name": "StackExchange" }
Q: Get the width (in px) of a div sized by height (in %) I have a div that is sized by height, its width is empty. HTML <div id="slideshow"><img src="1.jpg"></div> CSS #slideshow { position: absolute; height: 90%; } I need to get its current width in px in order to place other elements on the page. I tried the following but since the CSS has no width, the value of the var is 0. $(document).ready(function() { var divWidth = $('#slideshow').width(); }); UPDATE I found the issue, the child img loads with a programmed delay, so obviously the var gets an initial value of 0. Is there a way to get the width of the div with a delay? A: You probably want to wait until the window is fully loaded. I added a setTimeout for you as well since you asked for it. $(window).load(function() { setTimeout(function() { var divWidth = $('#slideshow').width(); // put your function using divWidth in here as well. }, 500); });
{ "pile_set_name": "StackExchange" }
Q: User not creating in rspec I have this very weird issue that I cant really get why it's not working. This is the test that I'm running to test post comments https://gist.github.com/2794100 now I added 2 extra tests there to get an idea as to why it wasnt working the "user should exist" and "post should exist" to try and understand what's going on, all I gathered is that the user is not creating. Which is weird cause when I run this other test everything works fine https://gist.github.com/2794105 the user creation is a copy and paste, seeing as I have the email as a unique key I even tried running the test by itself without any other tests to make sure there was no conflict and I also tried running it with a fresh made database. if I run each command on the rails console everything works, it's just on the test itself that it doesnt work Any help would be great. Thanks A: Your test is full of lines like: before { @post.title == "Example Post"} It's just a comparison, not an assignment. This doesn't make any sense! You always refer to implicit subject (it { should ...), which in your case is a new instance of PostComment. You should specify what exactly are you testing, like: subject { @foo } Or just explicitly name it: it 'should be valid even if something is nil' do before { @foo.name = nil } @foo.should be_valid end
{ "pile_set_name": "StackExchange" }
Q: jQuery fading page redirect I have a working jQuery page redirect. I want to fade into the page I am loading. $(function(){ var count = 5; countdown = setInterval(function(){ $("p#redirect").html("You will be redirected in " + count + " seconds"); if (count == 0) { window.location = 'http://link.com'; } if(count < 0) { $("p#redirect").html("Please wait..."); } count--; }, 1000); }); A: I think you're looking for http://www.jansfreeware.com/articles/ie-page-transitions.html The problem is it's SO 1999. A: You can't do this with JavaScript, especially if it's another domain. You can fade content it from that page when you get there (the destination page itself doing it), but you can't instruct the browser to do anything at a page it's going to, only that page can execute script. This is mostly due to security reasons, e.g. redirecting you to https://myBank.com then running script, well, you see how that could quickly become a problem :)
{ "pile_set_name": "StackExchange" }
Q: Rollback Netbeans IDE Is there any way to rollback the Netbeans IDE updates? or a log on what updates were made? i Just updated netbeans and the Ctrl+Tab doesn't work anymore... it's really really annoying, it's been 1hr since i made the update and it's getting on my nerves... You have to wait half second for the little window to show up (The one that shows which file or subwindow it's going to focus on) so you can switch to the last file you've been on. If you don't wait for that window to show up, it switches to the "Navigator" subwindow, insead of the previous focused open file It should take you to the previous file just by tapping Ctrl+Tab NetBeans IDE 8.0.2 (Build 201411181905) A: Once a professor in college said to me "It is wise to restart"... and so i did. :( Sorry for the useless post.
{ "pile_set_name": "StackExchange" }
Q: Can Bluetooth Low Energy Beacons act as receivers? I am working on a project which involves sending data from many BLE beacons to many other BLE beacons. To be more specific, I have two groups of beacons: The first group consists of senders (or advertisers) which regularly (i.e. 500ms interval) only send (or advertise) their IDs, for example UUIDs, using a protocol like iBeacon. These beacons may be attached to moving objects. The second group of beacons consists of receivers that receive the broadcasted IDs sent by sender beacons which are in their proximity (and then send this data over wifi to a central system; but this is another topic and not my concern now). These beacons are stationary and may be mounted on walls. I know the first group (sender beacons) can do their job properly. The second group (receiver beacons) is my concern. I am not sure whether the beacons based on Nordic NRF51xxx or NRF52xxx chips can also act as receivers? If it is possible, any pointers or links to documentation/tutorials on how this can be done would be really appreciated. P.S. (If it is possible,) I was wondering whether beacons based on other chips like BLE chips produced by TI (e.g. CC2540) can also act as receivers? P.P.S. Is it possible to connect wifi modules to beacons based on Nordic NRF51xxx or NRF52xxx chips? A: Is it possible to connect wifi modules to beacons based on Nordic NRF51xxx or NRF52xxx chips? Depends highly on the module you selected. I've seen beacon modules that have none of the GPIOs easy accessible. But there are roughly similar priced breakout modules, which would allow easy access to UART,TWI and SPI peripherials. I am not sure whether the beacons based on Nordic NRF51xxx or NRF52xxx chips can also act as receivers? They can have both roles in theory, but that requires a significant amout of RAM. Thus you most likely wanted to use NRF52 based modules with larger RAM and flash memory. Note that you could try to use the mesh SDK for NRF52 instead of WLAN for communication between the fixed nodes. If it is possible, any pointers or links to documentation/tutorials on how this can be done would be really appreciated. Nordicsemi has its own infocenter. Their SDKs ship with a bunch of examples.
{ "pile_set_name": "StackExchange" }
Q: Permanently add Libraries in Python I have this simple piece of code in a file: frame = DataFrame(np.random.randn(2, 4), index=pd.date_range('1/1/2000', periods=2, freq='W-WED'), columns=['Colorado', 'Texas', 'New York', 'Ohio']) When I try to run the file I get error messages telling me that it doesn't know what to do with DataFrame, np, or pd. I can fix this easily by adding in " from pandas import DataFrame import numpy as np import pandas as pd My question: is there a way that I can avoid having to import these libraries within every file that I want to use those tools? I had imported them in the command line before running this file but this didn't seem to make a difference. New to Python. Thanks in advance for the help. Using Python 2 in the Canopy editor. A: Generally, if you are going to use a package/module, then you should* import it in every module that needs it. While it might be a little annoying writing the same imports over and over, it's better in the long run because it makes your code a lot more clear. e.g. you know what np or DataFrame is and where it comes from. I suppose that it's worth noting that you probably can get around this requirement by writing your own import hook, but . . .That's way too complicated a thing to do just to enable you to write code that will likely confuse your co-workers :-) *There are some conveniences that you can use to get around this in the interactive interpretter, but not in anything that gets imported via the normal mechanisms.
{ "pile_set_name": "StackExchange" }
Q: Can we restrict the ability of users to keep changing their names? Obviously one of the things that this site encourages is the building up of reputation which is a reflection of how the community perceives you. However, after spending a while in any given tag, you can't help but get familiar with people by their SO user name and interpret their input accordingly. This is especially the case with comments: you have to click-through to the user's home page as their rep is not immediately visible. Hence it's pretty confusing when certain users keep changing their names: Is that someone who I have learnt to respect? Is that trollish behaviour, or has the user made a genuine error/comunication problem? Do I give this user the benefit of any doubt? I must say that I find this is particularly the case on meta. I'm not suggesting that user-names should be permanently locked but perhaps there could be a limit to how often a name could be changed (e.g. no more than once per quarter year). A: Personally, I found it much more confusing when certain users who had gone months under one name suddenly switched to new names (and, in at least one case, new gravatar images). Rate-limiting would do nothing to prevent this, but banning name-changes outright would hamper those who picked unfortunate pseudonyms, were poorly-named by their parents, or decide to change their names out of some misguided ideas of transparency. So I suggest one small change: keep a list of past pseudonyms attached to each user's bio somewhere. Let them decay over time, perhaps dropping old names after a month or so. A: New rules: only one display name change is allowed every 30 days user accounts less than 2 days old may change their display name at will there is a 15 minute grace period after each change during which you may change your display name at will A: Though it's incredibly annoying, I'm reluctant to support a restriction on this. The questions and answers should feature and stand by themselves. It's a Q&A site, and as such WHO is posting the answer (and whether they were the same yesterday) isn't as important as the answer itself.
{ "pile_set_name": "StackExchange" }
Q: Scikit Random Forest Classifier does not evaluate to True Curious edge behavior. In this example, KNN exists gets printed, but Random Forest exists does not. Discovered it when checking for the presence of a model, where if model: ... was not triggered when the model is a Random Forest. from sklearn.ensemble import RandomForestClassifier from sklearn.neighbors import KNeighborsClassifier if KNeighborsClassifier(4): print('KNN exists') if RandomForestClassifier(n_estimators=10, max_depth=4): print('Random Forest exists') Why does this happen? A: Aha! It's because Random implements __len__: In [1]: from sklearn.ensemble import RandomForestClassifier ...: from sklearn.neighbors import KNeighborsClassifier ...: In [2]: knn = KNeighborsClassifier(4) In [3]: forest = RandomForestClassifier(n_estimators=10, max_depth=4) In [4]: knn.__bool__ --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-4-ef1cfe16be77> in <module>() ----> 1 knn.__bool__ AttributeError: 'KNeighborsClassifier' object has no attribute '__bool__' In [5]: knn.__len__ --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-5-dc98bf8c50e0> in <module>() ----> 1 knn.__len__ AttributeError: 'KNeighborsClassifier' object has no attribute '__len__' In [6]: forest.__bool__ --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-6-fbdd7f01e843> in <module>() ----> 1 forest.__bool__ AttributeError: 'RandomForestClassifier' object has no attribute '__bool__' In [7]: forest.__len__ Out[7]: <bound method BaseEnsemble.__len__ of RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=4, max_features='auto', max_leaf_nodes=None, min_impurity_split=1e-07, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1, oob_score=False, random_state=None, verbose=0, warm_start=False)> In [8]: len(forest) Out[8]: 0 And, according to the Python Data Model: object.__bool__(self) Called to implement truth value testing and the built-in operation bool(); should return False or True. When this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__(), all its instances are considered true. As one might expect, the len of a RandomForestClassifier is the number of estimators, but only after it is .fit: In [9]: from sklearn.datasets import make_classification ...: X, y = make_classification(n_samples=1000, n_features=4, ...: n_informative=2, n_redundant=0, ...: random_state=0, shuffle=False) ...: In [10]: X.shape Out[10]: (1000, 4) In [11]: y.shape Out[11]: (1000,) In [12]: forest.fit(X,y) Out[12]: RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=4, max_features='auto', max_leaf_nodes=None, min_impurity_split=1e-07, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1, oob_score=False, random_state=None, verbose=0, warm_start=False) In [13]: len(forest) Out[13]: 10
{ "pile_set_name": "StackExchange" }
Q: How to get this telerik reporting chart to render correctly. I have constructed a collection of data series items. Each data series has multiple data points. I am binding all this to a bar chart. That data binding is working fine however for some reason beyond my comprehension the reporting engine has decided that all my bar chart items will be aligned to the left side of the chart. Currently the way my report is rendering is unacceptable. Is there a way to fix this (Please see screenshot) Cheers ! A: The problem here was that all my data was bound to one ChartSeries. Creating one ChartSeries per each set of bars worked perfectly.
{ "pile_set_name": "StackExchange" }
Q: HTML element : Attribute ordering Analyzing several pages and noticing different approaches/writing styles, I am wondering if the order of HTML element attributes effect: browser performance rendering (noticeable or not) client/server computational resources anything? Is their a standard for the ordering that I should consider? I can only think of it effecting JQuery selections of nth attribute. ie: <div class="foo" id="bar"></div> vs <div id="bar" class="foo"></div> A: On the querying side: Using IDs for selectors O(1) instead of selecting by class O(n) Use classes for selections of multiple elements, IDs for selections with only one element (this will cause you to only use either an id or a class, usually never both) On the rendering side: Minimize browser reflow ( https://developers.google.com/speed/articles/reflow ) CSS: Use a declaration only once ( https://developers.google.com/speed/articles/optimizing-css )
{ "pile_set_name": "StackExchange" }
Q: iPhone - power button intermittent I recently updated my iPhone to iOS 6.1.2 and after the the update the top "power" button will not consistently lock the screen. Sometimes it needs to pressed 5 to 6 times before it will actually lock the phone. There does not appear to be anything physically wrong with the button. It still has a nice click feel and sound to it. I know the last update involved a bug fix for bypassing the lock the screen, so I thought others may be having this same issue. My guess is it would be a software bug, not a hardware issue. Other than restore the phone any suggestions? A: This actually ended up being a hardware issue. I took my iPhone 5 into an apple store and they said they have seen this happen many times. When I pressed on the right side of the button vs. the left side it seemed to work always. Strange coincidence it just started happening after the software update. Apple immediately replaced my iPhone 5, no fuss. Now everything works fine.
{ "pile_set_name": "StackExchange" }
Q: SCA SuiteScript query item to code I need to add an non-inventory item by internal id to the cart in SCA, how would I go about pulling that item and then adding it? The code samples I find are for pulling data always refer to views, I am thinking I need to pull it as an item, as I need to add it as an item using methods in LiveOrder.Model thanks for anyhelp you may give A: So I found out that the easiest way to do this is like this, the items are returns in a object array, so thanks for your help $.get('/api/items?id=10779&fieldset=details', function(obj) { }).done(function(obj) { });
{ "pile_set_name": "StackExchange" }
Q: Sector wise mean wind speed and directions in R I am trying to get mean wind speeds of a data-set based on its mean direction within a sector. It is fairly simple and the below program does the trick. I, however, am unable to automate it, meaning I have to manually input the values of fsector and esectorevery time. Also, the output is not where I would like. Please tell me a better way or help me on improving this one. ##Dummy Wind Speed and Directional Data. ws<-c(seq(1,25,by=0.5)) wd<-C(seq(0,360,by=7.346939)) fsector<-22.5 ##Starting point esector<-45 ##End point wind <- as.data.frame(cbind(ws,wd)) wind$test<- ifelse(wind$wd > fsector & wind$wd < esector,'mean','greater') mean<-rbind(aggregate(wind$wd,by=list(wind$test),mean)) meanws<-rbind(aggregate(wind$ws,by=list(wind$test),mean)) mean<-cbind(meanws[2,2],mean[2,2]) mean It would be great if i can choose the number of sectors and automatically generate the list of mean wind speeds and mean direction. Thanks. A: Actually I'm working with the same data. First I do a wind rose like this: And then, depending the direction, I put the data: max(Windspeed[direc >=11.25 & direc <= 33.75]) min(Windspeed[direc >=11.25 & direc <= 33.75]) mean(Windspeed[direc >=11.25 & direc <= 33.75]) I put he direccion in degrees. If you don't search that, I will be here waiting for help you.
{ "pile_set_name": "StackExchange" }
Q: How can I have shared views inside an Area in ASP.NET MVC 2.0? Can I have a Shared Views directory inside a Area where I can put partial views/user controls to be shared amongst the controllers of that specific Area? A: There is a a Views/Shared/ folder inside each area (or if there is not, you can create one - Areas/%AreaName%/Views/Shared). This works in the same way as the main Views/Shared/ folder, but just for that area.
{ "pile_set_name": "StackExchange" }
Q: How to add a new table/column to an existing table using mysql for a rails application? I am developing an API only application in rails 5 with MySQL. Can I add a new column to an existing table or new table directly in MySQL database instead of using rail generator(rails generate migration add_email_to_users email:string / rails generate model User)? If yes, how to create migration for this? A: You should do this by executing migrations. But, if you want directly , then you can execute the alter table statement in the mysql. For example: ALTER TABLE users ADD email varchar(30);
{ "pile_set_name": "StackExchange" }
Q: OpenCV-OpenGL interoperability I'm under Linux and compiled OpenCV 2.4.4 with OpenGL support, but I don't have any idea of how using the opengl_interop.hpp functions (some of them are even undocumented!, at least on my version of documentation). Looking at window.cpp in the section with OpenGL enabled I found some hints about the use of the functions setOpenGLContext, setOpenGLDrawCallback and updateView but I can't get working even this very simple piece of code: #include <opencv2/opencv.hpp> #include <GL/gl.h> #include <GL/glut.h> #include <opencv2/core/opengl_interop.hpp> using namespace cv; void on_opengl(void* userdata); int main(void) { VideoCapture webcam(CV_CAP_ANY); Mat frame; namedWindow("window", CV_WINDOW_OPENGL); setOpenGlContext("window"); while(waitKey(30) < 0) { webcam >> frame; setOpenGlDrawCallback("window", on_opengl); imshow("window", frame); updateWindow("window"); } return 0; } void on_opengl(void* userdata) { glLoadIdentity(); glTranslated(0.0, 0.0, 1.0); glRotatef( 55, 1, 0, 0 ); glRotatef( 45, 0, 1, 0 ); glRotatef( 0, 0, 0, 1 ); static const int coords[6][4][3] = { { { +1, -1, -1 }, { -1, -1, -1 }, { -1, +1, -1 }, { +1, +1, -1 } }, { { +1, +1, -1 }, { -1, +1, -1 }, { -1, +1, +1 }, { +1, +1, +1 } }, { { +1, -1, +1 }, { +1, -1, -1 }, { +1, +1, -1 }, { +1, +1, +1 } }, { { -1, -1, -1 }, { -1, -1, +1 }, { -1, +1, +1 }, { -1, +1, -1 } }, { { +1, -1, +1 }, { -1, -1, +1 }, { -1, -1, -1 }, { +1, -1, -1 } }, { { -1, -1, +1 }, { +1, -1, +1 }, { +1, +1, +1 }, { -1, +1, +1 } } }; for (int i = 0; i < 6; ++i) { glColor3ub( i*20, 100+i*10, i*42 ); glBegin(GL_QUADS); for (int j = 0; j < 4; ++j) { glVertex3d(0.2*coords[i][j][0], 0.2 * coords[i][j][1], 0.2*coords[i][j][2]); } glEnd(); } } What is the right way of using opengl on the webcam stream? bye! A: Apologize for my bad English, since it's not my native language. OpenGL is designed for rendering graphics, OpenCV is for computer vision. Thus I suggest you using CV in a GL-based application, instead of using CV API for rendering, callback etc. If all you want is a simple demo, then you can use freeGLUT to write a very simple program with a few callbacks, freeGLUT will handle window callbacks and GL context creation. ( GLFW or Qt is also OK ) Within the program, use the cv::ogl::Texture2D class to handle texture objects. Use Texture2D::copyFrom(...) and Texture2D::copyTo(...) to handle device/host memory transfer. Inside render callback, use standard GL routine to draw a fullscreen rect. This method is not efficient though, it works. #include <GL/glew.h> #include <GL/freeglut.h> #include <opencv2/opencv.hpp> #include <opencv2/core/opengl_interop.hpp> using namespace cv; //Global vars Texture2D g_img; void timer_cb( int ) { //...Update the content of g_img } void resize_cb( int w, int h ) { /*...*/ } void render_cb() { /* ...render g_img here */ g_img.bind(); #ifdef USE_FIXED_PIPELINE //use fixed pipeline for old-school GL rendering glMatrixMode( GL_MODELVIEW ); //Do some transformation glBegin(GL_QUADS); glTexCoord(...); glVertex**(...); ... glEnd(); #else //use shaders and VBOs for 3.1+ GL glBindProgram( ... ); glBindBuffer( ... ); glVertexAttribPointer( ... ); glDrawArrays( ... ); #endif } int main( int argc, char** argv ) { //...init GLUT, GLEW and other stuff glutMainLoop(); return 0; } Note: a. freeGLUT is recommanded instead of GLUT, they are TWO things. GLUT is outdated.But freeGLUT keeps supporting latest OpenGL version while expanding GLUT. b. You will probably need a GL loading library like GLEW to get GL function pointers c. Newer OpenGL (3.1+) no longer supports fixed pipeline rendering, therefore requires VBOs and shaders. If you target a lower version of GL, you will need to specify context version. This can be done via glutInitContextVersion( int major, int minor ). Lots of tutorials available on the web.
{ "pile_set_name": "StackExchange" }
Q: Laravel 5.2 - modify a model's builder So, I am using Laravel's built in soft Deletes and I have run into an issue. When I call withTrashed() it returns a query builder object. This would be fine for most cases but after I call this I then want to call a method like filter($this->filters) which is specific to the MODEL and I no longer have access to now that I only have a query builder. The reverse relationship also does not work as withTrashed() also wants a model where any kind of parsing method I can think of would return the model's query builder. So I was hoping to find a way to modify a model object with where clauses so I can add my filters and send the model to withTrashed() WITH the filters in place. I am honestly not sure how to do this. Worst case scenario I can have the filter method return the query builder without any global scopes and add the withTrashed() query on to the end manually. So the end result would be something like this: $model->filter($this->filters)->withTrashed(); Im not trying to get a giant collection and whittle it down. Even with chunking when you have a few million rows it can get slow really quick, especially when you bring in filtering. Technically, for a one off, I could just add multiple ->where() clauses to the query builder before i call ->get() but that would mean doing custom filtering in every controller's index. So i am looking to abstract it as a method in the model that parses filters sent in and adds them to the model (this is the part im not sure on. Kind of like: github.com/marcelgwerder/laravel-api-handler Any ideas? A: I believe you're looking for query scopes. You can create a new query scope on your model, and then it can be used like any other query builder method. For example, to create a filter() scope: class MyModel extends Model { public function scopeFilter($query, $filters) { // modify $query with your filters return $query; } } With that query scope defined, you call it like any other query builder method: $data = \App\MyModel::withTrashed()->filter(/* your filters */)->get(); You can read more about query scopes here.
{ "pile_set_name": "StackExchange" }
Q: Can anyone help me to find the last 2 digits of this operation. Find the last 2 digits of Thanks in advance A: Well, $1993^2\equiv 93^2\equiv 49\pmod{100}$ and so $1993^4\equiv49^2\equiv1\pmod{100}$. So $1993^x$ modulo $100$ only depends on what $x$ is modulo $4$. What is $x$ here modulo $4$?
{ "pile_set_name": "StackExchange" }
Q: include .as file inside .fla i open up .fla file, but when i click window->action, there is not actionscript inside it. may i know where else can i check the .fla file is importing .as file. where to check it in flash cs3? A: Opening the Actions window only shows you script attached to the frame you've currently selected. Try opening Window -> Movie Explorer. This lets you browse all the contents (including scripts) contained in the movie (make sure the "show: ActionScript" button is selected). Then look through any scripts you find for #include statements that may refer to external AS files. Note also that Flash objects can be attached to Classes, which will cause the .as file associated with the class to be imported. In the Library panel, check the "Linkage" column to see which objects have classes attached to them.
{ "pile_set_name": "StackExchange" }
Q: Sencha Touch 2 list is invisible in container I'm trying to write simple view with list on container but i have some problems. First of all, the List is not visible when I'm trying to do it like this: Ext.define('App.view.News', { extend: 'Ext.Container', but when it's written like this: Ext.define('App.view.News', { extend: 'Ext.navigation.View', it works. The problem is that when I write it with extend of navigation.View, im getting two toolbars on top and I can't find solution to disable the second one (added by the list). Full code: Ext.define('App.view.News', { extend: 'Ext.Container', //Ext.navigation.View xtype: 'news', requires: [ 'Ext.dataview.List', 'Ext.data.proxy.JsonP', 'Ext.data.Store' ], config: { style: ' background-color:white;', items: [ { xtype: 'toolbar', docked: 'top', title: 'News', minHeight: '60px', items: [ { ui: 'back', xtype: 'button', id: 'backButton', text: 'Back', }, { minHeight: '60px', right: '5px', html: ['<img src="resources/images/Image.png"/ style="height: 100%; ">',].join(""), }, ], }, { xtype: 'list', itemTpl: '{title},{author}', store: { autoLoad: true, fields : ['title', 'author'], proxy: { type: 'jsonp', url: 'https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://feeds.feedburner.com/SenchaBlog', reader: { type: 'json', rootProperty: 'responseData.feed.entries' } } } } ] } }); Help please! A: You need to give your container a layout and your list a flex property. The flex is important on lists as they don't have a viewable height since they scroll. I added a couple properties to your code below. Hope this helps. Ext.define('App.view.News', { extend: 'Ext.Container', //Ext.navigation.View xtype: 'news', requires: [ 'Ext.dataview.List', 'Ext.data.proxy.JsonP', 'Ext.data.Store' ], config: { style: ' background-color:white;', layout: 'vbox', // add a layout items: [ { xtype: 'toolbar', docked: 'top', title: 'News', minHeight: '60px', items: [ { ui: 'back', xtype: 'button', id: 'backButton', text: 'Back', }, { minHeight: '60px', right: '5px', html: ['<img src="resources/images/Image.png"/ style="height: 100%; ">',].join(""), }, ], }, { xtype: 'list', itemTpl: '{title},{author}', flex: 1, // add a flex property store: { autoLoad: true, fields : ['title', 'author'], proxy: { type: 'jsonp', url: 'https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://feeds.feedburner.com/SenchaBlog', reader: { type: 'json', rootProperty: 'responseData.feed.entries' } } } } ] } });
{ "pile_set_name": "StackExchange" }
Q: TextArea MaxLength - Supported or Not Supported? I was getting ready to add a jQuery plugin to support maxlength on textarea's and noticed that the MaxLength attribute is working natively on Safari, Chrome, and Firefox. Is this thanks to HTML5 or ? Does that means having a maxlength on textareas no longer requires a jQuery type plugin? Thanks A: Yes, maxlength was added to <textarea> in HTML5, so that's why you're seeing the behavior in newer browsers. Do you need a plugin? that depends...if you need to support older browsers, then yes.
{ "pile_set_name": "StackExchange" }
Q: Laravel | retrieving collection with relationship and except specific Ids i'm working for a car rental booking system so my plan is when a customer search if there is a available car in chosen Car Model, first : get the cars id's already taken for the date chosen by customer second : get all the cars except the not availavle cars, $collection = Booking::whereDate('dropoffday', '>' ,$date1) ->whereDate('pickupday' ,'<', $date2) ->get(['car_id']) ; if ($collection->isEmpty()) { $cars = Car::with('marques.images')->get(); return Response::json($cars); } $taken = []; foreach ($collection as $car) { $id = $car->car_id; array_push($taken,$id); } $cars = Car::with('marque.images')->except($taken); return Response::json($cars); } how must i rewrite this line $cars = Car::with('marque.images')->except($available); to get all cars with relationship except not available cars A: If your relations are set up correctly you can probably use the whereDoesntHave method like this: $cars = Car::with('marque.images')->whereDoesntHave('bookings', function ($query) use ($date1, $date2) { $query->whereDate('dropoffday', '>' ,$date1) ->whereDate('pickupday' ,'<', $date2); })->get(); return Response::json($cars);
{ "pile_set_name": "StackExchange" }
Q: C# Winform runtime load Windows Forms Controller Library I wanted to load a dll file runtime what contains Windows Forms Controller Library in C# Winform app. I need help. Thanks for help: Horbert A: Please use the below code using System.Reflection; Assembly dll= Assembly.Load("DALL"); //DALL name of your assembly Type MyLoadClass = dll.GetType("DALL.LoadClass"); // name of your class object obj = Activator.CreateInstance(MyLoadClass)
{ "pile_set_name": "StackExchange" }
Q: Is there a shared lead AND Gate IC? Hi I'm an electronics hobbyist still learning some basics of digital logic. I'm looking into building an arduino shield, but I want the arduino pinouts I'm using to be accessible when the shield is not enabled(by a single control pin). I know I could just wire up one lead of each of the gates 74HC08 to the enable line, but I'm wondering if there is a more convenient form factor for this kind of application, as the pins are somewhat awkwardly positioned. For example is there an IC where i[n] is passed to o[n] if enable is set? EN o0 o1 o2 |___|___|___| | | |___________| | | | | GND i0 i1 i2 To clarify, I'm not looking for a specific product, rather I assume this is a common problem, and would like to know what keywords to use to find such a device. A: If you're willing to use a pullup or pulldown, the 74XX125 and similar devices will reflect the inputs on their outputs if the enable line is asserted, and go high-impedance if deasserted.
{ "pile_set_name": "StackExchange" }