text
stringlengths
64
89.7k
meta
dict
Q: Generate all combinations of 10 digits without any repetition I am having an assignment about creating password through Java: Suppose you work in a safe selling company and your manager asked you to create a list of all the ten digit numbers between 0000000000 and 9999999999 without repeating a digit in the same number. What is the method to do this algorithm in JAVA? Here's what I've done so far: public static long generateNumber() { String s1 = "33333"; double d = Math.random(); d=d*100000.0; int i = (int) d; String s2 = String.valueOf(i); String s3=s1+s2; long m = Long.parseLong(s3); return m; } A: If you're looking for ten digit numbers without any duplicate digits, you're effectively looking to generate all permutations of all digits, i.e. the string "0123456789". There are other threads on SO to help you with this, for example these Generating all permutations of a given string Generate list of all possible permutations of a string
{ "pile_set_name": "StackExchange" }
Q: How to detect if user open two tabs for same session? I've done a booking application done using CakePHP which involves a few steps before the checkout page. In between these steps I store the information in the session. How it works is that Step 1 requires them to fill in their information. When going to Step 2, the information in Step 1 will be saved into the session object. As they proceed in the other steps, the process repeats. At the end when they checkout, all the data is then saved to the database. Everything works great if the user opens one instance of the application in the browser. But once they have another page or another tab opened for the same application in the same browser, problem happens. Let's say they have two instance of the application open in Tab A and Tab B. In Tab A they entered the details in Step 1 and proceed to Step 2. Then the user does the same thing in Tab B. At the last step when the user does a checkout, information in Tab A is the same as in Tab B. Right now, I can only think the best way is to prevent the user from opening the same application in two browser instance. Is there a way to detect and prompt the user to complete the booking form in Tab A first when they try to open another instance in Tab B? A: 1.The same problem (and solution) : https://sites.google.com/site/sarittechworld/track-client-windows 2.You can send information by POST or GET
{ "pile_set_name": "StackExchange" }
Q: What regular expression is required (for PHP preg_match)? One set of values in a MySQL table contains dimensions in varying formats, such as: 2140 × 910 Ø500 Ø600 × 1200 2000 × 1000 or Ø1500 These numbers are all dimensions in millimetres, and I would like a regular expression that can extract all the numbers (into an array, for example) so that I can convert them to inches and spew them back out in the same kind of format. Using regextester.com I have tested the pattern (\d+) and it works fine, highlighting any group of digits within a string. However, when I try and use this in my PHP code (below), the array of matches looks different to what I would expect. $pattern = '/(\d+)/'; $string = '2140 &times; 910'; preg_match ($pattern, $string, $matches); echo "<pre>"; print_r ($matches); echo "</pre>"; This code outputs: Array ( [0] => 2140 [1] => 2140 ) Thanks in advance for your help. A: try using preg_match_all()
{ "pile_set_name": "StackExchange" }
Q: How to Add a "Go Back" Toggle I have a code where it allows me to go to new text if I press "next" but I also want to create another button where it would allow me to go back to the previous text I was reading. I know I just write Previous but I don't know the javascript to go back. $(function() { $('.js-button').click(function() { if ($('div.active').next().hasClass('hidemsg')) { $('div.active').next('div').addClass('active').end().removeClass('active'); }else{ alert('Sorry, there is no next entry'); } }); }); .hidemsg { display: none; } .hidemsg.active { display: block; } <!DOCTYPE html> <html lang="en" class="no-js.june"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <div id="msg1" class="hidemsg active"> <p class="content__item-copy-text"> 1) Info here </p> </div> <div id="msg2" class="hidemsg"> <p class="content__item-copy-text"> 2) Info Here </p> </div> <div id="msg3" class="hidemsg"> <p class="content__item-copy-text"> 3) Info Here </p> </div> <div id="msg4" class="hidemsg"> <p class="content__item-copy-text"> 4) Info Here </p> </div> <div id="msg5" class="hidemsg"> <p class="content__item-copy-text"> 5) Info Here </p> </div> <a href="#" type="button" class="btn btn-default js-button">Next</a> A: Use this, works like a charm. // Next $('.js-button').click(function() { if ($('div.active').next().hasClass('hidemsg')) { $('div.active').next('div').addClass('active').end().removeClass('active'); }else{ alert('Sorry, there is no next entry'); } }); // Previous $('#previous_button').click(function() { if ($('.active').prev().hasClass('hidemsg')) { $('.active').prev('div').addClass('active').end().removeClass('active'); } else { alert('Sorry, there is no previous entry'); } }); .hidemsg { display: none; } .hidemsg.active { display: block; } <!DOCTYPE html> <html lang="en" class="no-js.june"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <div id="msg1" class="hidemsg active"> <p class="content__item-copy-text"> 1) Info here </p> </div> <div id="msg2" class="hidemsg"> <p class="content__item-copy-text"> 2) Info Here </p> </div> <div id="msg3" class="hidemsg"> <p class="content__item-copy-text"> 3) Info Here </p> </div> <div id="msg4" class="hidemsg"> <p class="content__item-copy-text"> 4) Info Here </p> </div> <div id="msg5" class="hidemsg"> <p class="content__item-copy-text"> 5) Info Here </p> </div> <a href="#" type="button" class="btn btn-default js-button">Next</a> <a href="#" type="button" class="btn btn-default" id="previous_button">Previous</a>
{ "pile_set_name": "StackExchange" }
Q: Get specific object from a list with a certain parameter I have a list of Account objects in self.accounts, and I know that only one of them will have a type attribute equal to 'equity'. What is the best (most pythonic) way to get only that object from the list? Currently I have the following, but I'm wondering if the [0] at the end is superfluous. Is there a more succinct way to do this? return [account for account in self.accounts if account.type == 'equity'][0] A: return next(account for account in self.accounts if account.type == 'equity') or return (account for account in self.accounts if account.type == 'equity').next() A: "Pythonic" means nothing. There is probably not any more "Succinct" solution than yours, no. Ignacios solution has the benefit of stopping once it finds the item. Another way of doing it would be: def get_equity_account(self): for item in self.accounts: if item.type == 'equity': return item raise ValueError('No equity account found') Which perhaps is more readable. Readability is Pythonic. :) Edit: Improved after martineaus suggestions. Made it into a complete method.
{ "pile_set_name": "StackExchange" }
Q: Pass HTML5-Validation-Event in hidden Tab to JavaScript-Function The Setup HTML-page with 2 tabs (build with Bootstrap Tabbable nav) both of the 2 tabs are surrounded by exactly one form-tag there is one submit button, which is constantly shown, independent of which tab is currently active only tab 1 contains form fields (the form fields have HTML5 "required"-attributes) The Situation the user has tab number 2 active... ...and fires "submit" let's assume, there is a HTML5 validation error on tab 1 The Problem the HTML5-validation is not shown (because the user has tab 2 active and the error is shown on tab 1) the user would manually have to switch to tab 1 to see the error The Question how can I manage to automatically switch to tab number 1 in this situation? is there an easy solution? (maybe passing the HTML5-Validation-Event to JavaScript somehow?) I would be very happy if somebody could help me out here. Creative ideas are very welcome. Thank you very much in advance. A: I thought about the whole problem, and came up with this: If there will be validation errors thrown, then they have to be on tab 1. In other words: validation errors can only arise in tab 1. So I decided to write my own submit-function! How I solved it (more detailed): 1.) "Degraded" the submit-button to a "plain old" button 2.) Added a onclick-event on that button, that fires the "submitTabs()"-Function 3.) Custom function function submitTabs() { // always get tab 1 to front $('a[href=#tab_with_fields]').tab('show'); // submit form manually $('form:first').submit(); } Now, whenever I submit the form, tab 1 gets active and will be shown. When there are HTML5-Validation errors, they will be displayed. If there are no errors, the tab gets active for a second or two, the form is being submitted and redirects to a different page.
{ "pile_set_name": "StackExchange" }
Q: Discontinuities of a monotonic function (Baby Rudin) In Rudin's Principles of Mathematical Analysis, he first proves that the set of points at which a monotonic function is discontinuous is at most countable (Theorem 4.30). Immediately following this proof, he remarks (Remark 4.31) "It should be noted that the discontinuities of a monotonic function need not be isolated. In fact, given any countable subset E of (a,b), which may even be dense, we can construct a function f, monotonic on (a,b), discontinuous at every point of E, and at no other point of (a,b)." I don't quite follow the logical flow here. What is the meaning of discontinuities not needing to be isolated? Does it mean that the set of points at which the function is discontinuous may have points that are limits points of the set? Is there a specific reason he is clarifying this via a remark? Does Theorem 4.30 mislead people to think that the discontinuities would be isolated? If so, why? Finally, what is the significance of the phrase, "which may even be dense" in the remark? Does being dense have anything to do with having points that aren't isolated points? A: According to the statement you may find a function which is discontinuos precisely in each rational number and continuous in every irrational number. I think the warning does not so much address the idea that this particular theorem may mislead people to think discontinuity points are isolated, rather the idea of continuity and our intuition with regard to the concept may lead to such a misconception. As for your last question: a dense set does in fact not contain isolated points. An isolated point $x$ of $S\subset X$ has a whole neighbourhood $U$ such that $U\cap S=\{x\}$, and this cannot not be true if $S$ is dense.
{ "pile_set_name": "StackExchange" }
Q: jQuery Mobile App + remote REST Webservice: Alternatives to JSONP? Currently I'm working on a jQuery Mobile website which will later be transformed into an app via Titanium. I have created a RESTful JSON web service, which is running on a different server than the jQuery Mobile application. The web service is consumed via AJAX using JSONP. One thing I find annoying is that I can't make use of HTTP error codes, because jQuery automatically aborts a JSONP call whenever the server issues an error. I can never get hold of the error code on the client side. Another thing is that JSONP only works with the HTTP verb GET, you cannot issue a JSONP POST for example (Currently, the web service is GET only, but that could change). Are there any alternatives to JSONP? Or is JSONP the only choice I have when using remote JSON web services with AJAX? For example, how do Twitter apps interact with the Twitter API (they have a REST API)? A: Your question is a nice illustration why people complain that jquery is too easy to adopt ;) JSONP is not ajax. There are no success and failure callbacks. JSONP is this: put the parameters in the url add &jsoncallback=random2745273 create a global variable random2745273 and put the callback reference in it add <script src="theurlhere"></script> to the head that's all you can do. The server returns random2745273({somedata}); and that's how your callback is called. If you want to report errors, then your server has to generate a correct code. You will not know what HTTP headers were sent. And this is the only way you can communicate cross-domain with an api. Sending cross-domain communicates is also possible with generating iframes, but it's hacky and rarely used. [edit] Ok, that got me thinking... I could use the iframe hack to wrap over the JSONP! And as usual - I wasn't the first to have the idea (and I'm finally humble enough to google my ideas expecting it ;) ) Here it is: http://beebole.com/en/blog/general/sandbox-your-cross-domain-jsonp-to-improve-mashup-security/ awesome [edit2] awww, I forgot... There's another one. window.postMessage It already got implemented in some browsers. If you don't have to be compatible with most of the browsers, you can start using it now! :)
{ "pile_set_name": "StackExchange" }
Q: Classification for High dimensional data I am trying to build a classification model with 1000+ features and I am performing the below steps but I am not sure if it's the correct way to do it Step 1. Finding Variable Importance using the entire dataset Step 2. Build a model using the subset of the features returned from Step 1 Once I get my new data I am splitting the data in training and testing and then performing cross validation on training data. My question is should I use CV while performing variable importance on the entire dataset? Thanks for your help! A: Before answering your question I would ask if you actually need so many variables or you can apply some dimensionality reduction technique (i.e. PCA)? It could boost your training speed and maybe result in a better model efficiency. Lets suppose for some reason (i.e. model explainability) you need the exact variables. You can still remove some of them without using feature importance (i.e. removing highly correlated ones, but there are other alternatives too). Indeed using only feature importance to remove variables can be dangerous. Imagine there is an important factor that highly influence your model but it shows up in several variables. In this case it can happen that the importance of this factor will be distributed among those variables. You will experience maybe that those variables are less important and remove them all thereby also eliminating an otherwise important factor. To answer your question. I would before step 1 take away my test set and only use the training set for any kind of modeling activity. It's a good practice to guarantee that your test set has never been seen by the model and it did not influence it in any way. In this case you can just remove less important features and measure the final results on the test set, it's not necessary to do CV. On the other hand you will probably face with the challenge how to define your threshold for eliminating variables based on feature importance.You can try to do some gridsearch on it. In this case you should avoid measuring the results of different models on the test set or you risk over-fitting on it. In this case using CV can be a good solution to define your threshold.
{ "pile_set_name": "StackExchange" }
Q: Given $\lambda$ and $A$, find $v$ such that $\lambda = v^{\intercal}Av$ If I know the values of $\lambda$ and $A$, how do I find a vector $v$ such that $\lambda = v^{\intercal}Av $? This isn't a homework question; I just ran into this problem in Real Life and realized I couldn't solve it! A: Start with any vector $v$ such that $v^{\intercal}Av\ne0$ and then $$v\rightarrow\sqrt{c}\ v\ \Longrightarrow\ v^{\intercal}Av\rightarrow c\ v^{\intercal}Av,$$ i.e. you can make the expression take any value. A: If $A$ is positive definite then for any $\lambda>0$ pick any vector $v\not=0$ and compute $$ c=v^TAv $$ Then $$ v\sqrt{\frac{\lambda}{c}} $$ satisfies your equation. A: Well, if $A$ is positive-definite one may compute a Cholesky decomposition $$ A = U^{\intercal} U$$ where $U$ is an upper triangular matrix, so your equation reduces to $$||Uv||^2=\lambda $$ Pick any vector $y$ on the $n$-sphere of radius $\sqrt\lambda$, solve $$Uv=y$$ for $v$ - which should be trivial, since, as I said above, $U$ is upper triangular - and you've found your solution. Of course this solution is immensely more expensive from a computational standpoint, but it has the advantage that it gives you a way to generate all possible solutions by varying $y$.
{ "pile_set_name": "StackExchange" }
Q: How to create a license value that belongs to one user SQL I have a java swing application that interacts with MySQL and i want to be able to create license key that allow the user to use the application, the user can only have one license number, here is what i have so far in SQL. CREATE TABLE User ( id INT AUTO_INCREMENT NOT NULL, License VARCHAR(100) NOT NULL, PRIMARY KEY(id) ); CREATE TABLE Address ( id INT AUTO_INCREMENT NOT NULL, LicenseNumber VARCHAR(255) NOT NULL, FOREIGN KEY (LicenseNumber) REFERENCES User(id), PRIMARY KEY(id) ); Is this the correct solution? also what would be a good way to generate the actual License Number with SQL? This is my solution to my question: Here is the SQL: CREATE TABLE User( id int NOT NULL auto_increment primary key, LicenseID VARCHAR(100) NULL, CONSTRAINT fk_license_number FOREIGN KEY (LicenseID) REFERENCES License(LicenseNumber) ); CREATE TABLE License( id INT AUTO_INCREMENT NOT NULL, LicenseNumber VARCHAR(100) NOT NULL UNIQUE, PRIMARY KEY (ID) ); For the LicenseNumber, i went ahead and used sha1 in my java code Java String to SHA1 A: You should rather use license id as a Foreign Key rather than a license number. Therefore schema should rather look like CREATE TABLE License ( id INT AUTO_INCREMENT NOT NULL PRIMARY KEY, LicenseNumber VARCHAR(40) NOT NULL UNIQUE ); CREATE TABLE User ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, LicenseID INT, CONSTRAINT fk_license_number FOREIGN KEY (LicenseID) REFERENCES License(id) ); If you need to you can generate SHA1 on db-side by using SHA1() function. E.g.: INSERT INTO License (LicenseNumber) VALUES (SHA1('Lisence1')); Here is SQLFiddle demo
{ "pile_set_name": "StackExchange" }
Q: Python: confused with classes, attributes and methods in OOP I'm learning Python OOP now and confused with somethings in the code below. Questions: def __init__(self, radius=1): What does the argument/attribute "radius = 1" mean exactly? Why isn't it just called "radius"? The method area() has no argument/attribute "radius". Where does it get its "radius" from in the code? How does it know that the radius is 5? class Circle: pi = 3.141592 def __init__(self, radius=1): self.radius = radius def area(self): return self.radius * self.radius * Circle.pi def setRadius(self, radius): self.radius = radius def getRadius(self): return self.radius c = Circle() c.setRadius(5) Also, In the code below, why is the attribute/argument name missing in the brackets? Why was is not written like this: def __init__(self, name) and def getName(self, name)? class Methods: def __init__(self): self.name = 'Methods' def getName(self): return self.name A: The def method(self, argument=value): syntax defines a keyword argument, with a default value. Using that argument is now optional, if you do not specify it, the default value is used instead. In your example, that means radius is set to 1. Instances are referred to, within a method, with the self parameter. The name and radius values are stored on self as attributes (self.name = 'Methods' and self.radius = radius) and can later be retrieved by referring to that named attribute (return self.name, return self.radius * self.radius * Circle.pi). I can heartily recommend you follow the Python tutorial, it'll explain all this and more. A: def __init__(self, radius=1): self.radius = radius This is default value setting to initialize a variable for the class scope.This is to avoid any garbage output in case some user calls c.Area() right after c = Circle(). In the code below, why is the attribute/argument "name" missing in the brackets? In the line self.name = 'Methods' you are creating a variable name initialized to string value Methods. Why was is not written like this: def init(self, name) and def getName(self, name)? self.name is defined for the class scope. You can get and set its value anywhere inside the class.
{ "pile_set_name": "StackExchange" }
Q: Facebook mobile app site url I am creating a Facebook application that will integrate into a mobile version of a site. My question is - are the Canvas URL and Post-Authorize URL's publicly visible? Will the user ever see these URLs or are they just for Facebook to my app's authentication purposes? The reason is that the mobile app is run through a mobile application that uses a webview and I do not wish to advertise this URL publicly. I am aware of the Android/iPhone SDK's, but am looking for the answers to the above questions. A: Facebook uses those URLs for security, and there is zero attempt to "hide" them (because it isn't possible to do so). It's up to your app to decide what happens when the user is on one of those URLs.
{ "pile_set_name": "StackExchange" }
Q: simple "Up a directory" button in htaccess? a while ago i was using htaccess to display some files, and recently i started that project again and found i had somehow deleted the "go up a level" button back then. Can anyone tell me what the code line in htaccess looks like to get this button back? Should be relatively simple but i just cant find it... heres what i got. Options +Indexes # DIRECTORY CUSTOMIZATION <IfModule mod_autoindex.c> IndexOptions IgnoreCase FancyIndexing FoldersFirst NameWidth=* DescriptionWidth=* SuppressHTMLPreamble # SET DISPLAY ORDER IndexOrderDefault Descending Name # SPECIFY HEADER FILE HeaderName /partials/header.html # SPECIFY FOOTER FILE ReadmeName /partials/footer.html # IGNORE THESE FILES, hide them in directory IndexIgnore .. IndexIgnore header.html footer.html icons # IGNORE THESE FILES IndexIgnore header.html footer.html favicon.ico .htaccess .ftpquota .DS_Store icons *.log *,v *,t .??* *~ *# # DEFAULT ICON DefaultIcon /icons/generic.gif AddIcon /icons/dir.gif ^^DIRECTORY^^ AddIcon /icons/pdf.gif .txt .pdf AddIcon /icons/back.png .. </IfModule> Options -Indexes A: Okay found the problem, it was simple, just not very observant when looking at the code. The line "IndexIgnore .." roughly in the middle.
{ "pile_set_name": "StackExchange" }
Q: syntax differences MySQL / PostgresSQL for foreign keys I have used many databases that other people built with foreign keys but have only recently been learning how to include them myself. Can see from this answer that the following two statements with and without 'FOREIGN KEY' are equivalent: author_id INTEGER REFERENCES author(id) author_id INTEGER, FOREIGN KEY(author_id) REFERENCES author(id) Then the following runs perfectly on Postgres but produces an error in MySQL: CREATE TABLE cities ( city varchar(80) primary key, location point ); CREATE TABLE weather ( city varchar(80) references cities(city), temp_lo int, temp_hi int, prcp real, date date ); (tested here - https://dbfiddle.uk/) What are the differences in the syntax for this between the two dialects? A: There are multiple ways to express a foreign key relationship in a create table statement. Here are some ways: Inline with the column definition: city varchar(80) references cities(city), Explicitly as a foreign key: city varchar(80), . . . foreign key (city) references cities(city), Explicitly as a constraint: city varchar(80), . . . constraint fk_weather_city foreign key (city) references cities(city), MySQL does not support the first version, with inlined constraints. Most if not all other databases do. The first version only handles foreign keys with a single column reference, so it is not as general as the other methods (and the syntax allows for naming constraints and for the foreign key keyword for the inline foreign key definitions). The explicit definition is more general (handling multiple columns). I tend to prefer explicitly named constraints. I do admit to sometimes using the inline version, simply because it is more convenient.
{ "pile_set_name": "StackExchange" }
Q: vue.js Bootstrap Modal Data Bind Fails I'm having some issues with binding data within a Bootstrap modal element. If I move everything in the modal-body class outside the modal container it works fine, however, vue.js doesn't pick up the bindings within the modal. Not sure if this has something to do with the modal styles (display: none; before it's opened) or conflicting scripts. The modal code looks like: <div class="modal fade" tabindex="-1" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <div v-if="loading" class="text-center"> <img src="loading.gif" alt="Loading"> </div> <div v-else> <div v-if="plugins.length > 0" class="list-group"> <a href="#" class="list-group-item" v-for="(index, plugin) in wpplugins"> <h5 class="list-group-item-heading"><strong>{{ plugin.name }}</strong> by {{ plugin.author }}</h5> <p class="list-group-item-text"><small>{{ plugin.desc }}</small></p> </a> </div> </div> </div><!-- /.modal-body --> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> This ends up just outputting the image and the syntax: How it appears in the modal when open A: Make sure your modal code is within the element that Vue is bound to
{ "pile_set_name": "StackExchange" }
Q: What is the difference between $ and $$? I have been going through some jQuery functionality. Can any one please give me some idea of what the difference is between the use of $ and $$? A: $ and $$ will work on any web page (if jQuery is not included also) on Google Chrome, Firefox and Safari browsers where $ returns first element of selector passed. Here, $ is document.querySelector $$ is document.querySelectorAll They are native functions of Google Chrome and Firefox browsers, you can see $ and $$ definition in Safari as well. Open Google in any of Google Chrome, Firefox or Safari, and open Developer Tools to check these results... (why Google, because they won't use jQuery or Moo tools) $('div'); // returns first DIV in DOM $$('div'); // returns all DIVs in DOM A: On jQuery documentation there is no $$ statement. jQuery has a default selector with $ character. Maybe this scripts uses another javascript lib and has some conflicts with jQuery. In this case, you can use jquery.NoConflict to avoid this kind of problem, and set another jquery selector. Something like: var s = jQuery.noConflict(); // something with new jQuery selector s("div p").hide(); // something with another library's using $() $("content").style.display = 'none'; If your code has somethig like to avoid conflicts: var $$ = jquery.noConfict();, you can use $$ as a jquery selector: $$("#element").method(); See more on the documentation: http://api.jquery.com/jQuery.noConflict/ A: jQuery is an object provided by jQuery. $ is another, which is just an alias to jQuery. $$ is not provided by jQuery. It's provided by other libraries, such as Mootools or Prototype.js. More importantly, $$ is also provided in the console of modern browsers as an alias to document.querySelectorAll. Except if it's overridden by another library. $ is also provided in the same way, as an alias to document.querySelector. See this answer for more information.
{ "pile_set_name": "StackExchange" }
Q: draw satellite covarage zone on equirectangular projection I need to draw borders of the observation zone of satellite on equirectangular projection. I found this formulas (1) and figure: sin(fi) = cos(alpha) * sin(fiSat) – sin(alpha) * sin (Beta) * cos (fiSat); sin(lambda) = (cos(alpha) * cos(fiSat) * sin(lambdaSat)) / cos(asin(sin(fi))) + (sin(alpha) * sin(Beta) * sin(fiSat) * sin(lambdaSat)) / cos(asin(sin(fi))) - (sin(alpha) * cos(Beta) * cos(lambdaSat))/cos(asin(sin(fi))); cos(lambda) = (cos(alpha) * cos(fiSat) * cos(lambdaSat)) / cos(asin(sin(fi))) + (sin(alpha) * sin(Beta) * sin(fiSat) * cos(lambdaSat)) / cos(asin(sin(fi))) - (sin(alpha) * cos(Beta) * sin(lambdaSat)) / cos(asin(sin(fi))); Cross-sections of the Earth in various planes: And equations system (2) with figure: if sin(lambda) > 0, cos(lambda) > 0 then lambda = asin(sin(lambda)); if sin(lambda) > 0, cos(lambda) < 0 then lambda = 180 - asin(sin(lambda)); if sin(lambda) < 0, cos(lambda) < 0 then lambda = 180 - asin(sin(lambda)); if sin(lambda) < 0, cos(lambda) > 0 then lambda = asin(sin(lambda)); Scheme of reference angles for the longitude of the Earth: Where: alpha – polar angle; fiSat, lambdaSat – latitude, longitude of satellite; Beta – angle which change from 0 to 2*Pi and help to draw the observation zone; fi, lambda – latitude, longitude of point B on the border of observation zone; I repeat both (1) and (2) formulas in cycle from 0 to 2*Pi to draw border of observation zone. But I am not quite sure in (2) system of equations. Inside intervals [-180;-90], [-90;90], [90;180] the zone draws correctly. Center at -35;45: Center at 120;60: Center at -120;-25 But on border of -90 and 90 degree it get messy: Center at -95;-50 Center at 95;30 Can you help me with formulas(1) and (2) or write another ones? double deltaB = 1.0*M_PI/180; observerZone.clear(); for (double Beta = 0.0; Beta <= (M_PI * 2) ; Beta += deltaB){ double sinFi = cos(alpha) * sin(fiSat) - sin(alpha) * sin(Beta) * cos(fiSat); double sinLambda = (cos(alpha) * cos(fiSat) * sin(lambdaSat))/cos(asin(sinFi)) + (sin(alpha) * sin(Beta) * sin(fiSat) * sin(lambdaSat))/cos(asin(sinFi)) - (sin(alpha) * cos(Beta) * cos(lambdaSat))/cos(asin(sinFi)); double cosLambda = (cos(alpha) * cos(fiSat) * cos(lambdaSat))/cos(asin(sinFi)) + (sin(alpha) * sin(Beta) * sin(fiSat) * cos(lambdaSat))/cos(asin(sinFi)) - (sin(alpha) * cos(Beta) * sin(lambdaSat))/cos(asin(sinFi)); if (sinLambda > 0) { if (cosLambda > 0 ){ sinLambda = asin(sinLambda); sinFi = asin(sinFi); } else { sinLambda = M_PI - asin(sinLambda); sinFi = asin(sinFi); } } else if (cosLambda > 0) { sinLambda = asin(sinLambda); sinFi = asin(sinFi); } else { sinLambda = -M_PI - asin(sinLambda); sinFi = asin(sinFi); } Point point; point.latitude = qRadiansToDegrees(sinFi); point.longitude = qRadiansToDegrees(sinLambda); observerZone.push_back(point); } A: I solve my problem. In (1) equation when calculating cosLambda should be + instead of -. double cosLambda = (cos(alpha) * cos(fiSat) * cos(lambdaSat))/cos(asin(sinFi)) + (sin(alpha) * sin(Beta) * sin(fiSat) * cos(lambdaSat))/cos(asin(sinFi)) + (sin(alpha) * cos(Beta) * sin(lambdaSat))/cos(asin(sinFi)); Sorry for disturbing.
{ "pile_set_name": "StackExchange" }
Q: How to get a CardHolder Name I am trying to read a smart card and i have been able to get some data from the smart card. The issue i am facing now is how to get the CardHolder name from the smart card. i have if(emv_is_tag_present(0x5F20) >=0){ tagDataLength = emv_get_tag_data(0x5F20, tagData, tagData.length); if(debug)Log.d(APP_TAG, "Carder "+ tagDataLength); appState.trans.setuserName(StringUtil.toString(AppUtil.removeTailF(ByteUtil.bcdToAscii(tagData,0, tagDataLength)))); } I do not really know the format to use in getting this field from the card while trying to use 5F20 Cardholder Name Indicates cardholder name according to ISO 7813 Card ans 2-26 '70' or '77' 2 26 primitive which i got from here This is the output i am getting 3030303030333830D160222101..but, whenever i try to convert that into a String...it gives back 00000380Ñ`"! which is not really the name of the Cardholder. Reading through the document (which link is posted there), i am not sure if i am using the correct format in getting my data. cos, in the document, i have ans 2-26. I do not really understand what it means. A: Tag 5F20 - CARD HOLDER NAME, if CARD returning the value of this tag, value will be hex string - Hex value of ASCII characters , what you need to do is to convert value to string and you will get the value personalized in the card. in the document, i have ans 2-26. I do not really understand what it means. sometimes we avoid to personalize card holder name inside the card and then we personalize " /" - space followed by / = 2 char. It is the minimum value for tag 5F20 defined in different EMV specification. Max value is 26 therefore 2-26 used for Tag 5F20. Hope this information will help you..
{ "pile_set_name": "StackExchange" }
Q: Ngrok returns 405 error while tunneling my localhost I have a web app bot that I would like to remote it so a few people can test it. I am using Bot Framework Emulator to test it locally and it works wonders, but I'm thoroughly failing to make ngrok host it. (I actually managed doing it using the ...azurewebsites.net/api/messages link my app has in Azure with another bot, but I couldn't with this one, so I'm trying with the link ngrok offers me - both bots, the one I managed and this one, are hosted in Azure, but I don't know how to make it available to remote access) Steps I'm taking: Deploy the app in Visual Studio so it runs on localhost:3979; Open port externally in ngrok using ngrok 3979 http -host-header=rewrite localhost:3979; Get one of the forwarding URLs ngrok provides me, like https://3d609207.ngrok.io Insert previous URL in Bot Framework Emulator; Click Connect. Both in ngrok and in Bot Framework Emulator returns me 405 Method Not Allowed. I tried accessing the link I inserted in Bot Framework Emulator and I normally have the page I would see while hosting my bot locally: Describe your bot here and your terms of use etc. Visit Bot Framework to register your bot. When you register it, remember to set your bot's endpoint to https://your_bots_hostname/api/messages But I can't send nor receive messages in Bot Framework Emulator. Additionally, ngrok prints this under the HTTP request headline: HTTP Requests ------------- POST / 405 Method Not Allowed GET /favicon.ico 200 OK GET / 200 OK My MSAppID and Password are configured properly in web.config, and compilation results in no error, so I doubt it's something on the code (unless there is some configuration in the code that prevents this bot being accessed remotely for a reason, but I have no idea). I would very much appreciate any help on this issue. Thanks for your time. A: Both in ngrok and in Bot Framework Emulator returns me 405 Method Not Allowed I can reproduce the issue on my side if I just provide https://xxxxxxxx.ngrok.io as message endpoint. Please try to specify https://xxxxxxxx.ngrok.io/api/messages as message endpoint, which works for me.
{ "pile_set_name": "StackExchange" }
Q: Create hot "sauce" from capsaicin extract There are a lot of hot sauces like "Blairs Mega Death" with more than 500.000 scoville heat units. However, they do have some odd taste, which I don't really like. So I'm thinking of creating a sauce from capsaicin or nonivamide extract. These are pure chemicals with 16.000.000 and 9.200.000 SHU respectively and would be perfect candidates for creating tasteless but very hot sauces. I already have nonivamide at home. Capsaicin is something I could get easily over the internet. Since you really can't just put them on your food, you have to dissolve or mix it with either a liquid or another powder. I don't think I can use a powder because that would never create a homogeneous mixture. So I'm thinking of a liquid. Facts: Capsaicin is soluble in alcohol, ether, benzene, slightly soluble in CS2, HCl, petroleum Nonivamide is soluble in methanol ... So, obviously these are all non-edibles, except for alcohol. But I don't really like the idea of consuming alcohol to every meal. It just doesn't sound very healthy. Does anyone have an idea of how to create a hot but tasteless "sauce" or powder from pure capsaicin / nonivamide? A: If capsaicin is soluble in alcohol, and you want a sauce with heat but no taste, there's a very simple way to do it if you do get a hold of pure capsaicin. Keep in mind that pepper sprays used for personal protection or law enforcement are in the range of 10% to 30% capsaicin. Bear spray (commonly seen here in Alaska) is required by law to be at or under 2% capsaicin. If you consider that then you've got to realize that you don't want a capsaicin concentration of greater than 1% anywhere near your food, and if you create a 1% solution, that's a product that you would only want to use by the micro-drop. So, if you're using your capsaicin solution by the micro-drop, how great of a health concern can it possibly be that the carrier of your capsaicin is vodka? There's more naturally occurring alcohol in a glass of fruit juice than in a micro-drop of vodka. So, just get yourself a little airline bottle of vodka, that will be 30mls of vodka. For this purpose, lets pretend that vodka weighs 1 gram per ml. That's not exactly right, vodka weighs slightly less, but calling 30mls of vodka 30 grams is fine for this. So, to achieve a 1% capsaicin solution in the vodka, you would add 0.3 grams of pure capsaicin to to the bottle. Shake and you're done. If you do get a hold of pure capsaicin, please treat it with great care and use protective clothing. Obviously if a 2% solution works as a bear repellant, the pure stuff could really hurt you. EDIT: Also, see my comment to GdD below. A: There's no point in getting pure capsaicin and diluting it yourself when you can buy capsaicin in just about any strength you want with all the work done for you. If you want something truly, painfully hot then get capsaicin 1 mil and then measure it into your dishes with an eye dropper. Be real careful with it, use gloves and don't sniff it, even at 1M it can still seriously hurt you. I second @Jolenealaska's warning that pure capsaicin is dangerous. In fact, you should not try to get the pure stuff even if it is available, get something somewhat diluted as it is safer and easier to work with. Pure capsaicin is used in industrial applications, you need to work in tiny quantities, requiring special equipment. It can also put you in the hospital, so just don't do it. As cool as it sounds "I made this sauce using pure capsaicin!", the reality is somewhat different.
{ "pile_set_name": "StackExchange" }
Q: Test if there are older posts in wordpress I've got this function: <?php next_posts_link( __( '<span class="meta-nav">&larr;</span> Older posts') ); ?> It creates a link if there are older posts. How do I do something on the condition that there are no older posts? Anything I do that uses this function only seems to echo the link. A: Simply add a get_ to the function :) <?php if (get_next_posts_link()) {} ?>
{ "pile_set_name": "StackExchange" }
Q: Partial reading and writing data via Spring Batch - OutOfMemoryError: GC overhead limit exceeded I'm running an application with spring batch jobs. When I try to collect and publish some data from one data source to another I get the following exception. o.s.batch.core.step.AbstractStep - Encountered an error executing step upload in job reviewsToYtBatchJob java.lang.OutOfMemoryError: GC overhead limit exceeded at com.mysql.jdbc.Buffer.<init>(Buffer.java:59) at com.mysql.jdbc.MysqlIO.nextRow(MysqlIO.java:1967) at com.mysql.jdbc.MysqlIO.readSingleRowSet(MysqlIO.java:3401) at com.mysql.jdbc.MysqlIO.getResultSet(MysqlIO.java:483) at com.mysql.jdbc.MysqlIO.readResultsForQueryOrUpdate(MysqlIO.java:3096) at com.mysql.jdbc.MysqlIO.readAllResults(MysqlIO.java:2266) at com.mysql.jdbc.ServerPreparedStatement.serverExecute(ServerPreparedStatement.java:1485) at com.mysql.jdbc.ServerPreparedStatement.executeInternal(ServerPreparedStatement.java:856) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2318) at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) at org.springframework.batch.item.database.JdbcCursorItemReader.openCursor(JdbcCursorItemReader.java:126) My questions are: How to get heap size parameter? How fetch data partially? It works only in a small amount of data. I've also tried this: reader.setFetchSize(CHUNK_SIZE); //JdbcCursorItemReader uploadStep.chunk(CHUNK_SIZE); //SimpleStepBuilder CHUNK_SIZE tried from 100 to 10000 If I limit selected data with the size it works, heap size was not exceeded. protected ItemReader<Review> reader() { JdbcCursorItemReader<Review> reader = new JdbcCursorItemReader<>(); reader.setDataSource(dataScource); reader.setSql( //sql query ); reader.setFetchSize(CHUNK_SIZE); reader.setRowMapper( (rs, rowNum) -> new Review( rs.getLong("reviewId"), //map data ) ); return reader; } private ItemProcessor<Review, ReviewTo> processor() { return review -> new ReviewTo( //parameters ); } private ItemWriter<ReviewTo> writer() { return new ItemWriter<>(client); } private TaskletStep uploadStep() { SimpleStepBuilder<Review, ReviewTo> uploadStep = new SimpleStepBuilder<>(stepBuilderFactory.get("upload")); return uploadStep .chunk(CHUNK_SIZE) .reader(reader()) .processor(processor()) .writer(writer()) .allowStartIfComplete(true) .build(); } @Bean public Job reviewsToYtBatchJob() { return jobBuilderFactory.get(JOB_NAME) .start(//generate table) .build()) .next(stepBuilderFactory.get("createTmpTable") .tasklet(//step) .build()) .next(uploadStep()) .next(stepBuilderFactory.get("moveTmpTableToDestination") .tasklet(//step) .build()) .build(); } A: There was not enough memory space. It worked with parameters CHUNK_SIZE = 100000 and -Xmx4g. There was a config file with arguments for virtual machine where I could increase heap size.
{ "pile_set_name": "StackExchange" }
Q: how to copy a file from local filesystem to hdfs file system using BDM(Informatica)? I am using Informatica version 10.2.1 and using the BDM I want to copy and paste a file from the local file system to the HDFS file system. I am very new to BDM and do not know how to do this. Currently I have created an object and filled the Read and Write parameters. I am using both Input Type and Output Type as command and issuing the command hdfs dfs -copyFromLocal -f /tmp/x.csv /tmp/x Any help is much appreciated. Edit Pasting an image of the error. A: Command input type in Informatica is used to read data. Like cat filename.txt stream data out to be read by Informatica and processed further. It's not meant to execute a shell command task. To get this done, you should use Command task in the workflow. ETL tool reads data from one source, performs transformation, and writes to a different place, called target. What you're trying to do here is a completely different thing, having nothing to do with ETL. Perhaps you can use a simple shell script? If you'd still like to get this done using Informatica in a proper way, you'd need to define a source, define your target, and map the data ports. Come back if you'd have issues. One final remark: you'd need to make sure the Integration server can access the source location. It seems to be your local file, it may not be possible to access from remote server.
{ "pile_set_name": "StackExchange" }
Q: OpenCV and reading data from OutputArrays or (Mat) I have a couple of problems with OpenCV's own functions for PnP and Rodrigues formula. I think it is related to cv::solvePnPRansac() cv::Mat w = cv::Mat::zeros(3,1,CV_32FC1); cv::Mat t = cv::Mat::zeros(3,1,CV_32FC1); std::vector<float> distortion = {0,0,0,0}; std::vector<cv::Point3f> tmp1 = eig_vec_to_cv3(pts); std::vector<cv::Point2f> tmp2 = eig_vec_to_cv2(pixels); cv::solvePnPRansac(tmp1, tmp2, eig_mat_2_cv(K),distortion, w, t,false, 100, 2.0f); cv::Mat R_ = cv::Mat::zeros(3,3,CV_32FC1); cv::Rodrigues(w,R_); std::cout<<"R_"<<std::endl; std::cout<<R_<<std::endl; std::cout<<R_.at<float>(0,0)<<std::endl; For std::cout<<R_<<std::endl it looks ok, but R_.at<float>(0,0) gives a trash number, like the memory is not allocated. The same holds for w and t. However, if I make like this: cv::Mat w_ = cv::Mat(3,1,cv_32FC1); w.at<float>(0,0) = 0.2; w.at<float>(0,1) = 0.4; w.at<float>(0,2) = 0.3; cv::Rodrigues(w_,R_); std::cout<<"R_"<<std::endl; std::cout<<R_<<std::endl; std::cout<<R_.at<float>(0,0)<<std::endl; It works just fine. This is a minimal (non)-working example: #include <opencv2/calib3d.hpp> #include <opencv2/opencv.hpp> #include <vector> int main() { cv::Mat w = cv::Mat(3,1,CV_32FC1); cv::Mat t = cv::Mat(3,1, CV_32FC1); std::vector<cv::Point3f> tmp1; std::vector<cv::Point2f> tmp2; for (int k = 0; k < 10; ++k) { cv::Point3f p1(0.2f+k, 0.3f-k, 7.5f-k); cv::Point2f p2(3.2f*k, 4.5f/k); tmp1.push_back(p1); tmp2.push_back(p2); } cv::Mat K = cv::Mat::zeros(3,3,CV_32FC1); K.at<float>(0,0) = 525.0; K.at<float>(0,2) = 234.5; K.at<float>(1,1) = 525; K.at<float>(1,2) = 312.5; K.at<float>(2,2) = 1.0f; std::vector<float> distortion = {0,0,0,0}; cv::solvePnPRansac(tmp1, tmp2, K,distortion, w, t,false, 100, 2.0f); std::cout<<w<<std::endl; cv::Mat R = cv::Mat::zeros(3,3,CV_32FC1); cv::Rodrigues(w,R); std::cout<<R<<std::endl; std::cout<<R.at<float>(0,0)<<std::endl; return 0; } Compiled with g++ main.cpp -I /usr/local/include/opencv4/ -o test -L /usr/local/lib/ -lopencv_calib3d -lopencv_core A: The reason is that the function cv::Rodrigues creates the output matrix of type CV_64FC1. So the values have to be read as follows: std::cout<<R.at<double>(0,0)<<std::endl; Even if we pre-allocate the output matrix to be of any other type ( say CV_32FC1 ), it will be reallocated by cv::Rodrigues to type CV_64FC1. In my opinion, the OpenCV documentation lacks clarity about the input and output types of many functions. In cases like these, one must be sure about the output types by printing the return value of Mat::type() function.
{ "pile_set_name": "StackExchange" }
Q: Where can I learn about apache I use apache web server for web development in python. The biggest problem I face with apache is setting up the environment. I can't understand thing like what is difference between /etc/apache2 and /private/etc/apache2. Also, things like /etc/private/apache2/httpd.conf and /etc/private/apache2/original/httpd.conf. Are they both same? Which one to change? Everytime I land in some set up problem and I keep on following instruction written by users like an idiot. Also, I don't understand how can apache point to custom directories(which files needed to be changed) and localhost would open up documents from that Directory(~Sites). I want to learn all about apache environment. What all directories mean? Which are the important file and which aren't? I went to apache docs but they are very messed up. Looks like it would take me years to read all of it. Can any one help me to find a nice startup article. Some tutorials? A: Seeing how you have a /private/etc directory I guess you're running Apache on MacOS X (please avoid putting linux windows and mac tags at the same time). This article should help you set up apache (ignore PHP related stuff). Basically, start by learning what httpd.conf file you should edit and look at Virtual Host/DocumentRoot. Having said that, you probably could use a very simple dev server or framework if you want to try your hand at python web-dev. I usually use Flask.
{ "pile_set_name": "StackExchange" }
Q: Variable defined by a function I'm doing this Hackerrank challange this is the question: Input Format: You have to complete the Node* Insert(Node* head, int data) method. It takes two arguments: the head of the linked list and the integer to insert. You should not read any input from the stdin/console. Output Format : Insert the new node at the tail and just return the head of the updated linked list. Do not print anything to stdout/console. /* Node is defined as var Node = function(data) { this.data = data; this.next = null; } */ And this is my code : function insert(head, data) { if(head){ while(head.next!==null){ head = head.next; } head.next = Node(data); }else{ head = Node(data); } } Does someone knows why it's wrong or can help me to understand how works? A: You should return something, your code should look like this: function(head, data) { if (head) { var nextNode = head while (nextNode.next !== null) { nextNode = nextNode.next } nextNode.next = new Node(data) } else { head = new Node(data) } return head }
{ "pile_set_name": "StackExchange" }
Q: xll work only on build computer I create *.xll with XLW lib. But it work only on build computer. If i rebuild my project on other computer xll work on it, but not my computer. Anybody have idea from this problem. A: This sounds like a classic case of you needing to deploy the runtime libraries of your tools to the machines which run the software. Your dev machines will have the necessary runtimes already. Exactly how to do that depends on which compiler you are using. The quick and dirty approach would be to link statically to the runtime.
{ "pile_set_name": "StackExchange" }
Q: int variable resetting when loading another scene in unity I created a football score calculator. I have a button that changes the scene, but when I change the scene and reopen it the score value is reset to 0. Here is the code: public class Main : MonoBehaviour { public Text plusUp; public int value = 0; public void button(int sc) { SceneManager.LoadScene(sc); } public void plus() { value++; plusUp.text = value.ToString(); } } A: 1. You can use the method Object.DontDestroyOnLoad on the object that hold the variable you want to save. It will keep the GameObject this script is attached too alive when another scene is loaded: void Awake() { DontDestroyOnLoad(this.gameObject); } See the documentation for more informations You can also make a Singleton but this design pattern is a little more complex as Unity will destroy it when you load another scene. You still have to use DontDestroyOnLoad see how to implement this pattern on their GitHub page 2. Or you can save the value on the disk before loading another scene and then load the value with PlayerPrefs helpers methods: public int value = 0; void Awake() { //Load the saved score (this value will be saved even if you restart the app) value = PlayerPrefs.GetInt("Score"); } public void button1(int sc) { //Save your value before you load the scene PlayerPrefs.SetInt("Score", value); SceneManager.LoadScene(sc); } See the documentation for more informations on the types. A: There's a few core concepts that would prove useful to understand this issue. Scope: Each scene operates in it's own scope. Any variables, objects, or changes that occur in one scene do not automatically transfer to another scene. When you start a scene, all objects in the scene are instantiated and initalized, and their Awake()/Start() methods are called if they are Monobehaviours. Initialization - When an object is instantiated, it is initialized with constructors or default values. Monobehaviours do not have constructors, so any variables will defer back to default values. Data persistence - When you change scenes, all game objects in the previous scene are destroyed, while all objects in the new scene are instantiated and initialized. Because all objects in the previous scene are destroyed, any values set on those objects disappear. You can prevent a GameObject from being destroyed with DoNotDestroyOnLoad(), but that does not overwrite the objects defined in the new scene. It is usually not advised to use DoNotDestroyOnLoad() as a core part of your game logic, as it often results in scenes being dependent on one another ("scene 1 has to define the values of a GameObject and pass it to scene 2 to be usable" = bad practice). Solving your problem It looks like you want score to persist as a value regardless of scene. Since all GameObjects and Monobehaviours are scoped within the scene, you can: Force the object to be scene-analagous using the Singleton pattern. Store score data to a file whenever it changes, and read from that file in the Start() method. My recommended approach: Use a ScriptableObject to hold the score, and refrence that object when changing the score and updating your gameObjects. ScriptableObjects are scoped at the project level, so they automatically persist between scenes.
{ "pile_set_name": "StackExchange" }
Q: Preventing directory traversal with web-facing application - are regular expressions bullet-proof? I am in a situation where I need to allow a user to download a file dynamically determined from the URL. Before the download begins, I need to do some authentication, so the download has to run through a script first. All files would be stored outside of the web root to prevent manual downloading. For example, any of the following could be download links: http://example.com/downloads/companyxyz/overview.pdf http://example.com/downloads/companyxyz/images/logo.png http://example.com/downloads/companyxyz/present/ppt/presentation.ppt Basically, the folder depth can vary. To prevent a directory traversal, like say: http://example.com/downloads/../../../../etc/passwd I need to obviously do some checking on the URI. (Note: I do not have the option of storing this info in a database, the URI must be used) Would the following regexp be bullet-proof in making sure that a user doesnt enter something fishy: preg_match('/^\/([-_\w]+\/)*[-_\w]+\.(zip|gif|jpg|png|pdf|ppt|png)$/iD', $path) What other options of making sure the URI is sane do I have? Possibly using realpath in PHP? A: I would recommend using realpath() to convert the path into an absolute. Then you can compare the result with the path(s) to the allowed directories. A: I'm not a PHP developer but I can tell you that using a Regex based protection for such a scenario is like wearing a T-shirt against a hurricane. This kind of problem is known as a Canonicalization vulnerability in security parlance (whereby your application parses a given filename before the OS has had a chance to convert it to its absolute file path). Attackers will be able to come up with any number of permutations of the filename which would almost certainly fail to be matched by your Regex. If you must use Regex, then make it as pessimistic as possible (match only valid filenames, reject everthing else). I would suggest that you do some research on Canonicalization methods in PHP.
{ "pile_set_name": "StackExchange" }
Q: VBA Global variables no longer declared after deleting worksheet I have some public worksheet variables that are first initialized when the workbook is open. I have a button that does this essentially: Dim Response As Variant Response = MsgBox("Are you sure you want to delete this worksheet?", vbYesNo + vbExclamation, "Confirm Action") If Response = vbNo Then GoTo exit sub End If 'Save workbook prior to deletion as a precaution ThisWorkbook.Save ActiveSheet.Delete For some reason after this runs, those worksheet variables are no longer declared and I have to reinitialize them every time. I tried adding my InitVariables macro call after the .Delete and it still doesn't work. Any reason why this might be happening? A: The reason is actually really simple - a Worksheet is a class in VBA, and its code module gets compiled along with the rest of your project even if it's empty. When you delete a worksheet and let code execution stop, the next time you run some code the VBE has to recompile the project because you removed a code module. That causes your custom class extensions to lose their state. Note that this does not happen unless the code stops running and is recompiled. This works just fine: Sheet1.foo = 42 'foo is a public variable in Sheet1 Sheet2.Delete Debug.Print Sheet1.foo 'Prints 42 A: I just tested it using Comintern foo. It's interesting that the standard module foo losses it value but the public foo variable in a worksheet module does not loses it's value.
{ "pile_set_name": "StackExchange" }
Q: Reassign the starting Julian date (July 1st = Julian date 1, southern hemisphere) My data set includes various observations at different stages throughout the year. year when samples were collected. site location of measurement Class physical stage during r of measurement date date of measurement Julian Julian date The final measurements usually occur in the early part of the new year, which is the summer time in the southern hemisphere. (e.g. summer is winter, spring is fall). year site Class date Julian 1 2009 10C Early 2008-09-15 259 2 2009 10C L2 2008-09-29 273 3 2009 10C L3 2008-12-15 350 4 2010 10C Early 2009-08-31 243 5 2010 10C L2 2009-09-14 257 6 2010 10C L3 2009-12-11 345 7 2012 10C Early 2011-08-23 235 8 2012 10C L2 2011-09-22 265 9 2012 10C L3 2011-12-03 337 10 2012 10C LSample 2012-03-26 86 11 2013 10C Early 2012-09-07 251 12 2013 10C L2 2012-09-30 274 13 2013 10C L3 2012-12-17 352 14 2014 10C Early 2013-09-02 245 15 2014 10C L2 2013-09-16 259 16 2014 10C L3 2013-12-16 350 17 2014 10C LMid 2014-01-07 7 18 2015 10C Early 2014-09-08 251 19 2015 10C L2 2014-09-30 273 20 2015 10C L3 2014-12-01 335 I am having a difficult time converting/reassigning the Julian start date to July 1st instead of January 1st. The dot plot below illustrates the final sampling that occurs at the beginning of the year (February-March). The chron package has an option to reorder the origin but I cannot get it to work properly with my data. library(chron) library(dplyr) data.date <- data %>% mutate(July.Julian = chron(date,format = c(dates = "ymd"), options(chron.origin = c(month=7, day=1, year=2008)))) Error in chron(c("2008-09-15", "2008-09-29", "2008-12-15", "2009-08-31", : misspecified chron format(s) length or July.Julian = chron(data$date, format = c(dates = "ymd"), options(chron.origin = c(month=7, day=1, year=2008))) Error in chron(c("2008-09-15", "2008-09-29", "2008-12-15", "2009-08-31", : misspecified chron format(s) length I am trying to start the Julian date as 1 instead of 182. Thoughts or suggestions are welcome. A: Assuming that July.Julian is supposed to be Julian days past July 1st: transform(date.data, July.Julian = as.chron(sprintf("%d-07-01", year)) + Julian) or date.data %>% mutate(July.Julian = as.chron(sprintf("%d-07-01", year)) + Julian) Note that one does not actually need chron here. Just replace as.chron with as.Date and either of these work.
{ "pile_set_name": "StackExchange" }
Q: What is the correct word order when lining up the same verb in three different tenses? In expressing the following idea in French, I got stuck on the correct word order. I waver back and forth between: Passé, Présent, then Futur: Peu m’importe ce qu'ils ont fait, font ou feront. La seule chose qui compte, ce sont les résultats. {or}: Présent, Passé, then Futur: Peu m’importe ce qu'ils font, ont fait ou feront. ... Incidentally, {Présent, Passé, then Futur} is how it works in German. Much as I'm tempted to go with the same order and plump for the 2nd construction, I somehow prefer the flow of the 1st option. Es ist mir einerlei, woran sie arbeiten, gearbeitet haben oder noch arbeiten werden. ... A: I find the order (past, present, future) more natural, but I think any order is ok. Choosing a different order puts a slightly different emphasis: if chronological order is not used, then the first time period is the focus of the sentence. Peu importe ce qu'ils ont fait, font ou feront. → treats all time periods equally, which emphasizes the untimeliness of the claim. Peu importe ce qu'ils font, ont fait ou feront. → this is about what they habitually do; they started this habit in the past and will continue in the future but the sentence is centered on the present. Peu importe ce qu'ils feront, ou font ou ont fait. → the sentence is about the future, and anecdotically what they did before that future moment is also unimportant. Peu importe ce qu'ils ont fait, ou feront ou font. → the sentence is about the past, and anecdotically what they did after that past moment is also unimportant. (The other two orders are also possible, but sound a bit weirder.)
{ "pile_set_name": "StackExchange" }
Q: Trouble setting request specific timeout in Elasticsearch DSL I'm trying to set a timeout for a specific request using elasticsearch_dsl. I've tried the following: from elasticsearch import Elasticsearch from elasticsearch_dsl import Search, F ... def do_stuff(self, ids): client = Elasticsearch(['localhost'], timeout=30) s = Search(using=client, index= 'my_index', doc_type=['my_type']) s = s[0:100] f = F('terms', my_field=list(ids)) s.filter(f) response = s.execute() return response.hits.hits Notes: When I change the doc_type to a type containing a million entities, the query runs fine. When I point the doc_type to a few billion entities, I get a timeout error showing the default timeout of 10 seconds. From the elasticsearch_dsl docs I even tried setting the default connection timeout: from elasticsearch import Elasticsearch from elasticsearch_dsl import Search, F from elasticsearch_dsl import connections connections.connections.create_connection(hosts=['localhost'], timeout=30) I still received the 10 second timeout error. A: So for some reason adding the parameter via .params() seems to do the trick: s = Search(using=client, index= 'my_index', doc_type=['my_type']) .params(request_timeout=30) The really interesting part is that the query now takes less than a second to run and the index is only on a single node.
{ "pile_set_name": "StackExchange" }
Q: Unsafe JavaScript error writing to C# variable I have some JavaScript in a page that takes the values passed by a module Window and assigns it to a C# variable, so it can be used within the code behind. So my JavaScript looks like: The JavaScript <script type="text/javascript"> function openSecure(args) { var manager = $find("<%= rwmSecure.ClientID %>"); var domain = '<%=ConfigurationManager.AppSettings("CPCDomain").ToString %>'; var URL; if (domain == 'localhost') { URL = 'http://localhost'; } URL += "/WindowPage.aspx?args=" + args; manager.open(URL, "rwSecure"); } function OnClientCloseSecure(oWnd, args) { var arg = args.get_argument(); if (arg) { var ResultCode = arg.ResultCode; document.getElementById("hdnResultCode").value = ResultCode; var AuthCode = arg.AuthCode; var ReferenceNumber = arg.ReferenceNumber; var TransactionID = arg.TransactionID; var ErrorCode = arg.ErrorCode; var ErrorDescription = arg.ErrorDescription; var CardNumber = arg.CardNumber; var PONumber = arg.PONumber; //document.getElementById('<%=btn.ClientID %>').click(); __doPostBack('pnlComplete', ''); } } </script> And to clarify this a bit more. The Module window is pulling in a page from localhost, but the Module window is being called from a page on localhost:61156. So once the javascript sets the variavle it also issues a click command on a asp.net button to run some code: C# Code protected void btn_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(hdnResultCode.Value)) { dspConfirm(); pnlComplete.Visible = false; pnlConfirm.Visible = true; } else { dspComplete(); pnlComplete.Visible = true; pnlConfirm.Visible = false; } } So when I run this I get a javascript error that says: Unsafe JavaScript attempt to access frame with URL http://localhost/SecurePayment.aspx?args=H4sIAAAAAAAEAOy9B2AcSZYlJi9tynt%2fSvVK1%2bB0oQiAYBMk2JBAEOzBiM3mkuwdaUcjKasqgcplVmVdZhZAzO2dvPfee%2b%2b999577733ujudTif33%2f8%2fXGZkAWz2zkrayZ4hgKrIHz9%2bfB8%2fIr578jMnL09%2b5k3etG%2fqbNlk07aolj%2bzi%2bdndsY7u%2f9PAAAA%2f%2f8VkT5ZIQAAAA%3d%3d&rwndrnd=0.23641548841260374 from frame with URL http://localhost:65116/ShoppingCart.aspx. Domains, protocols and ports must match. b.RadWindow._registerChildPageHandlersScriptResource.axd?d=vMihE91hOtu6KBE47c3D9AjqD9Il5YI4LpCLhSvp5YZn6p98cl2a_AbJJmNWVZfnmjtLnCnYEoaBHBC919OsikIEmKq8TGOzWNWN_HUBLLo8fW7DdN4EuN3Q076lAa_FOwh_Yk2b3DL-W2Fv0&t=38ec0598:1125 b.RadWindow._onIframeLoadScriptResource.axd?d=vMihE91hOtu6KBE47c3D9AjqD9Il5YI4LpCLhSvp5YZn6p98cl2a_AbJJmNWVZfnmjtLnCnYEoaBHBC919OsikIEmKq8TGOzWNWN_HUBLLo8fW7DdN4EuN3Q076lAa_FOwh_Yk2b3DL-W2Fv0&t=38ec0598:1143 (anonymous function)ScriptResource.axd:47 Sys$UI$DomEvent$addHandler.browserHandlerScriptResource.axd:4048 So is there any possible way around this or way to fix this? I've been scratching my head for two days and I'm ready to throw my keyboard. :) Thanks! A: Your javascript error is pretty informative. Unsafe JavaScript attempt to access frame with URL http://localhost/SecurePayment.aspx?args=... from frame with URL http://localhost:65116/ShoppingCart.aspx. Domains, protocols and ports must match. This sounds like an exception with the Same Origin Policy The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.[1] and The term "origin" is defined using the domain name, application layer protocol, and (in most browsers) port number of the HTML document running the script. Two resources are considered to be of the same origin if and only if all these values are exactly the same. Your script is running on your local machine in a site at a particular port, but trying to access a page on your local machine at a different port. I'd start there.
{ "pile_set_name": "StackExchange" }
Q: PHP: In shopping cart, Fatal error: Call to undefined function getCart() Recently I start with php and not because it gives me this error. This code is onyl for show articles and total price of shopping cart when reload page, using PHPSESSID, if they have a better idea or an alternative for that function, they are appreciated! INDEX.PHP <?php require("php/DB_Functionss.php"); ?> <!doctype html> <html lang="es"> <head> ........ </head> <body> <div id="infoShopCart"> <a href="contShopping"><img src="img/shopping_cart.png" width="30px"/> Artículos: <b id="cantArticles">0</b> Total: $ <b id="totalPriceArticles">0.00</b></a> <?php getCart(); ?> </div> ..... .... </body> </html> AND DB_Functions.php session_start(); $sessionID = $_COOKIE['PHPSESSID']; class DB_Functions { private $db; //put your code here //constructor function __construct() { require_once 'DB_Connect.php'; //connecting to database $this->db = new DB_Connect(); $this->db->connect(); } //destructor function __destruct() { } public function getCart(){ $query ="SELECT * FROM carrito ORDER BY id_pelicula"; $result = mysql_query($query) or die(mysql_error()); $no_of_rows = mysql_num_rows($result); if($no_of_rows > 0) { while ($row = mysql_fetch_assoc($result)) { $totalItems = $totalItems + 1; $movieTotalPrice = $movieTotalPrice + $row['precio_pelicula']; } echo ("Artículos: <b id='cantArticles'>"+$totalItems+"</b><otal: $ <b id='totalPriceArticles'>"+$totalPrice+"</b></a>"); } else { return false; } } A: You should initialize the object and then use its method. Like so: <div id="infoShopCart"> <a href="contShopping"><img src="img/shopping_cart.png" width="30px"/> Artículos: <b id="cantArticles">0</b> Total: $ <b id="totalPriceArticles">0.00</b></a> <?php $db_object = new DB_Functions(); $db_object->getCart(); ?> </div>
{ "pile_set_name": "StackExchange" }
Q: post checkbox values to a php file I'm trying to write a script to post with jQuery checkboxes ids that are checked(for php deletion script). I have something like this <form> <input type="checkbox" name="id" id="id" value='1'> <input type="checkbox" name="id" id="id" value='2'> <input type="checkbox" name="id" id="id" value='3'> <input type="button" name="DELETE" id="DELETE"> </form> So I want to post those values(ids) to a php file delete.php, how can I achieve this? A: I assume you wanted to achieve this through using jQuery ajax call to post to php Html <form> <input type="checkbox" name="id[]" id="id" value='1'> <input type="checkbox" name="id[]" id="id" value='2'> <input type="checkbox" name="id[]" id="id" value='3'> <input type="button" name="DELETE" id="DELETE"> </form> Javascript with jQuery var selected_values = $("input[name='id[]']:checked"); Directly post to delete.php <?php // $_POST['id'] will return an array. $selected_values = $_POST['id']; ?>
{ "pile_set_name": "StackExchange" }
Q: heroku pgbackups - how does it work? I'm trying to migrate a database over to a new app from an existing one using pgbackups, but I'm running into issues. I've read the documentation on heroku's dev site but I'm still getting errors. I've got the plugin installed for both databases and I can successfully go to my source db and copy/capture it. $ heroku pgbackups:capture -a costrecovery --expire HEROKU_POSTGRESQL_ONYX_URL (DATABASE_URL) ----backup---> b007 ←[0KCapturing... doneB - ←[0KStoring... done And then I change to the directory of the app I want to copy the db to and followed the instructions listed by heroku. The problem is that I don't know if it's not working because their is a bug or if it's because I'm not interpreting the instructions properly, which is entirely possible. First I'll list the instructions from heroku's dev site and then the commands I've tried. HEROKUS INSTRUCTIONS $ heroku pgbackups:restore DATABASE -a target-app \ `heroku pgbackups:url -a source-app` COMMANDS I'VE TRIED $ heroku pgbackups:restore DATABASE_URL -a boiling-reef-2060 \ > heroku pgbackups:url -a costrecovery ! Backup not found $ heroku pgbackups:restore HEROKU_POSTGRESQL_GREEN_URL -a boiling-reef-2060 \ > 'heroku pgbackups:url -a costrecovery' ! Backup not found $ heroku pgbackups:restore DATABASE -a boiling-reef-2060 \ > 'heroku pgbackups:url -a costrecovery' ! Backup not found $ heroku pgbackups:restore DATABASE_URL -a costrecovery-copy2 \ > heroku pgbackups:"https://s3.amazonaws.com/hkpgbackups/[email protected]/b 007.dump?AWSAccessKe > yId=AKIAJFDIRYCGYNFXR4FQ&Expires=1365184330&Signature=po0wZ982Jbx%2Fkv0bKk0iv P%2 > FRWac%3D" ! Resource not found Can someone helpl me out with the proper syntax? Thanks A: pgbackups can restore from a database on your same app, or from any pgbackups URL, as in, the one you captured in your source application/database. The instructions use backticks (`) to shell out and grab the pgbackups URL from your source application. The pgbackups:url command will provide such an URL. Try running this, to understand what's happening: heroku pgbackups:url -a costrecovery (assuming costrecovery is where you captured your data). Knowing this, you should be able to simply run: heroku pgbackups:restore DATABASE_URL --app boiling-reef-2060 `heroku pgbackups:url --app costrecovery
{ "pile_set_name": "StackExchange" }
Q: cambiar el home predeterminado laravel alguien sabe como cambiar elwelcome.balde.php que tiene por predeterminado laravel y cambiarlo por home.blade.php. Intenté configurandolo en el reoutes.php pero aun me sigue saliendo el welcome, ¿toca hacer una configuración para se ejecute? <?php Route::get('/', function(){ //return View::make('home'); return '55'; }); A: En Laravel 5.4 las rutas del "frontend" se encuentran normalmente en routes/web.php, ahí es donde debes hacer la modificación: <?php Route::get('/', function(){ return view('home'); }); https://laravel.com/docs/5.4/routing#basic-routing
{ "pile_set_name": "StackExchange" }
Q: Why are Cucumber and Capybara called that? Does anybody know why these names were selected for Capybara and Cucumber? Or were they just picked randomly? A: Cucumber was written by Aslak Hellesøy and named by his fiancee. He asked her for a "catchy, non-geeky sounding name" to replace its provisional name, "Stories". The name Capybara appears to be a play on "webrat", the name of a similar library which predated Capybara. (An actual capybara is a large rodent native to South America, not really a "rat" but related.)
{ "pile_set_name": "StackExchange" }
Q: Is this design for dependency injection easy to understand? I'm working on a project with a large existing codebase and I've been tasked with performing some re-engineering of a small portion of it. The existing codebase does not have a lot of unit testing, but I would like at least the portion I'm working on to have a full suite of unit tests with good code coverage. Because the existing codebase was not designing with unit testing in mind, I need to make some structural changes in order to support isolation of dependencies. I'm trying to keep the impact on existing code as small as possible, but I do have a bit of leeway to make changes to other modules. I'd like feedback on whether the changes I've made make sense or if there is a better way to approach the problem. I made the following changes: I extracted interfaces for all of the non-trivial classes on which my 'coordinator' class depends. The other developers grudgingly allowed this, with some minor grumbling. I modified the coordinator class to refer only to the interfaces for its operation. I could not use a DI framework, but I had to inject a large number of dependencies (including additional dependency instantiation as part of the class operation), so I modified the coordinator class to look like this (domain-specific names simplified): . public sealed class Coordinator { private IFactory _factory; public Coordinator(int param) : this(param, new StandardFactory()) { } public Coordinator(int param, IFactory factory) { _factory = factory; //Factory used here and elsewhere... } public interface IFactory { IClassA BuildClassA(); IClassB BuildClassB(string param); IClassC BuildClassC(); } private sealed class StandardFactory : IFactory { public IClassA BuildClassA() { return new ClassA(); } public IClassB BuildClassB(string param) { return new ClassB(param); } public IClassC BuildClassC() { return new ClassC(); } } } This allows for injection of a stubbed factory to return the mocked dependencies for unit testing. My concern is that this also means any user of this class could supply their own factory to change the way the class operates, which is not really the intention. This constructor is purely intended for unit testing, but it has the side effect of implying that additional extensibility was intended. I don't usually see this pattern in other classes I use, which makes me wonder if I'm over-complicating and if there's a better way to achieve the required isolation. NOTE: There's something weird going on with the code formatting, so I apologize for the poor formatting above. Not sure why it won't let me format it correctly. A: The proposed design is a variant of Constructor Injeciton sometimes known as Bastard Injection. In a greenfield situation I would consider Bastard Injection an anti-pattern, but it's a good compromise in a brownfield situation like the one you describe. You shouldn't really be concerned about the implied extensibility of the Coordinator class. Done correctly, testability is extensibility, so ideally the injected IFactory should represent a proper Domain Concept that enables variability. I understand that this can be difficult/impossible to achieve at a single stroke when you're refactoring from legacy code, but that's the direction in which your code base should be moving. In any case, if your coworkers already begrudge the extraction of interfaces, they are probably not very likely to interpret the IFactory constructor parameter as an extensibility point. Good luck.
{ "pile_set_name": "StackExchange" }
Q: How to export Apiary Blueprint as PDF, stand-alone HTML or similar "deliverable"? We need to export our Apiary Blueprint for task assignment purposes as a self containing "deliverable" like PDF or ZIP or similar. I'm aware of the feature request and the discussion below. Is it possible to "hack" something better than the poor html exporter? Maybe by injecting some css style into the page with chrome? Has somebody found a "good-enough" solution? A: Ján Sáreník mentioned aglio, you can make it work locally by the following steps. Save your API definition markdown (e.g. myfile.md) Install aglio npm install aglio -g Start aglio server aglio -i myfile.md -s Open localhost:3000 and download the HTML file Hack the HTML by commenting out the <div id="localFile" ...>...</div> warning Hack the HTML by replacing http://localhost:3000/ with empty string everywhere Aaand it's done.
{ "pile_set_name": "StackExchange" }
Q: Relation between Numerical methods and Chaos theory . Chaos theory is about the sensitive dependence on initial conditions, i.e., in a simple system, when the initial conditions are altered, this leads to an enormous change in the output. I was thinking about whether the same kind of effect applies in the case of numerical methods, where we discard errors like rounding off or chopping errors. However, here the difference is that we don’t change the initial conditions slightly, but rather we take the value by rounding or chopping off. Is there any resource where I can find a connection between these two? A: I think you are being too fixated on the typical setup of chaos theory. A numerical error is not really different from a change in the initial conditions: Suppose the state of your system at time $t$ is $y(t)$. If you evolve a system from $t_0$ to $t_1$ and then continue to evolve it to $t_2$, you may as well regard $y(t_1)$ instead of $y(t_0)$ as the initial condition for integrating to $t_2$. From yet another point of view, you do not consider initial conditions at all but trajectories with a certain distance. And here, a separation to numerical errors is equivalent to a separation of initial conditions. Of course, in reality you have more than one isolated numerical error, but this just makes things tediously complicated without any fundamental qualitative changes. This is why chaos theory typically considers initial conditions and not permanent noise. Finally, note the existence of the shadowing lemma, which states that you can find a true trajectory (without numerical errors) close to any numerically obtained trajectory.
{ "pile_set_name": "StackExchange" }
Q: How to get keycode on `focusout` or `focus` in the input field I am trying to get the focusin and focusout keycode of tab and shift+tab. but getting only 0 as a value. how to get the values on tab or shift+tab on a input field? here is my try: $('body').on('focusout', '#textbox', function(e) { if (e.which == 9) { e.preventDefault(); // do your code } console.log( e.which ); //0 }); Fiddle A: As you have seen, the focusout event doesn't expose a which attribute in the event object. You'll have to work with the keydown event. (You can't use keyup because the element loses focus when you press the tab key down, not when you let it up, so your text box doesn't get a keyup event when you tab away from it.) Here's a bit of code that seems to do what you're looking for: var cKey; var cKeyShifted; $('body').on('keydown', '#textbox', function(e) { cKey = e.which; cKeyShifted = e.shiftKey; }); $('body').on('focusout', '#textbox', function(e) { $('#log').html('cKey = ' + cKey + ' ' + cKeyShifted); //got to clear the variables, otherwise you can tab out of the box, click //back in, click out of it again, and they will not have changed cKey = 0; cKeyShifted = false; }); So, store e.which to a variable in the keydown event. Then in the focusout event, evaluate (and clear) the variable. If it isn't 9, then you didn't use the tab key to lose focus. Please note that tab and shift+tab both have the same e.which value. You have to evaluate the shiftKey attribute of the keydown event to determine whether the Shift key was pressed with the Tab key.
{ "pile_set_name": "StackExchange" }
Q: 安定結婚問題の「絶望の定理」の証明 グラフ理論において、安定結婚問題があります。 ある2部グラフの特定の安定マッチングにおいて、ペアを作れなかった人(たとえば男性数>女性数でのマッチングで存在)は、どのような安定マッチングにおいてもペアが作れないことを、安定結婚問題における「絶望の定理」と呼ぶらしいのですが、この定理の証明を見つけられずにいます。 証明自体、もしくは証明のソースをご存知の方はいらっしゃいますでしょうか。 A: @argus さんの情報を情報をもとに、調べて行った結果、 https://cs.stackexchange.com/a/37942/37273 (man-oriented な Gale-Shapley で man-optimal (最大元)かつ woman-pessimal (最小元)が得られる) と https://math.stackexchange.com/q/978729/260854 (1. optimal, 任意の matching, pessimal の3つの間で、パートナーの有無は、単調増加(語弊あり?)する 2. ある参加者のパートナーの有無が stable matching 間で変わったとすると、1. の結果から玉突き事故のようなことが起こってしまうので、そんなことは起こらない) によって、説明できそうでした。
{ "pile_set_name": "StackExchange" }
Q: MySQL Workbench não inicia Tenho trabalhado diariamente no mysql workbench. Acontece que do nada, a ferramenta deixou de funcionar. Carrego no ícone e não acontece nada. Já tentei reiniciar o computador assim como reiniciar o serviço "MySQL56" mas sem efeito. Fui consultar o ficheiro wb em "C:\Users\Pedro\AppData\Roaming\MySQL\Workbench\log\wb" e tem o seguinte erro: "Workbench]: Console redirection failed." Alguém sabe como posso resolver isto? A: Como descobrir e reportar os bugs do MySQL Workbench: # Microsoft Windows shell> cd "C:\Program Files (x86)\MySQL\MySQL Workbench CE 6.3.4\" shell> MySQLWorkbench.exe -log-level=debug3 # OS X shell> cd /Applications shell> MySQLWorkbench --log-level=debug3 # Linux (Ubuntu) shell> cd /usr/bin shell> mysqlworkbench --log-level=debug3 Diretórios de criação dos logs: Windows 7: C:\Users\[user]\AppData\Roaming\MySQL\Workbench\log OSX: ~/Library/Application Support/MySQL/Workbench/logs Linux: ~/.mysql/workbench/logs Referência: https://dev.mysql.com/doc/workbench/en/workbench-reporting-bugs.html
{ "pile_set_name": "StackExchange" }
Q: Python test runs forever in Visual Studio I am trying to create tests for my python module, but I am having all kind of issues. My tests never end, they seem to run forever. To discard an issue with the configuration of my solution, I created a new empty solution, with only a Python Application project and added a unit test. The default unit test never ends either! I created a unit test directly under the test project: PythonTestApplication1 my_class.py Its content is: import unittest class Test_my_class(unittest.TestCase): def test_A(self): self.fail("Not implemented") if __name__ == '__main__': unittest.main() I am new to Python, so I don't know if I am doing any obvious mistakes, regarding naming convention, spacing or anything else that could be causing this issue. What could be causing my tests run forever? A: I installed Visual Studio 2015 Update 2 and the issue got solved. However, I think the issue is already solved in Update 1. From my research It may be related to the issue posted here. But I couldn't install Windows 10 to verify it. I was also having issues discovering the tests. To address that: Select the Test x86 settings (Test => Test Settings => Default Processor Architecture => x86 Test names should start with test_
{ "pile_set_name": "StackExchange" }
Q: I am using dynamic form in angular 7 it gives me the ERROR Error: Cannot find control with name: 'i' i am using angular 7 dynamic form in which i import FormBuilder and FormArray from @angular/forms i am facing some error that i can not figure out i am new in angular import { Component } from '@angular/core'; import {FormBuilder, FormArray} from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(private fb:FormBuilder){} users = this.fb.group({ user_fname:this.fb.array([]), user_lname:this.fb.array([]), user_conatact:this.fb.array([]), user_email:this.fb.array([]) }); get UserFirstName() { return this.users.get('user_fname') as FormArray; } get UserLastName() { return this.users.get('user_lname') as FormArray; } get UserContact() { return this.users.get('user_conatact') as FormArray; } get UserEmail() { return this.users.get('user_email') as FormArray; } addNewUserRow() { this.UserFirstName.push(this.fb.control('')); this.UserLastName.push(this.fb.control('')); this.UserEmail.push(this.fb.control('')); this.UserContact.push(this.fb.control('')); } } and my component html code is <div class="container"> <h1>User Registeration Form</h1> <hr /> {{users.value | json}} <form [formGroup]="users"> <div class="row"> <div class="col-md-3"> <div class="form-group"> <label for="first-name">First Name</label> <input type="text" class="form-control"> </div> </div> <div class="col-md-3"> <div class="form-group"> <label for="last-name">Last Name</label> <input type="text" class="form-control"> </div> </div> <div class="col-md-3"> <div class="form-group"> <label for="last-name">Contact No</label> <input type="text" class="form-control"> </div> </div> <div class="col-md-3"> <div class="form-group"> <label for="last-name">Email Address</label> <input type="text" class="form-control"> </div> </div> <div formControlArray="user_fname" *ngFor="let fname of UserFirstName.controls; let i=index;" class="col-md-3"> <div class="form-group"> <label for="">First Name</label> <input type="text" class="form-control" formControlName="i"> </div> </div> <div formControlArray="user_lname" *ngFor="let fname of UserLastName.controls; let i=index;" class="col-md-3"> <div class="form-group"> <label for="last-name">Last Name</label> <input type="text" class="form-control"> </div> </div> <div formControlArray="user_contact" *ngFor="let fname of UserContact.controls; let i=index;" class="col-md-3"> <div class="form-group"> <label for="last-name">Contact No</label> <input type="text" class="form-control"> </div> </div> <div formControlArray="user_email" *ngFor="let fname of UserEmail.controls; let i=index;" class="col-md-3"> <div class="form-group"> <label for="last-name">Email Address</label> <input type="text" class="form-control"> </div> </div> </div> </form> Add New Row and it,s give me the following error AppComponent.html:40 ERROR Error: Cannot find control with name: 'i' A: Here i a small demo where you have a form visible to add first user and then you click add button to add more rows to add more users. Sorry for the plain styling you can add that according to you convenience. Here is the HTML <form [formGroup]="usersForm"> <div *ngFor="let user of userControls; let i=index" [formGroup]="user"> <div class="col-md-3"> <div class="form-group"> <label for="first-name">First Name</label> <input formControlName="firstName" type="text" class="form-control"> </div> </div> <div class="col-md-3"> <div class="form-group"> <label for="last-name">Last Name</label> <input formControlName="lastName" type="text" class="form-control"> </div> </div> <div class="col-md-3"> <div class="form-group"> <label for="last-name">Contact No</label> <input formControlName="contact" type="text" class="form-control"> </div> </div> <div class="col-md-3"> <div class="form-group"> <label for="last-name">Email Address</label> <input formControlName="email" type="text" class="form-control"> </div> </div> </div> <button (click)="addNew()">Add New User</button> </form> <h6>Form value</h6> {{value | json }} Componenet.ts import { Component } from '@angular/core'; import { FormBuilder, FormArray,FormGroup } from '@angular/forms'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { usersForm: FormGroup; constructor(private formBuilder: FormBuilder){ this.usersForm = this.formBuilder.group({ users: this.formBuilder.array([ this.createUserRow() ]) }); } get userControls(){ return (this.usersForm.get('users') as FormArray).controls } get value(){ return this.usersForm.getRawValue(); } createUserRow(){ return this.formBuilder.group({ firstName: [null], lastName:[null], contact:[null], email:[null] }) } addNew(){ (this.usersForm.get('users') as FormArray).controls.push(this.createUserRow()); } } Hope this helps :)
{ "pile_set_name": "StackExchange" }
Q: Most efficient / proper way to give Json response in Django? I am writing a polling view in Django -- being called once per second. I'd like to avoid the effect of hammering the server (since its a small device). Currently I'm returning this response: return HttpResponse(json.dumps({'body':body})) but is there a more appropriate way to do this, thus using minimal resources / features for this simple / ongoing response? A: You could use JsonResponse, from django.http import JsonResponse return JsonResponse({'body':body}) Then, you don't have to do json.dumps, For documentation, click here If you want you could refer to this question, Creating a JSON response using Django and Python
{ "pile_set_name": "StackExchange" }
Q: Multiple JQuery Plugins not functioning properly I am trying to get the jquery plugins timpickr and multidatespicker to work on the same page. Unfortunately I'm having issues getting them to work together. They are both located here: http://code.google.com/p/jquery-utils/wiki/UiTimepickr http://multidatespickr.sourceforge.net/ This is my current code: Test <link type="text/css" href="css/jquery-ui-1.8.16.custom.css" rel="stylesheet" /> <script type="text/javascript" src="js/jquery-v1.4.4.js"></script> <!-- Start Timepickr --> <link rel="Stylesheet" media="screen" href="css/ui.timepickr.css" /> <script type="text/javascript" src="js/jquery.timepickr.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('#inTime').timepickr({convention: 12}); $('#outTime').timepickr({convention: 12}); }); </script> <!-- END Timepickr--> <!-- POPUP CALENDAR --> <!--<script type="text/javascript" src="js/jquery-v1.4.4.js"></script>--> <script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js"></script> <script type="text/javascript" src="js/jquery-ui.multidatespicker.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('#date').multiDatesPicker({numberOfMonths: 2}); }); </script> <!-- END POPUP CALENDAR--> Date: <input type="text" name="date" id="date"> <br> Time In: <input type="text" name="inTime" id="inTime"> <br> Time Out: <input type="text" name="outTime" id="outTime"> Currently timepickr works. If you add in "script type="text/javascript" src="js/jquery-v1.4.4.js"" right after where "!--Popup Calendar--" starts, the calendar will work but then timepickr does not. Does anyone have any suggestions as to what I'm doing wrong? Thanks! -Brandon A: Alright, I've been taking a serious look at the plugins and I know what your problem is. You're missing a couple of scripts needed for the plugins to work. Here is a solution where both plugins work, I tested it myself. You can see in the source tags where I got the modules from, they actually came with the plugin packages. <!-- Stylesheets --> <link rel="Stylesheet" media="screen" href="/ui-timepickr/dist/themes/default/ui.core.css" /> <link rel="Stylesheet" media="screen" href="/ui-timepickr/dist/themes/default/ui.timepickr.css" /> <link rel="stylesheet" type="text/css" href="/multidates/css/mdp.css"> <!-- latest JQuery module --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <!-- JQuery UI --> <script type="text/javascript" src="/multidates/js/jquery.ui.core.js"></script> <script type="text/javascript" src="/multidates/js/jquery.ui.datepicker.js"></script> <!-- Spanish dates --> <script type="text/javascript" src="/multidates/js/jquery.ui.datepicker-es.js"></script> <!-- timepickr --> <script type="text/javascript" src="/ui-timepickr/page/jquery.ui.all.js"></script> <script type="text/javascript" src="/ui-timepickr/page/jquery.utils.js"></script> <script type="text/javascript" src="/ui-timepickr/page/jquery.strings.js"></script> <script type="text/javascript" src="/ui-timepickr/page/jquery.anchorHandler.js"></script> <script type="text/javascript" src="/ui-timepickr/src/ui.dropslide.js"></script> <script type="text/javascript" src="/ui-timepickr/src/ui.timepickr.js"></script> <!-- datepicker --> <script type="text/javascript" src="/multidates/jquery-ui.multidatespicker.js"></script> <!-- execution code --> <script type="text/javascript"> $(document).ready(function(){ //timepickr $('#inTime').timepickr(); $('#outTime').timepickr(); //popup calendar $('#date').multiDatesPicker(); }); </script> Date: <input type="text" name="date" id="date"> <br> Time In: <input type="text" name="inTime" id="inTime"> <br> Time Out: <input type="text" name="outTime" id="outTime"> I hope that solves it for you. To make it easier, put all the necessary modules under the same directory, so you don't accidentally add a duplicate of the same script, IE, one directory for everything that has to do with JQuery, and another directory for plugins. To learn more about the plugins, I suggest you read their documentation.
{ "pile_set_name": "StackExchange" }
Q: LinqPad / Sqlite version info and foreign key support I am using fabulous LinqPad and its Sqlite driver. 1) Is there a way to obtain Sqlite version information by executing say "select version"? 2) Which driver specific connection string should I use to enable foreign key support in Sqlite? A: select distinct sqlite_version() from sqlite_master;
{ "pile_set_name": "StackExchange" }
Q: How to specify column list in hive insert into query I have just installed and configured Apache Hive version 1.1.0. Then I have created a table by quering this query: create table person (name1 string, surname1 string); And then I want to add one row by: insert into person (name1, surname1) values ("Alan", "Green"); And it cause an error: Error: Error while compiling statement: FAILED: ParseException line 1:20 cannot recognize input near '(' 'name1' ',' in statement (state=42000,code=40000). But when I execute query without column list it works fine: insert into person values ("Alan", "Green"); The question is: how to specify column list in hiveQL to make insert into? A: According to this bug HIVE-9481, you can specify column list in INSERT statement, since 1.2.0. The syntax is like this: INSERT OVERWRITE TABLE tablename1 [PARTITION (partcol1=val1, partcol2=val2 ...) [(column_list)] [IF NOT EXISTS]] select_statement1 FROM from_statement; example: CREATE TABLE pageviews (userid VARCHAR(64), link STRING, "from" STRING) PARTITIONED BY (datestamp STRING) CLUSTERED BY (userid) INTO 256 BUCKETS STORED AS ORC; INSERT INTO TABLE pageviews PARTITION (datestamp = '2014-09-23') (userid,link) VALUES ('jsmith', 'mail.com'); I tested this with Hive 2.1. It works only with INSERT INTO, not with INSERT OVERWRITE And I don't know why this syntax is not mentioned in the Apache wiki page LanguageManual DML https://issues.apache.org/jira/browse/HIVE-9481 A: Insert into specific columns in the above query: insert into table person (name1, surname1) values ("Alan", "Green"); is supported in Hive 2.0
{ "pile_set_name": "StackExchange" }
Q: How to get member function pointer if exists in a template To get a class member function pointer, we do the following: return_type (Class::*varName)(paramType1, paramTypeN) = &Class::functionName; The "functionName" should be known in advance. The fact is, I do not (we should not actually) care about the function name, is there a way that , I could check the existence of "member function pointer", if it is not null, i call it. I would like to do that in my template class. If the template parameter object has a member function, which matches the signature I expect, I call that function. The code is not valid C++ code, but it gives you a hint of what I am looking for. template< typename T > class MyTemplateClass { void myFunction(T& object) { if constexpr( exists_in_class< T, void (T::*)(const int&, const int&) >::value ) { call_member_function_pointer< T, void (T::*)(const int&, const int&) >( object, 1, 2 ); } } }; If that is not possible, because you might have many functions with different names but with the same exact signature (prototype). Is it possible to find a way to pass the function name as follows: template< typename T > class MyTemplateClass { void myFunction(T& object) { if constexpr( exists_in_class< T, void (T::*)(const int&, const int&), FunctionNameIExpect >::value ) { call_member_function_pointer< T, void (T::*)(const int&, const int&), FunctionNameIExpect >( object, 1, 2 ); } } }; A: With std::experimental::is_detected, you might do: template<class T> using has_my_function_name_t = decltype(&T::my_function_name); template< typename T > class MyTemplateClass { public: void myFunction(T& object) { if constexpr(std::experimental::is_detected_exact<void (T::*)(const int&, const int&), has_my_function_name_t, T>::value) { object.my_function_name(1, 2); } } }; Demo If you are more permissif in allowed signature (Ret (T::*)(int, int) /*const*/), std::is_invocable might be used.
{ "pile_set_name": "StackExchange" }
Q: Mapping JSON to Class automatically - design issue I am using a certain API which returns JSON data in the following format: entities { entity#1 { [property#1:value, property#2:value] }, entity#2 { [property#3:value, property#4:value] } } The entities in this JSON are defined manually, which means each entity can have unique properties. What is the best way to parse this kind of data? At the moment, I'm making a unique class for each entity that I define on the API however the amount of entities that I define could be well over 100. Is there a way in Java to create a single class that would have the shared properties pre-defined, and then add properties to that same class on runtime? A: Your entities probably share some of the common properties and differ in others. It that case a decent compromise approach would be having a class containing the common properties as class fields. The rest needs to be stored in a Map a key-value pairs. This allows you to have at least some class structure without having a hundred of slightly different classes. Something like private String someProperty; private boolean someOtherCommonProperty; ... private Map<String, Object> allTheOtherProperties; For deserialization details check this article: http://www.baeldung.com/jackson-map Specifically 4.2. Map Deserialization
{ "pile_set_name": "StackExchange" }
Q: Using only the axioms for a field, give a formal proof for $\frac{1}{z_{1}z_{2}}=\frac{1}{z_{1}}\cdot \frac{1}{z_{2}}$. Using only the axioms for a field, give a formal proof for $\frac{1}{z_{1}z_{2}}=\frac{1}{z_{1}}\cdot \frac{1}{z_{2}}$, where $z_{1},z_{2}\in \mathbb{C}$. This is my attempt: $\frac{1}{z_{1}z_{2}}=\frac{1}{z_{1}z_{2}}\cdot 1=\frac{1}{z_{1}z_{2}}\cdot z_{1}z_{1}^{-1}=\frac{1}{z_{2}}z_{1}^{-1}\cdot 1=\frac{1}{z_{2}}z_{1}^{-1}\cdot z_{2}z_{2}^{-1}=z_{1}^{-1}z_{2}^{-1}=\frac{1}{z_{1}}\cdot \frac{1}{z_{2}}$ Is this correct though? Any critique is appreciated! A: Your proof assumes that$$\frac1{z_1z_2}\cdot z_1=\frac1{z_2}.$$How do you know that? I would use the fact that\begin{align}\left(\frac1{z_1}\cdot\frac1{z_2}\right)\cdot(z_1\cdot z_2)&=\left(\frac1{z_1}\cdot\frac1{z_2}\right)\cdot(z_2\cdot z_1)\\&=\left(\left(\frac1{z_1}\cdot\frac1{z_2}\right)\cdot z_2\right)\cdot z_1\\&=\left(\frac1{z_1}\cdot\left(\frac1{z_2}\cdot z_2\right)\right)\cdot z_1\\&=\left(\frac1{z_1}\cdot1\right)\cdot z_1\\&=\frac1{z_1}\cdot z_1\\&=1.\end{align}
{ "pile_set_name": "StackExchange" }
Q: Storing xml within excel workbook I have some data defined in .xml file. I need to create an Excel workbook that provides some functions based on information contained in that file. The XML data must be placed within that Excel file --- i.e., it cannot be put into a separate file (so afterwards you can keep .xlsx file without .xml). So I want to create something like this: sub Load() 'this function is called once, and after it was called the .xml file is no longer required' fName = "some path to data.xml" ActiveSheet.OLEObjects.Add(Filename:=fName) End Sub 'Does not open external .xml file' Sub SomeFunction() Dim data As MSXML2.DOMDocument Set data = New MSXML2.DOMDocument data.Load(ActiveWorkbook.OLEObjects(1)) 'Load method can not be called like that' ' parse the data' End Sub The way I see it is that the .xml file should be embedded into Excel file as an OLE object. Yet I can't find a way to read the data (as string) form file after it was embeded. I know that using MSXML2 it's possible to read .xml stored in an external file (MSXML2.DOMDocument.Load method) so it can be parsed. Is it possible to use MSXML2 object to open an embedded document? Or is there an alternative way to store external XML structures within the workbook? A: You can do this using the CustomXMLParts object see https://msdn.microsoft.com/en-us/library/office/ff863162.aspx or the Object browser
{ "pile_set_name": "StackExchange" }
Q: shorten file path in terminal I would like to shorten the file path that is currently active in the terminal to allow more space. This is a shortened example but I sometimes have filepaths that I am working with that are 6 levels deep and it would be nice to hide that. test@ubuntu:~$ cd code/helloworld test@ubuntu:~/code/helloworld$ would like to just see somehting like helloworld: Any ideas? Thanks! A: Add to your .bashrc or run at a prompt: PS1='\W: ' For background information, run man bash and search for PROMPTING.
{ "pile_set_name": "StackExchange" }
Q: Laravel 5 : How to get the value in data attribute using vue js I am new in vue js. In our app, we have validation if this value is already exists in the database. I want to improve it by making it a dynamic. So I added to put data attribute in my field whenever the user type anything. My value in mthe data attribute is the table where I will check if this value already exist. Add.vue <label>Code <span class="required-field">*</span></label> <input type="text" name="code" @keyup="checkCOACode" v-model="coa_code" class="form-control" :data-table="chart_of_accounts"> Add.vue in my method checkCOACode(e) { e.preventDefault(); var code = this.coa_code; var x = event.target.getAttribute('data-table'); alert(x); return false; axios.post("/checkIfCodeExists", {code:code}) .then((response) => { var code_checker = ''; if (response.data == 0) { $('.add-chart-of-account').removeAttr('disabled','disabled'); }else{ $('.add-chart-of-account').attr('disabled','disabled'); code_checker = 'Code is already exist'; } this.coa_checker_result = code_checker; }); }, My value in my x is null. Question: How do I get the value of my data attribute? A: You can get value of data attribute in vue by adding ref attribute to your text element <input type="text" ref="coaCode" name="code" @keyup="checkCOACode" v-model="coa_code" class="form-control" :data-table="chart_of_accounts"> And then get that attribute like checkCOACode(e) { e.preventDefault(); const coa = this.$refs.coaCode const coaCode = coa.dataset.table alert(coaCode); return false; },
{ "pile_set_name": "StackExchange" }
Q: Remove parts of line that fall within a polygon I have a polygon and two lines. How can I remove the portion of each line that falls within the polygon? # polygon coords <- matrix(c(-1.798123, -1.793072, -1.805767, -1.804129, -1.798123, 55.68066, 55.67369, 55.67508, 55.68139, 55.68066), ncol=2) myPolygon <- Polygons(list(Polygon(coords)), "myPolygon") myPolygon <- SpatialPolygons(list(myPolygon)) proj4string(myPolygon) <- CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0") plot(myPolygon) # lines line1 <- matrix(c(-1.79880, -1.79517, 55.67737, 55.67920), ncol=2) line2 <- matrix(c(-1.80231, -1.80679, 55.67764, 55.68004), ncol=2) line1L <- Line(line1) line2L <- Line(line2) my.lines <- Lines(list(line1L, line2L), ID="my.lines") myLines <- SpatialLines(list(my.lines)) proj4string(myLines) <- CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0") plot(myLines, add=T) A: The gDifference function from the rgeos package is probably your best/easiest bet. Returns the regions of geometry1 that are not within geometry2. For reference, the example from the above link (substitute your polygon/line geometries): x = readWKT("POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))") y = readWKT("POLYGON ((3 3, 7 3, 7 7, 3 7, 3 3))") d = gDifference(x,y) plot(d,col='red',pbg='white') d2 = gDifference(y,x)
{ "pile_set_name": "StackExchange" }
Q: HtmlHelper to display only a few characters Is it possible use a HtmlHelper to display only a few characters of the text? how can I do this? A: Something like this? public static MvcHtmlString SubString(this HtmlHelper helper, string theString, int length) { return MvcHtmlString.Create(theString.Substring(0,length)); }
{ "pile_set_name": "StackExchange" }
Q: VBA Excel: Run-time error 13 type mismatch due to too many characters I'm working on a 'dashboard' in excel where the user can select a commodity and then presses the run button, so the code then prints out all suppliers linked to that commodity. (Several commodities and supplier names are listed on other tabs in the same workbook, and the code goes over all tabs to collect the right supplier names) EDIT: the issue is due to a supplier name being longer than 255 characters. The debugger focuses on this code in particular: If Application.Evaluate("COUNTIF(" & myDataRng.Address & "," & cell.Address & ")") > 1 Then cell.Offset(0, 0).Font.Color = vbRed End If This code is part of the bigger set below. The code highlights all suppliernames that are listed under the chosen category in different tabs (hence they would be printed out multiple times, I want to highlight the duplicate values). '##### Find duplicates in commodity column and highlight them ###### Dim myDataRng As Range Dim cell As Range Set myDataRng = Range("E10:E" & Cells(Rows.Count, "E").End(xlUp).Row) For Each cell In myDataRng cell.Offset(0, 0).Font.Color = vbBlack If Application.Evaluate("COUNTIF(" & myDataRng.Address & "," & cell.Address & ")") > 1 Then cell.Offset(0, 0).Font.Color = vbRed End If Next cell Any idea what it could be? A: The error is not immediately obvious. I made a few tweaks to the code, however this should allow you to see what's being evaluated. Typically you'd get this error from the formula not being entered with the correct format, but it works on my end. I removed the Offset(0,0) as it is superfluous at present with no offset applied, as well as placing the vbBlack formatting in an Else block for performance/clarity. However seeing the Debug.Print statement should be critical for understanding when the code is not functioning. The only other thought I have, is you may want to clarify which sheet this Countif is being completed on. Update I've revised my answer to use SumProduct instead of CountIf to workaround the issue of 255 characters being the limit for CountIf. Public Sub TestSub() Dim myDataRng As Range Dim cell As Range Dim EvalStr As String Set myDataRng = Range("E10:E" & Cells(Rows.Count, "E").End(xlUp).Row) For Each cell In myDataRng EvalStr = "SumProduct((" & myDataRng.Address & "=" & cell.Address & ")+0)" If Application.Evaluate(EvalStr) > 1 Then cell.Font.Color = vbRed Else cell.Font.Color = vbBlack End If Next cell End Sub
{ "pile_set_name": "StackExchange" }
Q: Alternative to django form processing boilerplate? The suggested pattern for processing a form in a view seems overly complex and non-DRY to me: def contact(request): if request.method == 'POST': # If the form has been submitted... form = ContactForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass # Process the data in form.cleaned_data # ... return HttpResponseRedirect('/thanks/') # Redirect after POST else: form = ContactForm() # An unbound form return render_to_response('contact.html', { 'form': form, }) That's a lot of conditionals, it repeats the ContactForm() construction, and the whole block is repeated everywhere a view needs to process a form. Isn't there a better way of doing it? A: You can avoid the repetition, of course. Mostly, you need to pass in as arguments the class of form and template name to use, a callable to process the cleaned data when a valid form is submitted, and a destination for the redirect after such processing; plus, you need a little extra code to call the form class just once, to produce either a bound or unbound form, and deal with it properly. I.e.: def process_any_form(request, form_class, template_file_name, process_data_callable, redirect_destination): form = form_class(request.POST if request.method == 'POST' else None) if form.is_bound and form.is_valid(): process_data_callable(form.cleaned_data) return HttpResponseRedirect(redirect_destination) return render_to_response(template_file_name, {'form': form}) A: You are right it could be better, here is a better alternative (but keep reading): def contact(request): form = ContactForm(request.POST or None) # A form bound to the POST data if form.is_valid(): # All validation rules pass # Process the data in form.cleaned_data # ... return HttpResponseRedirect('/thanks/') # Redirect after POST return render_to_response('contact.html', { 'form': form, }) This snippet comes from a talk called Advanced Django Form Usage from DjangoCon11. Note that this will process an empty form as valid (even before submission) if all the fields are optional and you don't use CSRF protection. So to eliminate that risk, you better use this one: def contact(request): form = ContactForm(request.POST or None) # A form bound to the POST data if request.method == 'POST' and form.is_valid(): # All validation rules pass # Process the data in form.cleaned_data # ... return HttpResponseRedirect('/thanks/') # Redirect after POST return render_to_response('contact.html', { 'form': form, })
{ "pile_set_name": "StackExchange" }
Q: post multipart/form-data variable and image using curl My company has an html form to send variables and update image (jpeg) to the server, I tried to automate it using curl, but got stuck. I can send variables but not the image. I used "tamper data" firefox and noticed that my form send the following variables to the server: -----------------------------291231848620019\r\nContent-Disposition: form-data; name="pin"\r\n\r\ndf8794b1ec63c7094f6498f7a1322bcc\r\n-----------------------------291231848620019\r\nContent-Disposition: form-data; name="yourdata"\r\n\r\nonly test\r\n-----------------------------291231848620019\r\nContent-Disposition: form-data; name="your_file"; filename="chansy.jpg"\r\nContent-Type: image/jpeg\r\n\r\n{content-of-image-file-here}\r\n-----------------------------291231848620019\r\nContent-Disposition: form-data; name="birth_date[]"\r\n\r\n1\r\n-----------------------------291231848620019\r\nContent-Disposition: form-data; name="birth_date[]"\r\n\r\n1\r\n-----------------------------291231848620019\r\nContent-Disposition: form-data; name="birth_date[]"\r\n\r\n1970\r\n-----------------------------291231848620019\r\nContent-Disposition: form-data; name="your_email"\r\n\r\[email protected]\r\n-----------------------------291231848620019\r\nContent-Disposition: form-data; name="code"\r\n\r\n\r\n-----------------------------291231848620019\r\nContent-Disposition: form-data; name="pass"\r\n\r\npass_sample\r\n-----------------------------291231848620019\r\nContent-Disposition: form-data; name="act"\r\n\r\nUpdate Changes\r\n-----------------------------291231848620019\r\nContent-Disposition: form-data; name="your_name"\r\n\r\njust me\r\n-----------------------------291231848620019--\r\n here is the code i used on array postfields: $img=file_get_contents($filename); $data = array('pin' => $pin, 'yourdata' => $_POST['yourdata'], 'your_file'=>$img, 'filename' =>$filename, 'Content-Type' => 'image/jpeg', 'birth_date[]' => $_POST['birth_date'], 'birth_date[]' => $_POST['birth_month'], 'birth_date[]' => $_POST['birth_year'], 'your_email' => $_POST['your_email'], 'pass' => $_POST['pass'], 'act' => 'Update changes', 'your_name' => $_POST['your_name']); $ch = curl_init(); curl_setopt($ch, CURLOPT_VERBOSE, 0); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_COOKIE, $cookie); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch , CURL_HTTPHEADER , "Content-Type: multipart/form-data" ); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_REFERER, "http://internalweb.com/"); curl_setopt($ch, CURLOPT_URL, "http://internalweb.com/profile"); $page = curl_exec($ch); On the result, when I run my script, it can update those variables, but no luck with the image.. i am so confuse... what should i do to put in variable? I am learning everything from google, and now i am stuck since i dont have any knowledge in deep programming, can you please help me what to do to put image in $data array? I tried to look on the thread of: multipart/form-data into array not processing multipart/form-data php curl Posting raw image data as multipart/form-data in curl note: I tried to follow Hassan's suggestion, but not work still. Does anyone know how to convert this: Content-Disposition: form-data; name="your_file"; filename="merc.jpg" Content-Type: image/jpeg $contentfile into $data array for curl? A: When you upload a file to server using curl, you need to specify the @ sign before the file path. For example this image file: $img = '/var/tmp/someimg.jpg'; // must be full path Then in your post data, it should be: 'your_file' => '@' . $img, Also, remove the following header from your curl code. Curl will automatically set this header with length based on your parameters. curl_setopt($ch , CURL_HTTPHEADER , "Content-Type: multipart/form-data" ); Finally make sure your other parameter values are correct. And, also enable the verbose mode, so that you can see the output from curl curl_setopt($ch, CURLOPT_VERBOSE, 1);
{ "pile_set_name": "StackExchange" }
Q: One method for one operation in OOP? In Functional Programming, the good rule of thumb for composition is to create a function for each operation and compose them together to achieve the desired functionality. In contrast, in Object-oriented Programming, should each method be self-contained with the use of less helper methods or same as Functional Programming? What is a good practice? A: Whether OOP or FP, a function should do one thing. The good rule of thumb, no matter the paradigm is OOP or FP, is that a function should do one thing. It does not mean that a function should not internally compose with others. If helpers method contribute to participate to achieve the sole function/method responsibility, that's pretty fine to use them.
{ "pile_set_name": "StackExchange" }
Q: Is it safe to send vulnerable information as function arguments in PHP? I have two functions: get_post_data() gets the POST data from a form. It then sends the username and password to process_login($username, $password). I want to send the password in plain-text. Am I safe to do this, or do I have to hash/encrypt the password before I send it as a function argument? A: Hashing should be done when storing the password to a permanent location, or obviously when you need to check it against the stored hash. Otherwise, if you're transferring it from one server to another or an external resource I would think it would be better practice to hash it and or at minimum use an encrypted connection. Preferably both.
{ "pile_set_name": "StackExchange" }
Q: Postgres slow query (slow index scan) I have a table with 3 million rows and 1.3GB in size. Running Postgres 9.3 on my laptop with 4GB RAM. explain analyze select act_owner_id from cnt_contacts where act_owner_id = 2 I have btree key on cnt_contacts.act_owner_id defined as: CREATE INDEX cnt_contacts_idx_act_owner_id ON public.cnt_contacts USING btree (act_owner_id, status_id); The query runs in about 5 seconds Bitmap Heap Scan on cnt_contacts (cost=2598.79..86290.73 rows=6208 width=4) (actual time=5865.617..5875.302 rows=5444 loops=1) Recheck Cond: (act_owner_id = 2) -> Bitmap Index Scan on cnt_contacts_idx_act_owner_id (cost=0.00..2597.24 rows=6208 width=0) (actual time=5865.407..5865.407 rows=5444 loops=1) Index Cond: (act_owner_id = 2) Total runtime: 5875.684 ms" Why is taking so long? work_mem = 1024MB; shared_buffers = 128MB; effective_cache_size = 1024MB seq_page_cost = 1.0 # measured on an arbitrary scale random_page_cost = 15.0 # same scale as above cpu_tuple_cost = 3.0 A: Ok, You have big table, index and long time execution plain for PG. Lets think about ways how to improve you plan and reduce time. You write and remove rows. PG write and remove tuples and table and index can be bloated. For good search PG loads index to shared buffer. And you need keep you index clean as possible. For selection PG reads to shared buffer and than search. Try to set up buffer memory and reduce index and table bloating, keep db cleaned. What you do and think about: 1) Just check index duplicates and that you indexes have good selection: WITH table_scans as ( SELECT relid, tables.idx_scan + tables.seq_scan as all_scans, ( tables.n_tup_ins + tables.n_tup_upd + tables.n_tup_del ) as writes, pg_relation_size(relid) as table_size FROM pg_stat_user_tables as tables ), all_writes as ( SELECT sum(writes) as total_writes FROM table_scans ), indexes as ( SELECT idx_stat.relid, idx_stat.indexrelid, idx_stat.schemaname, idx_stat.relname as tablename, idx_stat.indexrelname as indexname, idx_stat.idx_scan, pg_relation_size(idx_stat.indexrelid) as index_bytes, indexdef ~* 'USING btree' AS idx_is_btree FROM pg_stat_user_indexes as idx_stat JOIN pg_index USING (indexrelid) JOIN pg_indexes as indexes ON idx_stat.schemaname = indexes.schemaname AND idx_stat.relname = indexes.tablename AND idx_stat.indexrelname = indexes.indexname WHERE pg_index.indisunique = FALSE ), index_ratios AS ( SELECT schemaname, tablename, indexname, idx_scan, all_scans, round(( CASE WHEN all_scans = 0 THEN 0.0::NUMERIC ELSE idx_scan::NUMERIC/all_scans * 100 END),2) as index_scan_pct, writes, round((CASE WHEN writes = 0 THEN idx_scan::NUMERIC ELSE idx_scan::NUMERIC/writes END),2) as scans_per_write, pg_size_pretty(index_bytes) as index_size, pg_size_pretty(table_size) as table_size, idx_is_btree, index_bytes FROM indexes JOIN table_scans USING (relid) ), index_groups AS ( SELECT 'Never Used Indexes' as reason, *, 1 as grp FROM index_ratios WHERE idx_scan = 0 and idx_is_btree UNION ALL SELECT 'Low Scans, High Writes' as reason, *, 2 as grp FROM index_ratios WHERE scans_per_write <= 1 and index_scan_pct < 10 and idx_scan > 0 and writes > 100 and idx_is_btree UNION ALL SELECT 'Seldom Used Large Indexes' as reason, *, 3 as grp FROM index_ratios WHERE index_scan_pct < 5 and scans_per_write > 1 and idx_scan > 0 and idx_is_btree and index_bytes > 100000000 UNION ALL SELECT 'High-Write Large Non-Btree' as reason, index_ratios.*, 4 as grp FROM index_ratios, all_writes WHERE ( writes::NUMERIC / ( total_writes + 1 ) ) > 0.02 AND NOT idx_is_btree AND index_bytes > 100000000 ORDER BY grp, index_bytes DESC ) SELECT reason, schemaname, tablename, indexname, index_scan_pct, scans_per_write, index_size, table_size FROM index_groups; 2) Check if you have tables and index bloating? SELECT current_database(), schemaname, tablename, /*reltuples::bigint, relpages::bigint, otta,*/ ROUND((CASE WHEN otta=0 THEN 0.0 ELSE sml.relpages::FLOAT/otta END)::NUMERIC,1) AS tbloat, CASE WHEN relpages < otta THEN 0 ELSE bs*(sml.relpages-otta)::BIGINT END AS wastedbytes, iname, /*ituples::bigint, ipages::bigint, iotta,*/ ROUND((CASE WHEN iotta=0 OR ipages=0 THEN 0.0 ELSE ipages::FLOAT/iotta END)::NUMERIC,1) AS ibloat, CASE WHEN ipages < iotta THEN 0 ELSE bs*(ipages-iotta) END AS wastedibytes FROM ( SELECT schemaname, tablename, cc.reltuples, cc.relpages, bs, CEIL((cc.reltuples*((datahdr+ma- (CASE WHEN datahdr%ma=0 THEN ma ELSE datahdr%ma END))+nullhdr2+4))/(bs-20::FLOAT)) AS otta, COALESCE(c2.relname,'?') AS iname, COALESCE(c2.reltuples,0) AS ituples, COALESCE(c2.relpages,0) AS ipages, COALESCE(CEIL((c2.reltuples*(datahdr-12))/(bs-20::FLOAT)),0) AS iotta -- very rough approximation, assumes all cols FROM ( SELECT ma,bs,schemaname,tablename, (datawidth+(hdr+ma-(CASE WHEN hdr%ma=0 THEN ma ELSE hdr%ma END)))::NUMERIC AS datahdr, (maxfracsum*(nullhdr+ma-(CASE WHEN nullhdr%ma=0 THEN ma ELSE nullhdr%ma END))) AS nullhdr2 FROM ( SELECT schemaname, tablename, hdr, ma, bs, SUM((1-null_frac)*avg_width) AS datawidth, MAX(null_frac) AS maxfracsum, hdr+( SELECT 1+COUNT(*)/8 FROM pg_stats s2 WHERE null_frac<>0 AND s2.schemaname = s.schemaname AND s2.tablename = s.tablename ) AS nullhdr FROM pg_stats s, ( SELECT (SELECT current_setting('block_size')::NUMERIC) AS bs, CASE WHEN SUBSTRING(v,12,3) IN ('8.0','8.1','8.2') THEN 27 ELSE 23 END AS hdr, CASE WHEN v ~ 'mingw32' THEN 8 ELSE 4 END AS ma FROM (SELECT version() AS v) AS foo ) AS constants GROUP BY 1,2,3,4,5 ) AS foo ) AS rs JOIN pg_class cc ON cc.relname = rs.tablename JOIN pg_namespace nn ON cc.relnamespace = nn.oid AND nn.nspname = rs.schemaname AND nn.nspname <> 'information_schema' LEFT JOIN pg_index i ON indrelid = cc.oid LEFT JOIN pg_class c2 ON c2.oid = i.indexrelid ) AS sml ORDER BY wastedbytes DESC 3) Do you clean unused tuples from hard disk? Is it time for vacuum? SELECT relname AS TableName ,n_live_tup AS LiveTuples ,n_dead_tup AS DeadTuples FROM pg_stat_user_tables; 4) Think about that. If you have 10 records in db and 8 of 10 have id = 2 thats mean you have bad selectivity of index and in this way PG will scan all 8 records. But of you try to use id != 2 index will work good. Try to set index with good selection. 5) Use proper column type got you data. If you can use less kb type for you column just convert it. 6) Just check you DB and condition. Check this for start going page Just try to see that you have in data base unused data in tables, indexes must be cleaned, check selectivity for you indexes. Try use other brin indexes for data, try to recreate indexes. A: You are selecting 5444 records scattered over a 1.3 GB table on a laptop. How long do you expect that to take? It looks like your index is not cached, either because it can't be sustained in the cache, or because this is the first time you used that part of it. What happens if you run the exact same query repeatedly? The same query but with a different constant? running the query under "explain (analyze,buffers)" would be helpful to get additional information, particularly if you turned track_io_timing on first.
{ "pile_set_name": "StackExchange" }
Q: C# and Excel automation Add-in problems I'm kind of new to c# and trying to create an automation add-in for excel and I followed the instructions given in this article This is working fine when I use numbers as parameters to the function called from a cell =MultiplyNTimes(3,7,8) but when I use cell addresses =MultiplyNTimes(A1,B2,C3) excel doesn't recognize the function and it throws the #NAME error. Debugging in VS, I can see that the function is not even called. A: Not very elegant, but try this: =MultiplyNTimes(VALUE(A1),VALUE(B2),VALUE(C3))
{ "pile_set_name": "StackExchange" }
Q: Greater Than / Equal To: using specific words I am trying to write a formula with an outcome of Pass or Fail based upon two criteria: Column A relates to a document's required approval level, ranging between Blue, Green, Yellow, Red, Purple, and Black (Blue being the lowest approval level and Black being the highest) Column B relates to the level of the agent who approved the document (same color ranking) The Pass/Fail formula will be housed in Column C and will check any given agent level in Column B against the corresponding document level in Column A (e.g. Agent level-Green in B4 against Document level-Blue in A4) With the above in mind: Is there any way to assign a ranking order for the aforementioned levels from lowest to highest using a formula? I suppose I would need two separate formulas: one to account for the ranking an the other to measure Column B against Column A. Thanks in advance. A: Put your list in order in a range and use MATCH to return a relative location: =IF(MATCH(B2,G:G,0)>=MATCH(A2,G:G,0),"PASS","FAIL") If you want to "hard code" the values and skip the helper column just put {"Blue","Green","Yellow","Red","Purple","Black"} in place ofG:G` in the formula.
{ "pile_set_name": "StackExchange" }
Q: Combinations of Nested Lists I have three lists that are generated by other functions. Let's assume for now they are: x = ['d', 'e'] g = ['1', '2'] y = ['f', g] As you can see, g is part of y. I am trying to get all combinations of the elements of the three lists. I have tried going about this in two ways: One way: l = [] l.append([a]+[b] for a in x for b in y) Another way using itertools: import itertools l = list(itertools.product([a for a in x], [b for b in y])) Both ways produce the following combinations: [('d', 'f'), ('d', ['1', '2']), ('e', 'f'), ('e', ['1', '2'])] But what I would like to get is: [('d', 'f'), ('d', '1'), ('d','2'), ('e', 'f'), ('e', '1'), ('e','2')] Also, when x for example is empty, I get no combinations at all when I am still expecting to get the element combinations of the remaining two lists. A: As @BrenBarn commented, you can flatten list y with chain function, and then use product: from itertools import product, chain list(product(x, chain.from_iterable(y))) # [('d', 'f'), ('d', '1'), ('d', '2'), ('e', 'f'), ('e', '1'), ('e', '2')] A: This is inspired from @Psidoms answer but just uses a specifically tailored flatten function to make sure only items that should be flattened are iterated: def flatten(x, types=list): lst = [] for item in x: if isinstance(item, types): for subitem in item: lst.append(subitem) else: lst.append(item) return lst >>> from itertools import product >>> list(product(x, flatten(y))) [('d', 'f'), ('d', '1'), ('d', '2'), ('e', 'f'), ('e', '1'), ('e', '2')] Note that there is unfortunatly no such flatten function in the standard library but you could also use one from an external library, for example iteration_utilities.deepflatten. Note that this requires to provide str or basestring as ignore: >>> from iteration_utilities import deepflatten >>> list(product(x, deepflatten(y, ignore=str))) [('d', 'f'), ('d', '1'), ('d', '2'), ('e', 'f'), ('e', '1'), ('e', '2')] To exclude empty iterables from the product simply exclude empty subiterables. For example: >>> x = [] >>> iterables = [subiterable for subiterable in (x, list(deepflatten(y, ignore=str))) if subiterable] >>> list(product(*iterables)) [('f',), ('1',), ('2',)]
{ "pile_set_name": "StackExchange" }
Q: How to select all grayscale colors? In ImageMagick convert, I can select a specific color with e.g. -opaque blue. How can I select all grayscale colors (e.g. #000000, #707070, #ffffff)? A: Not sure what you are trying to do, but this may help. The greyscale pixels will have a saturation of zero, so that is probably the easiest way to identify them. First, make a funky sample image: convert -size 400x100 gradient:black-white -bordercolor red -border 80 image.png Now make all grey areas (those with very low saturation) transparent: convert image.png -alpha on -channel A -fx "saturation<0.01?0:1" result.png Note Note that the -fx operator is extremely powerful but notoriously slow because it is actually interpolated for each and every pixel. If your images are large, the following technique may be more appropriate. Basically, I clone the image and convert the whole thing to HSL colorspace and separate the channels. Then I discard the Hue and Lightness channels so I am left with just the Saturation. I then threshold that and copy that back to the original image as the alpha channel. On a 2000x2000 pixel image, this method will run in under a second whereas the -fx method will require 5-6 seconds. convert image.png \( +clone -colorspace hsl -separate -delete 0,2 -threshold 1% \) -compose copy-opacity -composite result.png
{ "pile_set_name": "StackExchange" }
Q: SOLID и RxJava архитектура приложения Предположим что разрабатывается приложение. Выбран паттерн MVP. И необходимо придерживаться SOLID принципов. Например, создали класс репозиторий, методы репозитория обвернуты в observable от rxJava. Используем этот репозиторий в презентере. Как в этом случае работает dependency inversion principle? Получается, необходимо для репозитория сделать интерфейс, с описанием методов которые возвращают observable? - вроде, где-то читал что вообще по правильному не должны зависит от каких то сторонних фреймворков, а где-то читал что нужно считать rx как стандартную библиотеку и не париться по этому поводу. Насколько это правильно? Можете привести какой нибудь пример с реального проекта с rx? A: Да, все верно нужно создать интерфейс репозитория. Инжектим этот интерфейс в презентер. Тогда наш презентер не будет зависеть от реализации репозитория, а будет зависеть от абстракции. Это помогает в тех случаях, когда нам нужно поменять класс репозитория на другой класс совсем с другой логикой. Например, сначала у нас был репозиторий с тестовыми данными, потом бекенд закончил делать апи и мы подменили репозиторий на реальный, так как интерфейс репозитория остался такой же, то код презентера мы не меняем. Наверное, вы читали в статьях о clean architecture, что проект не должен зависеть от каких-то фреймфорков. Это правда и RxJava во всех слоях приложения это нарушение этого принципа. Но правда и то, что в андроиде сейчас RxJava это стандарт (как Stream API в java) поэтому она есть во всем проекте. Примеров в интернете очень много, один из фундаментальных это вот этот. Там как раз то, что я описал выше есть. На хабре есть статья по этому репозиторию, чтобы лечге понимать, что происходит в коде. Еще есть такая статья для большего понимания
{ "pile_set_name": "StackExchange" }
Q: Trouble passing multi-word argument from bash to expect I have looked at some of the related questions and answers in here, but i'm still stumped :-( I wish to pass a multi-word command from a bash script to an expect script. Inside the expect script, the multi-word command will be executed by a send statement. So, the multi-word command is: get dump perf 0 It is stored in the bash script in a variable called usrcmd. The expect script is called like this: ./userspecifiedcmd.exp root $password $server $usrcmd In the expect script, the multi-word command is extracted as follows: set usercommand [lrange $argv 3 3] And the multi-word command is executed as follows: send "$usercommand\r" RESULTS... The string actually sent by the send statement is: get I have tried putting quotes around the $usrcmd variable when I launch the expect script, like this: ./userspecifiedcmd.exp root $password $server "$usrcmd" When I do that, the string sent by the send statement is: {get dump perf 0} My gut tells me there is a simple fix. Is my gut correct? Thx! A: The expect script should be called like this: ./userspecifiedcmd.exp root "$password" "$server" "$usrcmd" Always quote your shell variables unless you have a compelling to omit them. In expect, map the args to variables like this: lassign $argv user password server usercommand The lrange command returns a list, and when you handle a list like a string, you get the {} artifacts. Be aware of your Tcl data types: handle lists as lists, strings as strings. When you have a list, use join to "convert" it into a string cleanly. The Tcl manual pages are helpful: http://tcl.tk/man/tcl8.5/TclCmd/contents.htm As is the Tcl tutorial: http://tcl.tk/man/tcl8.5/tutorial/tcltutorial.html
{ "pile_set_name": "StackExchange" }
Q: Using bash for loops in conjunction with embedded applescript for bash scripts I'm trying to get applescript to interact with the bash for loop that is a part of my code to keep from having to list each host manually and execute individual tell/end tell blocks for each host found in the hosts2.txt file. The purpose of the script is to open a new terminal tab on my Mac and automatically launch "screen -r $HOST" in each new terminal until the end of the list of hosts in the hosts2.txt document. Each host is listed on its own line. I've tried an all inclusive for loop, without the applescript "repeat 2 times" "end repeat" code that is shown below. It is repeating 2 times because there are only 2 hosts listed in the text document for testing purposes. Each time I have error output. #!/bin/bash for HOST in `cat ~/bin/hosts2.txt` do echo $HOST osascript -e 'repeat 2 times tell application "Terminal" activate tell application "System Events" to keystroke "t" using [command down] tell application "Terminal" to activate set host to $HOST tell application "Terminal" do shell script "screen -r " & host in front window end tell end repeat' done What I expect to happen is for the code the execute opening new terminal tabs with screen -r for each host. Error output is below this line. dev 44:52: syntax error: Expected end of line but found command name. (-2741) pulsar 44:52: syntax error: Expected end of line but found command name. (-2741) A: There are a few issues with your script: some that stop it from working entirely; some that get it to do the wrong thing; and some that needn't have been there in the first place. There are couple of other answers that address some points, but neither of them appeared to test the script because there's a lot they don't address. ...for each host found in the hosts2.txt file... ...Each host is listed on its own line. Then this line: for HOST in `cat ~/bin/hosts2.txt` is not what you want. That will create an array out of individual words, not lines in the file. You want to use the read command, that reads a file line-by-line. You can structure a loop in this manner: while read -r HOST; do . . . done < ~/bin/hosts2.txt As @entraz has already pointed out, your use of single quotes will stop shell variables from being expanding within your osascript. Then there is the AppleScript itself. I'm unclear why you included a repeat loop. The purpose of the script is to open a new terminal tab on my Mac and automatically launch "screen -r $HOST" in each new terminal until the end of the list of hosts in the hosts2.txt document. Each host is listed on its own line. It is repeating 2 times because there are only 2 hosts listed in the text document This makes no sense, given that you implemented a bash loop in order to read the lines into the $HOST variable. Granted, you were reading words, not lines, but the AppleScript repeat is a head-scratcher. Bin it. Then you have this: tell application "Terminal" activate tell application "System Events" to keystroke "t" using [command down] tell application "Terminal" to activate That's approximately infinity times the number you need to tell Terminal to activate. This line: set host to $HOST will throw an error for two reasons: firstly, host is taken as an existing name of a property in AppleScript's standard additions, so you can't go and set it to a new value; secondly, there are no quotes around $HOST, so it's not going to be recognised as a string. But, this is just for your learning, as we're actually going to get rid of that line completely. Finally: tell application "Terminal" do shell script "screen -r " & host in front window end tell is wrong. do shell script is not a Terminal command. It's a command belonging to AppleScript's standard additions. Therefore, if the rest of your code worked, and it got to this command, Terminal would execute nothing. Instead, the shell scripts would run in the background without an actual shell, so that's not much good to you. The command you're after is do script. Sadly, it does appear that, in High Sierra at least, the AppleScript commands to make new tabs and windows in Terminal no longer work, so I can see why you resorted to System Events to create a tab in the way that you have. Thankfully, that's not necessary, and nor are your multiple activate commands: do script will automatically run Terminal and execute a script in a new tab by default. Therefore, the only AppleScript command you need is this: tell application "Terminal" to do script "screen -r $HOST" The Final Script Putting this all together, here is the final hybrid script: while read -r HOST; do echo "$HOST" osascript -e "tell application \"Terminal\" to do script \"screen -r $HOST\"" done < ~/bin/hosts2.txt Alternatively If you wanted to take the loop from bash and put it in AppleScript instead, you can do so like this, for which I'll use a heredoc (<<) to simplify the use of quotes and aid readability: osascript <<OSA property home : system attribute "HOME" property file : POSIX file (home & "/bin/hosts2.txt") set hosts to read my file using delimiter {return, linefeed} repeat with host in hosts tell application "Terminal" to do script ("screen -r " & host) end repeat OSA
{ "pile_set_name": "StackExchange" }
Q: O que é livelock? O termo deadlock é bem conhecido na programação concorrente, porém acabei me deparando com o termo livelock nos meus estudos, e me perguntei o que seria isso? O que é livelock? E poderia dar algum exemplo (com código em qualquer linguagem, ou pseudocódigo) de como isso acontece? A: Segundo, tradução livre, esta resposta: Retirado de http://en.wikipedia.org/wiki/Deadlock : Na computação simultânea, um impasse é um estado no qual cada membro de um grupo de ações está aguardando que outro membro libere um bloqueio Um livelock é semelhante a um impasse, exceto que os estados dos processos envolvidos no livelock mudam constantemente um em relação ao outro, nenhum progredindo. Livelock é um caso especial de inanição de recursos; a definição geral afirma apenas que um processo específico não está progredindo. Um exemplo real de livelock ocorre quando duas pessoas se encontram em um corredor estreito, e cada uma tenta ser educada movendo-se para o lado para deixar o outro passar, mas elas acabam balançando de um lado para o outro sem progredir, porque ambas se movem repetidamente da mesma maneira ao mesmo tempo. Livelock é um risco em alguns algoritmos que detectam e se recuperam de um conflito. Se mais de um processo executar uma ação, o algoritmo de detecção de deadlock poderá ser acionado repetidamente. Isso pode ser evitado, garantindo que apenas um processo (escolhido aleatoriamente ou por prioridade) tome medidas. Um exemplo para explicar um livelock pode ser encontrado neste link: Imagine um exemplo em que duas ou mais threads precisam adquirir todas as Locks de um objeto, se a thread não conseguir obter todas as locks então ela tenta de novo, isso cria um livelock com todas as threads tentando obter todos os locks mas nenhuma consegue porque uma atrapalha a outra. LiveLock pode ocorrer numa situação onde há um mecanismo de travas em um dado programa que tenham dos recursos compartilhados, A e B. Se uma thread T1 requer lock sobre A e um T2 requer lock sobre B simultaneamente. Após isso T1 tenta acessar B e T2 tenta acessar A concomitantemente, T1 e T2 vão para um estado sleep, quando acordam, voltam a buscar pelo recurso alvo, que continuará com lock em ambas situações. Dada situação está constituído um livelock . Um exemplo em Java pode ser extraído da resposta desta pergunta Good example of livelock?: (Recomendo a leitura dos comentários da resposta) public class Livelock { static class Colher { private Cliente dono; public Colher(Cliente c) { dono = c; } public Cliente getDono() { return dono; } public synchronized void setDono(Cliente c) { dono = c; } public synchronized void usar() { System.out.printf("%s comeu!", dono.nome); } } static class Cliente { private String nome; private boolean comFome; public Cliente(String n) { nome = n; comFome = true; } public String getNome() { return nome; } public boolean isComFome() { return comFome; } public void comerCom(Colher colher, Cliente conjuge) { while (comFome) { // Não tem a colher, então espera pacientemente pelo conjuge. if (colher.dono != this) { try { Thread.sleep(1); } catch(InterruptedException e) { continue; } continue; } // Se o conjuge está com fome, insista em passar a colher. if (conjuge.isComFome()) { System.out.printf( "%s: Você come primeiro %s!%n", nome, conjuge.getNome()); colher.setDono(conjuge); continue; } // Conjuge não está com fome, então coma usando a colher. colher.usar(); comFome = false; System.out.printf( "%s: Estou cheio, %s!%n", nome, conjuge.getNome()); colher.setDono(conjuge); } } } public static void main(String[] args) { final Cliente marido = new Cliente("Bob"); final Cliente esposa = new Cliente("Alice"); final Colher colher = new Colher(marido); new Thread(() -> marido.comerCom(colher, esposa)).start(); new Thread(() -> esposa.comerCom(colher, marido)).start(); } }
{ "pile_set_name": "StackExchange" }
Q: PowerMockito to test MongoClient Singleton I have lazy singleton MongoConnection class with a static method which returns MongoClient instance on MongoConnection.getClient(): public class MongoConnection { private static MongoClient mongoclient; private MongoConnection() { } public static MongoClient getClient() { if (mongoclient == null) { // code to initialize MongoClient } return mongoclient; } } How do I use PowerMockito to mock MongoConnection singleton and test getClient method. I don't have choice over singleton because there will be single instance of MongoClient across the application (as per MongoDB documentation). Note: i don't want to connect to actual DB in test because it will be integration test rather than JUnit; I just want to make sure if MongoClient is initialized with expected parameters. How to do I achieve this with PockerMockito? Thank you A: The following example shows you how to use Mockito with PowerMockito to mock your MongoConnection.getMongoClient(): @RunWith(PowerMockRunner.class) @PrepareForTest({MongoConnection.class}) public class ATest { @Test public void aTestWhichRequiresMockingMongoConnection() { MongoClient mongoClient = Mockito.mock(MongoClient.class); PowerMockito.mockStatic(MongoConnection.class); Mockito.when(MongoConnection.getClient()).thenReturn(mongoClient); // set up some expectations on the mocked MongoClient returned by MongoConnection Mockito.when(mongoClient.getDatabase("aDatabaseName")).thenReturn(...); // ... etc } } This class is verified for: Mockito v2.7.19 PowerMock v1.7.0 JUnit v4.12 As an aside, this: i don't have choice over singleton because there will be single instance of MongoClient across the application(as per MongoDB documentation). ... does not mandate you to make your MongoClient static. You could make getClient() a non static method and ensure that MongoConnection is a singleton i.e. that your application only has single instance of it. Dependency injection solutions (such as Spring, Guice) have built-in support for ensuring that a dependency can be configured as a singleton.
{ "pile_set_name": "StackExchange" }
Q: Accessing associative tables postgresql I'm working on an existing project that uses a postgresql database. This is my first time working with postgresql. I have one major issue that is completely blocking me. In the database creation script, I have the following lines: CREATE TABLE "TA_cat_group" ( cat character varying NOT NULL, group character varying NOT NULL ); When I use a terminal and connect myself to psql, I can describe my database, by doing \d: List of relations Schema | Name | Type | Owner --------+-------------------------+----------+-------- public | TA_cat_group | table | vit public | cat | table | vit ... I can then do \d cat in order to access the description of the cat table. However, if I do \d TA_cat_group the following line appears: Did not find any relation named "TA_cat_group". Because of this issue I'm uncapable of doing requests on this table... What could be the reason for this? PS: I did a \c vit before, so I am connected under the right database, that doesn't seem to be the cause of my problem. Moreover, this schema is supposed to be public... A: Due to the double quotes your table name is now case sensitive. "TA_cat_group" is a different name then TA_cat_group. You need to use \d "TA_cat_group" I would however recommend to never use double quotes in your SQL statements to avoid having to cope with case-sensitive names. More details in the manual: http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS Unrelated, but: you can't use group as a column name without enclosing it in double quotes because it is a reserved keyword. Your example create table in your question will result in: ERROR: syntax error at or near "group" The only way to avoid that error would be to use "group" instead of group - but that however would use those dreaded double quotes.
{ "pile_set_name": "StackExchange" }
Q: Element not shown before jQuery ajax call I have an ajax loader gif that should be shown before the ajax call is triggered and hidden on ajax complete, however the element is not showing up. If I debug using inspect and run step by step the element is shown. $("#ajaxLoader").show(); $('.spn-invalid-zip').hide(); $("#txtZipCode").removeClass("input-validation-error-style"); if ($("#inValidZipCode").length <= 0) { $($('#txtZipCode').parent()).append("<span id='inValidZipCode' class='spn-invalid-zip input-validation-error-style'></span>"); } var valZipCode = value; if (valZipCode.length < 5) { resetCountyFields(); return false; } var zipCodeResult = false; $.ajax({ url: path, type: "POST", data: { zipcode: valZipCode }, async: false, success: function (data) { .... }, complete: function () { $("#ajaxLoader").hide(); } }); A: The issue is because you use async: false in your AJAX call. This blocks the UI thread of the browser from updating while the request is in transit, and hence the imagery you show/hide is never updated on the user's screen. If you remove that property from your AJAX options, your code will work fine: $("#ajaxLoader").show(); // your logic here: $.ajax({ url: path, type: "POST", data: { zipcode: valZipCode }, success: function (data) { .... }, complete: function () { $("#ajaxLoader").hide(); } }); Setting the async property to false is used to make the request synchronous, so that you don't need to use callback functions to retrieve the data in the request and so that the UI will not update until the request ends. It's really bad practice though, and the console will warn you about its use as the browser will appear to the user that it has hung until the request complete, which could be several seconds of inactivity. It's only valid for use in certain situations where code has to complete before the UI updates, onbeforeunload for example. Other than that you should never ever use it.
{ "pile_set_name": "StackExchange" }
Q: Angular what's meaning of three dots in @NGRX what does mean exactly these three dots and why i need them ? export function leadReducer(state: Lead[]= [], action: Action { switch(action.type){ case ADD_LEAD: return [...state, action.payload]; case REMOVE_LEAD: return state.filter(lead => lead.id !== action.payload.id ) } } A: The three dots are known as the spread operator from Typescript (also from ES7). The spread operator return all elements of an array. Like you would write each element separately: let myArr = [1, 2, 3]; return [1, 2, 3]; //is the same as: return [...myArr]; This is mostly just syntactic sugar as it compiles this: func(...args); to this: func.apply(null, args); In your case this gets compiled to this: return [...state, action.payload]; //gets compiled to this: return state.concat([action.payload]); A: It is a spread operator (...) which is used for spreading the element of an array/object or for initializing an array or object from another array or object. Let's create new array from existing array to understand this. let Array1 = [ 1, 2, 3]; //1,2,3 let Array2 = [ 4, 5, 6]; //4,5,6 //Create new array from existing array let copyArray = [...Array1]; //1,2,3 //Create array by merging two arrays let mergedArray = [...Array1, ...Array2]; //1,2,3,4,5,6 //Create new array from existing array + more elements let newArray = [...Array1, 7, 8]; //1,2,3,7,8 A: The ...(spread operator) works by returning each value from index 0 to index length-1:
{ "pile_set_name": "StackExchange" }
Q: Add Script Reference (JavaScript) to Script Manager on Microsoft AJAX Partial Postback I am trying to add a script reference to the script manager in the event of a Microsoft AJAX Partial Postback, ie a user clicks on a link in an Update Panel. ScriptManager.RegisterClientScriptInclude(Page, Page.GetType(), "UniqueName", Page.ResolveUrl(scriptPath)); Doesn't work and either does ScriptReference script = new ScriptReference(scriptPath); MyScriptManager.Scripts.Add(script); From what I have read on the net, RegisterClientScriptInclude should work even in a partial postback. http://www.codeproject.com/KB/ajax/addingCssJsAjaxPartialPos.aspx Can anyone give any ideas why these don't work, or another way to do it? EDIT: Additional information. I am working with a very large legacy code base that has the forms and script manager in each page rather than in the master page. I would like to place the code into a class and use the following call to add the javascript effect. ClientSideScripts.BackgroundColourFade(Page, ScriptManager, Control); The reasons I want to include the script in the method call is Consumes of the method don't have to remember to include the script Changing the script used only requires a change in one place Only include the javascript when needed to keep the load time of the page down A: Have a look at this SO-Question because it answers your question: ScriptManager.RegisterClientScriptInclude does not work in UpdatePanel function dynamic() { alert('dynamic'); $('#divDyn').text('Dynamic!'); } // notify that the script has been loaded <-- new! if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
{ "pile_set_name": "StackExchange" }
Q: Seeking for a fast non parametic clustering algorithm I'm looking for a fast clustering method to cluster a large kind of datas to a unknown count of clusters. I know about the PAM-Algorithm. But it's only efficient for low datasets. Is there a alternative Algorithm? (And maybe a implementation in C or Java?) //EDIT With "parameter-free" i would said that i dont define the number of clusters or the distance between them. In time i only want to cluster time-stamps with the simple L1-Distance(maybe datasets between 1.000 and 5.000 datas). But maybe i want to be cluster datas in NxM (I'm not sure). greetings A: If you can recast your data as a network, then mcl clustering could work - it can handle millions of nodes. It has just one parameter that affects the granularity of the resulting clustering: it is possible to find clusterings at different levels of granularity, but not to specify the number of clusters. Disclaimer: I wrote it. It is used a lot in the field of bioinformatics. High dimensional data can be cast to a network by using a set intersect similarity such as tanimoto similarity, or by a correlation coefficient (which is a type of similarity) such as Pearson's or Spearman's. Most network clustering algorithms expect such a similarity rather than a distance.
{ "pile_set_name": "StackExchange" }
Q: Detecting when Music has finished playing I'm using libgdx to play some background music for a game I'm writing. I have an array of potential music to be played, and I would like that when the current song finishes, another one is chosen at random from the array. The problem I'm having is working out when the Music is finished. The Music class doesn't appear to have any event handlers I could attach to, nor does it have a way of telling me how long it'll take for particular music to finish. The only idea which comes to mind involves polling music.isPlaying() On a loop of some sort, to be able to determine when its stopped. But this is an ugly solution in my opinion - and won't work if (say) the user has turned sound off. Is there anything else I could do ? A: In the latest versions of LibGDX you can define a OnCompletetionListener for your Music. See the documentation. It will be called when the current playback of your music reached the end. When using Sound there is a known problem about this feature. With Sound there really is no way to know when it finished, thanks to the Android API which needs to be supported. I'd suggest the gdx-audio extension in this case, but it's much more low-level and not available for GWT/iOS. See the wiki.
{ "pile_set_name": "StackExchange" }
Q: Pygame and PyOpenGL quad texturing problem I'm trying to texturing a quad and to understand how this little sample works. My code is not original, it's mixed from various examples. Texture: https://jamesmwake.files.wordpress.com/2015/10/uv_texture_map.jpg?w=660 My questions: When I change GL_TEXTURE_MIN_FILTER to GL_TEXTURE_MAG_FILTER in glTexParameteri the texture disappears. Why? When I change GL_LINEAR to GL_NEAREST, nothing happens. The used texture's resolution changed to 300x300px. Why is that? How can I make mipmaps and then using them? The loadImage() function make a texture. How knows PyOpenGL which texture should be used in the makeQuad() function? Code: import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * def loadImage(): img = pygame.image.load("checker_texture_downsized.jpg") textureData = pygame.image.tostring(img, "RGB", 1) width = img.get_width() height = img.get_height() bgImgGL = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, bgImgGL) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, textureData) glEnable(GL_TEXTURE_2D) def makeQuad(): glBegin(GL_QUADS) glTexCoord2f(0, 0) glVertex2f(25, 25) glTexCoord2f(0, 1) glVertex2f(25, 775) glTexCoord2f(1, 1) glVertex2f(775, 775) glTexCoord2f(1, 0) glVertex2f(775, 25) glEnd() def main(): pygame.init() display = (1280,800) pygame.display.set_mode(display, DOUBLEBUF|OPENGL) gluOrtho2D(0, 1280, 0, 800) loadImage() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) makeQuad() pygame.display.flip() main() A: Note, that drawing by glBegin/glEnd sequences, the fixed function pipeline matrix stack and fixed function pipeline per vertex light model, is deprecated since decades. Read about Fixed Function Pipeline and see Vertex Specification and Shader for a state of the art way of rendering. When I change GL_TEXTURE_MIN_FILTER to GL_TEXTURE_MAG_FILTER in glTexParameteri the texture disappears. Why? The initial value of GL_TEXTURE_MIN_FILTER is GL_NEAREST_MIPMAP_LINEAR. If you don't change it and you don't create mipmaps, then the texture is not "complete" and will not be "shown". See glTexParameter. See OpenGL 4.6 API Compatibility Profile Specification; 8.17 Texture Completeness; page 306 A texture is said to be complete if all the texture images and texture parameters required to utilize the texture for texture application are consistently defined. ... a texture is complete unless any of the following conditions hold true: The minification filter requires a mipmap (is neither NEAREST nor LINEAR), and the texture is not mipmap complete. When I change GL_LINEAR to GL_NEAREST, nothing happens. The used texture's resolution changed to 300x300px. Why is that? If the texture is smaller than the region where the texture is wrapped to, the the minification filter has not effect, but the magnification would have an effect. If you set the value GL_NEAREST to the GL_TEXTURE_MAG_FILTER then the texels are not interpolated any more. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) How can I make mipmaps and then using them? Mipmaps can be generated by glGenerateMipmap: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR) glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, textureData) glGenerateMipmap(GL_TEXTURE_2D) The loadImage() function make a texture. How knows PyOpenGL which texture should be used in the makeQuad() function? OpenGL is a state engine. Each state is kept until you change it again, even beyond frames. Since you have bound the texture in loadImage glBindTexture(GL_TEXTURE_2D, bgImgGL) the currently named texture object, which is bound to texture unit 0 is bgImgGL. This texture is used for drawing.
{ "pile_set_name": "StackExchange" }
Q: utf-8 coding in python gui I have simple app with English and Hungarian language. All localizables are in separate modul -localizable.py, for example: #!/usr/bin/python # -*- coding: utf-8 -*- ... ... if language == "hun": LOGIN_LABEL_USERNAME_STR = 'Felhasználó' LOGIN_LABEL_PASSWORD_STR = 'Jelszó' elif language == "eng": LOGIN_LABEL_USERNAME_STR = 'Username' LOGIN_LABEL_PASSWORD_STR = 'Password' But when I use Hungerian language in loginDialog.py: import localizable ... ... loginLayout.addRow(localizable.LOGIN_LABEL_USERNAME_STR, QtGui.QLineEdit()) loginLayout.addRow(localizable.LOGIN_LABEL_PASSWORD_STR, QtGui.QLineEdit()) ... I get Felhasználó and Jelszó instead Felhasználó and Jelszó. Any help would be appreciated. A: Why not use unicode objects in your localizable module, instead of bytestrings with no encoding? if language == "hun": LOGIN_LABEL_USERNAME_STR = u'Felhasználó' LOGIN_LABEL_PASSWORD_STR = u'Jelszó' This has the intended effect for me. You also might want to consider using the built-in functions for this provided by Qt.
{ "pile_set_name": "StackExchange" }
Q: text/html format in codeigniter rest_controller response I need a response in text/html format in one of the methods of the my web service. I use the following code, but it returns the string inside double quotation marks: $this->response("test", REST_Controller::HTTP_OK); How can I have the response as this (without quotation marks): test A: set rest default format in REST_Controller config file to html $config['rest_default_format'] = 'html';
{ "pile_set_name": "StackExchange" }
Q: Do Americans need approval from the United States government in order to become Canadians? A family member living in the states is considering a move to Canada. He has rights to apply for citizenship there in an expedited manner, since he is descended from a Canadian citizen. He has been to Canada as a tourist many times. When we talked about his move, he said that only people who have approval from the U.S. government are allowed to move long-term to Canada. That sounds like a de facto exit visa -- a concept that the U.S. has always proudly renounced. (For example, when people were sneaking out of East Germany, people in the west took great pride in not having the draconian exit limitations that East Germans faced in their country.) Is there a documented policy on the part of the Canadian government that limits entry, residency and/or citizenship to people with a U.S. "stamp of approval" of some sort? A: No this is absolutely not true. I know many Americans who have moved to Canada long term, and become Canadian citizens. Not one of them had to ask permission of the US government. Among other pieces of evidence, consider the huge number of people who moved to Canada to avoid the US draft in the 60s and 70s. If permission had been required they would not have been allowed to leave. Likewise Canada has no policy of requiring permission from the US before admitting US citizens for any length of time, or before making them Canadian citizens. They may possibly consult with US authorities before granting long term residence, but this would be only on matters like criminal records or threats to national security. And it is entirely at Canada's discretion what use they make of the information. Canada does not require someone to renounce a US citizenship before becoming a Canadian citizen. Note that if your family member is descended from Canadians closely enough, e.g. if one of their parents was born in Canada, then that person may already be a Canadian citizen.
{ "pile_set_name": "StackExchange" }
Q: $X$ a normal r.v , calculating $\mathbb{E}(e^{\lambda X})$ $X\sim { \mathcal{N}( \mu , \sigma^2) } $ a normal r.v, $Y = \frac{X-\mu}{\sigma} $ The solution says $\mathbb{E}(e^{\lambda X})= \mathbb{E}(e^{\sigma \lambda Y}) e^{\lambda \mu} = e^{\sigma^2 \lambda^2 + \lambda \mu} $ But what I find is : $\mathbb{E}(e^{\lambda X}) = e^{ \frac{ \sigma^2 \lambda^2}{2} + \lambda \mu} $ I can't see that I made a calculation mistake: $ \mathbb{E}( \frac{X-\mu}{\sigma} ) = \int y \frac{1}{\sqrt{2 \pi}} e^{-y^2/2} $ which gives $Y$ ~ ${ \mathcal{N}( 0 , 1) } $ $ \mathbb{E}(e^{ \lambda Y} ) = \int e^{\lambda y} \frac{1}{\sqrt{2 \pi}} e^{-y^2/2} = e^{\lambda^2/2} \int \frac{1}{\sqrt{2 \pi}} e^{-(y-\lambda)^2/2} = e^{\lambda^2/2}$ Now for $e^{\lambda X}$: $ \mathbb{E}(e^{ \lambda X} ) = \mathbb{E}(e^{ \lambda \sigma Y + \mu \lambda} ) $ $= e^{\lambda \mu}\mathbb{E}(e^{ \lambda \sigma Y } ) $ $= e^{\lambda \mu} \int e^{\lambda \sigma y } \frac{1}{\sqrt{2 \pi}} e^{-y^2/2} $ $= e^{\lambda \mu + \mu ^2\lambda^2/2} \int \frac{1}{\sqrt{2 \pi}} e^{-(y-\sigma \lambda)^2/2} = e^{\lambda \mu + \mu ^2\lambda^2/2}$ EDIT : I made a typing mistake, I meant : $= e^{\lambda \mu + \sigma ^2\lambda^2/2} \int \frac{1}{\sqrt{2 \pi}} e^{-(y-\sigma \lambda)^2/2} = e^{\lambda \mu + \sigma ^2\lambda^2/2}$ A: Your last two equalities are wrong. Note that $\lambda \sigma y-y^{2}/2=-(y-\lambda \sigma )^{2}/2+\lambda ^{2} \sigma ^{2}/2$. EDIT: Your edited answer is correct and the given answer is wrong.
{ "pile_set_name": "StackExchange" }
Q: Android: download images and save them as cache I have this Class which downloads images from the web, and I need someone to help me to modify my code below so the downloaded images are saved on the SDCard. Since I take this code from the internet and I'm a newbie, I'm pretty clueless to optimize it for the cache things. I'm open to any kind of solutions. Thanks much. public class ImageThreadLoader { private static final String TAG = "ImageThreadLoader"; // Global cache of images. // Using SoftReference to allow garbage collector to clean cache if needed private final HashMap<String, SoftReference<Bitmap>> Cache = new HashMap<String, SoftReference<Bitmap>>(); private final class QueueItem { public URL url; public ImageLoadedListener listener; } private final ArrayList<QueueItem> Queue = new ArrayList<QueueItem>(); private final Handler handler = new Handler(); // Assumes that this is started from the main (UI) thread private Thread thread; private QueueRunner runner = new QueueRunner();; /** Creates a new instance of the ImageThreadLoader */ public ImageThreadLoader() { thread = new Thread(runner); } /** * Defines an interface for a callback that will handle * responses from the thread loader when an image is done * being loaded. */ public interface ImageLoadedListener { public void imageLoaded(Bitmap imageBitmap ); } /** * Provides a Runnable class to handle loading * the image from the URL and settings the * ImageView on the UI thread. */ private class QueueRunner implements Runnable { public void run() { synchronized(this) { while(Queue.size() > 0) { final QueueItem item = Queue.remove(0); // If in the cache, return that copy and be done if( Cache.containsKey(item.url.toString()) && Cache.get(item.url.toString()) != null) { // Use a handler to get back onto the UI thread for the update handler.post(new Runnable() { public void run() { if( item.listener != null ) { // NB: There's a potential race condition here where the cache item could get // garbage collected between when we post the runnable and it's executed. // Ideally we would re-run the network load or something. SoftReference<Bitmap> ref = Cache.get(item.url.toString()); if( ref != null ) { item.listener.imageLoaded(ref.get()); } } } }); } else { final Bitmap bmp = readBitmapFromNetwork(item.url); if( bmp != null ) { Cache.put(item.url.toString(), new SoftReference<Bitmap>(bmp)); // Use a handler to get back onto the UI thread for the update handler.post(new Runnable() { public void run() { if( item.listener != null ) { item.listener.imageLoaded(bmp); } } }); } } } } } } /** * Queues up a URI to load an image from for a given image view. * * @param uri The URI source of the image * @param callback The listener class to call when the image is loaded * @throws MalformedURLException If the provided uri cannot be parsed * @return A Bitmap image if the image is in the cache, else null. */ public Bitmap loadImage( final String uri, final ImageLoadedListener listener) throws MalformedURLException { // If it's in the cache, just get it and quit it if( Cache.containsKey(uri)) { SoftReference<Bitmap> ref = Cache.get(uri); if( ref != null ) { return ref.get(); } } QueueItem item = new QueueItem(); item.url = new URL(uri); item.listener = listener; Queue.add(item); // start the thread if needed if( thread.getState() == State.NEW) { thread.start(); } else if( thread.getState() == State.TERMINATED) { thread = new Thread(runner); thread.start(); } return null; } /** * Convenience method to retrieve a bitmap image from * a URL over the network. The built-in methods do * not seem to work, as they return a FileNotFound * exception. * * Note that this does not perform any threading -- * it blocks the call while retrieving the data. * * @param url The URL to read the bitmap from. * @return A Bitmap image or null if an error occurs. */ public static Bitmap readBitmapFromNetwork( URL url ) { InputStream is = null; BufferedInputStream bis = null; Bitmap bmp = null; try { URLConnection conn = url.openConnection(); conn.connect(); is = conn.getInputStream(); bis = new BufferedInputStream(is); bmp = BitmapFactory.decodeStream(bis); } catch (MalformedURLException e) { Log.e(TAG, "Bad ad URL", e); } catch (IOException e) { Log.e(TAG, "Could not get remote ad image", e); } finally { try { if( is != null ) is.close(); if( bis != null ) bis.close(); } catch (IOException e) { Log.w(TAG, "Error closing stream."); } } return bmp; } } A: You can store bitmaps using the compress method of Bitmap class : here My own code is: FileOutputStream os = null; try { os = new FileOutputStream( new File( android.os.Environment.getExternalStorageDirectory().getAbsolutePath(), fileName)); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, os); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } It allows you to write a bitmap on SD card. To open a bitmap stored on SD card use the decodeFile() method from BitmapFactory class: here You should also verify if you can read and write on your SD card using: android.os.environment.getExternalStorageDirectory().canRead() and android.os.environment.getExternalStorageDirectory().canWrite() methods.
{ "pile_set_name": "StackExchange" }
Q: TSQL efficiency - INNER JOIN replaced by EXISTS Can the following be rewritten to be more efficient? I would use EXISTS if I didn't need fields from country but I do need those fields, and am not sure how to write this to make it more efficient. SELECT distinct p.ProvinceID, p.Abbv as RegionCode, p.name as RegionName, cn.Code as CountryCode, cn.Name as CountryName FROM dbo.provinces AS p INNER JOIN dbo.Countries AS cn ON p.CountryID = cn.CountryID INNER JOIN dbo.Cities c on c.ProvinceID = p.ProvinceID INNER JOIN dbo.Listings AS l ON l.CityID = c.CityID WHERE l.IsActive = 1 AND l.IsApproved = 1 A: There are two things to note: You're joining to dbo.Listings which results in many records, so you need to use DISTINCT (usually an expensive operator) For any tables with columns not in the select you can move into an EXISTS (but the query planner effectively does this for you anyway) So try this: SELECT p.ProvinceID, p.Abbv as RegionCode, p.name as RegionName, cn.Code as CountryCode, cn.Name as CountryName FROM dbo.provinces AS p INNER JOIN dbo.Countries AS cn ON p.CountryID = cn.CountryID WHERE EXISTS (SELECT 1 FROM dbo.Listings l INNER JOIN dbo.Cities c on l.CityID = c.CityID WHERE c.ProvinceID = p.ProvinceID AND l.IsActive = 1 AND l.IsApproved = 1 ) Check the query plans before and after - the query planner might be smart enough to do this anyway, but you have removed your distinct
{ "pile_set_name": "StackExchange" }
Q: Encoding multidimensional arrays in raw transaction data Say, there is a function in a contract: function foo(uint[2][2][2] numbers) {} How the following array should be encoded in raw transaction data? [ [ [ 1, 2 ], [ 3, 4 ] ], [ [ 5, 6 ], [ 7, 8 ] ] ] What if array is incomplete? [ [ [ 1, 2 ] ], [ [ 5 ], [ 7, 8 ] ] ] Also, is there a plan to support dynamically-sized multidimensional arrays (e.g. uint[][][], string[][]) in function arguments / return values? A: According to the official answer from the Ethereum team: This should be working now (in latest nightly) via using the new experimental encoder: pragma experimental ABIEncoderV2; contract C { function f() returns (uint[][][] memory) { } } Note: this will turn on an experimental feature (which is also noted in the metadata) and should not be used in production. It is only about encoding, decoding is not supported.
{ "pile_set_name": "StackExchange" }
Q: Ошибка инициализации в конструкторе C26495 Mat::Mat() { int a1[3][3] = { { 0,0,0 }, { 0,0,0 }, { 0,0,0 } }; int a2[3][3] = { { 0,0,0 }, { 0,0,0 }, { 0,0,0 } }; int a3[3][3] = { { 0,0,0 }, { 0,0,0 }, { 0,0,0 } }; int aa[18] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; int n = 0; int i = 0; int j = 0; int temp = 0; int r = 0;} Пишет Предупреждение C26495 Variable 'Mat::temp' is uninitialized. Always initialize a member variable (type.6). Lab 1. n 4 c:\users\antgo\source\repos\lab 1. n 4\matr.cpp 7 Предупреждение C26495 Variable 'Mat::a1' is uninitialized. Always initialize a member variable (type.6). Lab 1. n 4 c:\users\antgo\source\repos\lab 1. n 4\matr.cpp 7 Предупреждение C26495 Variable 'Mat::a2' is uninitialized. Always initialize a member variable (type.6). Lab 1. n 4 c:\users\antgo\source\repos\lab 1. n 4\matr.cpp 7 Предупреждение C26495 Variable 'Mat::a3' is uninitialized. Always initialize a member variable (type.6). Lab 1. n 4 c:\users\antgo\source\repos\lab 1. n 4\matr.cpp 7 Предупреждение C26495 Variable 'Mat::aa' is uninitialized. Always initialize a member variable (type.6). Lab 1. n 4 c:\users\antgo\source\repos\lab 1. n 4\matr.cpp 7 Предупреждение C26495 Variable 'Mat::i' is uninitialized. Always initialize a member variable (type.6). Lab 1. n 4 c:\users\antgo\source\repos\lab 1. n 4\matr.cpp 7 Предупреждение C26495 Variable 'Mat::j' is uninitialized. Always initialize a member variable (type.6). Lab 1. n 4 c:\users\antgo\source\repos\lab 1. n 4\matr.cpp 7 Предупреждение C26495 Variable 'Mat::n' is uninitialized. Always initialize a member variable (type.6). Lab 1. n 4 c:\users\antgo\source\repos\lab 1. n 4\matr.cpp 7 Предупреждение C26495 Variable 'Mat::r' is uninitialized. Always initialize a member variable (type.6). Lab 1. n 4 c:\users\antgo\source\repos\lab 1. n 4\matr.cpp 7 A: Видимо ваш класс Mat содержит массивы и обьекты с такими именами, и вы пытаетесь инициализировать в конструкторе эти члены, но неудачно, так как вы определяете новые обьекты и массивы, придворяя их иммена именем типа. Таким образом оставляете члены неинициализированными. Просто уберите имя типа int и получите присвоение этих обьектов. a1[3][3] = ... a2[3][3] = .. //... n = 0; i = 0; //... P.S. Чтобы инициализировать все элементы массива нулем(значением по умолчанию), достаточно инициализировать только первый: aa[18] = { 0 };
{ "pile_set_name": "StackExchange" }
Q: how to assign data to include layout in xml? Assume we have a layout contains a TextView: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/text1" style="@style/text_style"/> </LinearLayout> and then include this layout several times: <include android:id="@+id/info1" layout="@layout/myLayout" /> <include android:id="@+id/info2" layout="@layout/myLayout" /> <include android:id="@+id/info3" layout="@layout/myLayout" /> Is it possible to assign text into each TextView in the xml file which contains these layouts? If not, then how to assign in runtime? A: You can, For this you need to identify you layout LinearLayout info1 = (LinearLayout)findViewById(R.id.info1); Then with this layout object you need to identify you TextView TextView text1 = (TextView)info1.findViewById(R.id.text1); text1.setText("Your text");
{ "pile_set_name": "StackExchange" }
Q: email/password authentication for firebase SERVER_ERROR I'm trying to use Firebase's simple login and attempting to follow the general methods laid out in How do I use Firebase Simple Login with email & password. Everytime I try to create a new user (or sign in), however, I get a SERVER_ERROR: The connection to wss://s-xxxxxxxx was interrupted while the page was loading. How is this caused and how can I solve it? Also, it works on Firefox when I hardcode values (i.e. take createUser outside of the register submit handler), but not on Chrome. login.html <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> <script type='text/javascript' src='https://cdn.firebase.com/v0/firebase.js'></script> <script type='text/javascript' src='https://cdn.firebase.com/v0/firebase-simple-login.js'></script> </head> <body> <div id="login_or_register"> </div> <button id="logout">Logout</button> <script type='text/javascript' src='loginScript.js'></script> </body> </html> loginScript.js function showLoginRegister(auth){ $register_form = $('<form id="register">'+ '<input type="text" name="register-email" id="register-email" value="[email protected]">'+ '<input type="password" name="register-password" id="register-password" value="password">'+ '<input type="submit" value="Create an account!"/>'+'</form>') $login_form = $('<form id="login">'+'<input type="text" name="login-email" id="login-email" value="[email protected]">'+ '<input type="password" name="login-password" id="login-password" value="password">'+ '<input type="checkbox" name="rememberCheckbox" id="rememberCheckbox" checked>'+ '<input type="submit" value="Sign in"/>'+'</form>') $('#login_or_register').append($register_form,$login_form); $("#register").submit(function() { var email = $("#register-email").val(); var password = $("#register-password").val(); auth.createUser(email, password, function(error, user) { if (!error) { auth.login("password", { email: email, password: password, rememberMe: false }); } else{ console.log(error); } }); }); $("#login").submit(function() { var email = $("#login-email").val(); var password = $("#login-password").val(); var checkbox = $("#rememberCheckbox").val(); auth.login("password", { email: email, password: password, rememberMe: checkbox }); }); }; var ref = new Firebase('https://xxx.firebaseio.com/'); var auth = new FirebaseSimpleLogin(ref, function(error, user) { if (error){ console.log(error); return; } if (user) { // user authenticated with Firebase $("#logout").click(function(){ auth.logout(); }) } else { showLoginRegister(this); // user is logged out } }); A: The problem you're seeing is that the network request for the login methods are failing since you're navigating away from the current page before they can complete. The form is actually being submitted, and the page is redirecting / refreshing as a result. In order to prevent this behavior, update your code to include a return false; at the bottom of each of the $(element).submit() methods, which will prevent the form from submitting and the authentication requests will complete. $("#el").submit(function() { // Do stuff here ... return false; });
{ "pile_set_name": "StackExchange" }
Q: The Diophantine equation $x^2 + 2 = y^3$ How to solve the Diophantine equation $x^2 + 2 = y^3$ with $x,y>0$ ? ($x,y$ are integers.) A: Although I prefer an answer without ring theory here is a solution by using the extension $\mathbb{Z}[\sqrt{-2}]$. All variables in this proof are integers. $x^2+2=y^3$ factors as $(x+\sqrt{-2})(x-\sqrt{-2})=y^3$. Since $1)$ $\mathbb{Z}[\sqrt{-2}]$ is a UFD. $2)$ the LHS factors into $2$ conjugates which implies that the LHS must have $2n$ primefactors. (A conjugate factors analogue to its Original in a UFD , this is easy to show when using the norm) 3) the RHS must have $3m$ prime factors and the smallest common multiple of $2$ and $3$ is $6$. We can conclude that : $1)$ both LHS and RHS has $6A$ prime factors. $2)$ Since we have two conjugates on the LHS we can conclude that $(x+\sqrt{-2})$ is a cube in $\mathbb{Z}[\sqrt{-2}]$. Hence we get the equation $(x+\sqrt{-2})=(a+b\sqrt{-2})^3$ We proceed by expanding the cube : $x+\sqrt{-2} = a^3 - 6 a b^2 + (3 a^2 b-2 b^3)\sqrt{-2}$ We can solve the sqrt part $3 a^2 b-2 b^3 = 1$ because $b^2$ must be $1$ because $b$ is a factor on the LHS !! Let $b=1$ then we get $3a^2 - 2 = 1$ hence $a=1$. It follows $x=a^3 - 6a b^2 = 5$. If we took $b=-1$ or factored $x-\sqrt{-2}$ we get the same or a negative solution for $x$ hence $x=5$ is the only positive solution. We thus get $5^2 + 2 = 3^3$ Q.E.D. mick
{ "pile_set_name": "StackExchange" }
Q: iCloud PhotoStream syncing to seperate Windows devices with shared App/Music/iTunes sync I have been asked to help out with a friends iTunes/iOS/Phot syncing setup, they have 4 iOS devices (all iOS 5 compatible except one 3G iPhone) and a range of iTunes libraries that they have previously synced to. What they want to acheive is to share an Apple ID for purchases from the App Store, and also all sync to a single iTunes library on a shared Windows PC for music syncing etc. This bit is simple enough. Where it get's complicated is that want to be able to maintain their photos seperately on their own PCs (no Macs anywhere...sigh). I know that previously in Windows you could select a folder to sync pics to (as a crappy iPhoto replacement) and there was also some vague album support from a couple of Windows Apps (Photoship Elements?), but they dont have any of the apps. I also know about the Scanner & Camera Wizard/Windows Live Photo wizard also, which may still be the only option for the 3G iPhone which will not support iOS5, and thus iCloud accounts (I think this is true, corrections welcomed). What I want to propose to them, if possible, is to use the single Apple ID and sync to a single iTunes library for music/apps/backups etc for all devices, but each have their own iCloud account, and use Photo Stream to keep their photos seperate and not have them all sync to the same shared PC that the iTunes software runs on. I have no idea how Photostream works on a Windows machine, it is possible to log into iCloud through a control panel widget like you did with Mobile Me on Windows, and sign into iCloud and turn on Photostream to sync photos (either to a folder, or an app) on a per iCloud account basis, allowing them to all sync photos to their individual machines while keeping the iTunes sync relationship to a shared device? (Note, the Apple ID/Music bit is included for reference and completeness, I am only querying the capabilities of iCloud/Photostream, and would appreciate replies on that, not any suggestions to do anything different with the Apps/Music bit - just setting expactations, thanks) A: Simple. Use one AppleID for purchasing. Use one or many computers to download this content. Remember that iTunes can sync apps to computer A and music to computer B and photos to computer C. Each person can decide to join the communal computer for App syncing / backup / downloading without it affecting their Photo browsing. If they each get an iCloud account and use it for the rest - they can use the iCloud software on their PC to get the pictures or sync manually like any other photo device connected via USB. I haven't tested it, but WiFI sync might also be available on the PC side of iTunes. Good Luck! Let us know how you fare...
{ "pile_set_name": "StackExchange" }
Q: i need some help about using sessions in code igniter I am using codeigniter. I used session variable to store a id in a function and get the stored value in another function. I have a controller file which is given below: public function select_service($id) { $this->load->library('session'); $this->session->unset_userdata('employee'); $this->session->set_userdata('employee', ['total'=>$id]); // $id = $this->uri->segment(4); $data['service'] = $this->add_service_model->get_services(); $data['main_content'] = 'admin/service_limitation/service_view'; $this->load->view('includes/template', $data); } In the above code I get the id from a form and store in the session variable public function services() { //here i need to get the session variable employee['total'] $id = $this->uri->segment(5); $data_to_store=array('employee_id'=>$id,'service_id'=>$this->input->post("services")); $this->add_service_model->save($data_to_store); $data['addservice'] = $this->add_service_model->get_addservices(); $data['main_content'] = 'admin/service_limitation/newview'; $this->load->view('includes/template', $data); } In this function service I need to retrieve the stored value. both functions are in same controller. can some one help me with the code? A: Manuall Auto load the session library. This way the session is always loaded. when setting the id do: $this->session->set_userdata('employee', $id); when you want to get that id user $id = $this->session->userdata('employee');
{ "pile_set_name": "StackExchange" }
Q: PHP - file edit form shows blank I wanted to make an edit file form where you choose the a different file to upload and replace the previous file. This is my code. <?php require("config.php"); $id = $_GET['id']; $sql = "SELECT * FROM contracts WHERE id= '$id'"; $result = $con->query($sql); while ($row = $result->fetch_assoc()) { ?> <html><head></head> <body> <form method="GET" action="" enctype="multipart/form-data"> ID: <?php echo $id; ?><br> <input type="hidden" name="id" value="<?php echo $id; ?>" /> Upload File: <input type="file" name="upload" value="<?php echo $row($_FILES['name']) ?>"/><br> <input type="submit" name="submit" value="Submit"/> </form> </body> </html> <?php } if(isset($_GET['edit']) ){ if ($_FILES['upload']['size'] != 0 ){ $filename = $con->real_escape_string($_FILES['upload']['name']); $filedata= $con->real_escape_string(file_get_contents($_FILES['upload']['tmp_name'])); $filetype = $con->real_escape_string($_FILES['upload']['type']); $filesize = intval($_FILES['upload']['size']); $query = "UPDATE `contracts` set `filename` = '$filename',`filedata` = '$filedata', `filetype` = '$filetype',`filesize` = '$filesize' WHERE `id` = '$id' " ; if ($con->query($query) == TRUE) { echo "<br><br> New record created successfully"; } else { echo "Error:<br>" . $con->error; } } else { $filename = $con->real_escape_string($_FILES['upload']['name']); $filetype = $con->real_escape_string($_FILES['upload']['type']); $filesize = intval($_FILES['upload']['size']); $query = "UPDATE `contracts` set `filename` = '$filename', `filetype` = '$filetype',`filesize` = '$filesize' WHERE `id` = '$id' " ; if ($con->query($query) == TRUE) { echo "<br><br> New record created successfully"; } else { echo "Error:<br>" . $con->error; } } $con->close(); } ?> When I went to the page it only shows blank. Like this Can someone tell me what did I do wrong? A: The correct coding should be Upload File: <?php echo $row['filename'] ?> <input type="file" name="upload"/><br> <input type="submit" name="edit" value="Submit"/>
{ "pile_set_name": "StackExchange" }
Q: How to create an mkv file from an mkv and an mka file from termial I have a bunch of mkv files, and an mka file for each one with the same name. I would like to merge them. I can do it with mkvmerge-gui one-by-one, but I want to do it from the terminal, because a script would be able to do it for each file. I tried this: mkvmerge -o 001.mkv EP01.mkv +EP01.mka And i get this: mkvmerge v7.1.0 ('Good Love') 64bit built on Jul 27 2014 13:10:18 'EP01.mkv': Using the demultiplexer for the format 'Matroska'. 'EP01.mka': Using the demultiplexer for the format 'Matroska'. 'EP01.mkv' track 0: Using the output module for the format 'AVC/h.264'. 'EP01.mkv' track 1: Using the output module for the format 'FLAC'. 'EP01.mkv' track 2: Using the output module for the format 'FLAC'. 'EP01.mka' track 0: Using the output module for the format 'FLAC'. 'EP01.mka' track 1: Using the output module for the format 'FLAC'. 'EP01.mka' track 2: Using the output module for the format 'AC3'. 'EP01.mka' track 3: Using the output module for the format 'PGS'. 'EP01.mka' track 4: Using the output module for the format 'PGS'. No append mapping was given for the file no. 1 ('EP01.mka'). A default mapping of 1:0:0:0,1:1:0:1,1:2:0:2,1:3:0:3,1:4:0:4 will be used instead. Please keep that in mind if mkvmerge aborts with an error message regarding invalid '--append-to' options. Error: The file no. 0 ('EP01.mkv') does not contain a track with the ID 3, or that track is not to be copied. Therefore no track can be appended to it. The argument for '--append-to' was invalid. Thank you for your help! A: You do not need the + sign in the command. It means something quite different than you think. mkvmerge -o output.mkv input.mkv input.mka This should do the trick for you. The plus sign appends the streams from the second file to the first. So if you were to have two video files and you wanted to make a single file that plays first the video from file1 and then video from file2 on the same stream, then you'd use the plus. The error basically tells you that it cannot find any video in your .mka file, and it has nothing to append.
{ "pile_set_name": "StackExchange" }
Q: How to compare dates to make sure Google Apps Script is only sending an alert once a day? I have a script in a Google Sheet that is sending out an alert if a certain condition is met. I want to trigger the script to run hourly, however, if an alert was already sent out today, I don't want to send out another one (only the next day). What is the best way to achieve this? I've tried formatting the date several ways, but somehow the only thing working for me so far is getting the year, month and day from the date object as int and comparing them separately. function sendAlert{ var now = new Date(); var yearNow = now.getYear(); var monthNow = now.getMonth() + 1; var dayNow = now.getDate(); var sheet = SpreadsheetApp.getActive().getSheetByName('CHANGE_ALERT'); var sentYear = sheet.getRange("R2").getValue(); var sentMonth = sheet.getRange("S2").getValue(); var sentDay = sheet.getRange("T2").getValue(); if (yearNow != sentYear || monthNow != sentMonth || dayNow != sentDay) { sendEmail(); var sentYear = sheet.getRange("R2").setValue(yearNow); var sentMonth = sheet.getRange("S2").setValue(monthNow); var sentDay = sheet.getRange("T2").setValue(dayNow); else { Logger.log('Alert was already sent today.'); } } I think this solution is definitely not the best approach, but I cannot come up with another that merges the date into one. Only comparing the new Date() doesn't work, since the time of day will not necessarily be the same. If I format the date to YYYY-MM-dd, it should work, but then when I get the date again from the spreadsheet it gets it as a full date with the time again. A: Requirement: Compare dates and send an email if one hasn't been sent already today. Modified Code: function sendAlert() { var sheet = SpreadsheetApp.getActive().getSheetByName('blank'); var cell = sheet.getRange(2,18); //cell R2 var date = new Date(); var alertDate = Utilities.formatDate(cell.getValue(), "GMT+0", "yyyy-MM-dd"); var currentDate = Utilities.formatDate(date, "GMT+0", "yyyy-MM-dd"); if (alertDate !== currentDate) { sendEmail(); cell.setValue(date); } else { Logger.log('Alert was already sent today.'); } } As you can see, I've removed all of your year/month/day code and replaced it with Utilities.formatDate(), this allows you to compare the dates in the format you specified in your question. I've also changed the if statement to match this, so now we only need to compare alertDate and currentDate. References: Utilities.formatDate() Class SimpleDateFormat
{ "pile_set_name": "StackExchange" }
Q: PDI/Kettle: avoid file creation or mapping (sub-transformation) execution It's clear by now that all steps from a transformation are executed in parallel and there's no way to change this behavior in Pentaho. Given that, we have a scenario with a switch task that checks a specific field (read from a filename) and decides which task (mapping - sub-transformation) will process that file. This is part of a generic logic that, before and after each mapping task, does some boilerplate tasks as updating DB records, sending emails, etc. The problem is: if we have no "ACCC014" files, this transformation cannot be executed. I understand it's not possible, as all tasks are executed in parallel, so the second problem arises: inside SOME mappings, XML files are created. And even when Pentaho is executing this task with empty data, we can't find a way of avoiding the XML output file creation. We thought about moving this switch logic to the job, as in theory it's serial, but found no conditional step that would do this kind of distinction. We also looked to Meta Data Injection task, but we don't believe it's the way to go. Each sub-transformation does really different jobs. Some of them update some tables, other ones write files, other ones move data between different databases. All of them receive some file as input and return a send_email flag and a message string. Nothing else. Is there a way to do what we are willing for? Or there is no way to reuse part of a logic based on default inputs/outputs? Edit: adding ACCC014 transformation. Yes, the "Do not create file at start" option is checked. A: You can use Transformation Executor step (http://wiki.pentaho.com/display/EAI/Transformation+Executor) in order to execute transformation conditionally. Though I haven’t really used this step, so I can’t say anything about it’s stability or performance. Main transformation: Set-up your parent transformation like this: Regarding the Injector step: in 5.2 version, I was not able to get fields created in the sub-transformation even though they were defined on “result rows” tab, so I had to define all these fields in the Injector step instead. Not sure, if it is still necessary in current version. Possible adjustments for Transformation Executor: Probably, you’d want to change The number of rows to send to the transformation value on Row grouping tab: set it to 0 in order to send all rows at once instead of re-executing the transformation for every N rows. If you want to read output of your sub-transformation, select “This output will contain the result rows after execution” option while creating the hop to the subsequent step: Sub-transformation: The only change you'll probably need here is to replace your mapping input and output by Get rows from result and Copy rows to result: Known issue in 5.2: It seems like the job executor reads the output of sub-transformation not from the “Copy rows to result” step, but from the most recently created step. So, if you have added some steps to your sub-transformation, remember to re-create the step, from which you expect to read the output: just select the “Copy rows to result”, cut it, paste it back and re-create the hop.
{ "pile_set_name": "StackExchange" }
Q: Error inside the class I have created this class, but there is an error last part saying "Syntax error on token "(", delete this token" on the "timers.schedule part" public class refrend { Timer timers = new Timer(); final Handler handler = new Handler(); int initial = 1000; int looper = 6000; TimerTask task = new TimerTask() { @Override public void run() { handler.post(new Runnable() { public void run() { new activityIns().execute(); } }); } }; timers.schedule(task, initial, looper); } Thanks for your help :) A: what you can do is to create a function public class refrend { Timer timers = new Timer(); final Handler handler = new Handler(); int initial = 1000; int looper = 6000; public void your_Function(){ TimerTask task = new TimerTask() { @Override public void run() { handler.post(new Runnable() { public void run() { // new activityIns().execute(); } }); } }; timers.schedule(task, initial, looper); } } now you can call that function in you class by your_Functino(); and if you want to use that function out side of class create it object and call it refrend object=new refrend(); object.your_Function();
{ "pile_set_name": "StackExchange" }