text
stringlengths
64
89.7k
meta
dict
Q: How to compute the output? How to compute the output for the recursive functions ? I know recursion invokes a stack, but am confusing while solving some aptitude question. Given the following code snippet: #include <stdio.h> void fun(int a){ if(a>0){ fun(--a); printf("%d ",a); fun(--a); printf("%d ",a); } return; } int main(void){ int num = 5; fun(num); return 0; } This is not any home work assignment but I am unable to solve such question under exam condition.(Theoretical exam without Compiler) What is the standard way to solve such question ? Please explain with a small example.Any pointer in the right direction or some web link will be welcomed. A: Take a pen and paper; draw the invocations of the function along with the parameters - you'll have a kind of a binary tree. Track the execution and write all relevant data on the page. It will also help you understand the functionality. The branching involved in recursive invocations (especially binary ones like this one) is very logical and intuitive when you draw it on a paper. This is how I was taught back in school - and imo its a good way of understanding stuff like this, at least at the beginning when not everything is as intuitive. Example: fun [5] / \ fun[4] fun[3] / \ | \ fun[3] fun[2] fun[2] fun[1] I've drawn the calling tree, the same way you can draw it on the paper. This should help with making whats happening clearer for you. And that's really the way I handled this kind of stuff back in the day, so trust me - it works :) A: Writing a recursive method is a bit like making a plan to line up dominoes and knock them over. You have to anticipate how each individual recursive call (domino) is going to add its part to accomplishing the whole task. That means that the "meat" of a recursive method is not in the recursive part, but in the "end cases" the parts of the code that execute when you are not going to re-call the method, the last domino in the chain, the one that you push to start the fun. So, let's look at your first example, a recursive program for (integer) division. The division algorithm you are trying to implement is "for positive d and n, let n(0) be n. Keep subtracting d from n(i) step by step, until in some step q, n(q) is less than d. Your answer is q." The key is to look at the END case first. What if at the start n is already less than d? Then you did "zero steps", so your division result is 0. In pseudocode: int divide(int n, int d) { if (n < d) { return 0; } .... } Now what if n is not less than d (greater than or equal to d)? Then we want to try another step in the division process with a smaller n. That is, run the divide function again with "the same d" and n = "the old n" - d. But once THAT divide finishes it only tells us how many subtraction steps were required for (n-d)/d. We know that n/d requires one more step. So we have to add that step tally to the result: int divide(int n, int d) { if (n < d) { return 0; } else { return divide( n-d, d ) + 1; } } What is that second return actually saying? It says: " I don't know how to compute the result myself, but I do know that it is ONE MORE than the result for 'divide( n-d, d )'. So I will 'pass the buck' to that method call and then just add one to whatever it gives me back." And the process continues. We keep adding "divide" dominoes to the chain until we reach a divide operation where n has "shrunk" to be smaller than d... our end case, our zero result. Now we knock over the first domino (the last one we added to the chain), returning "0". And the dominoes begin to fall. Every time one domino knocks over another domino we add "1" to the method result until finally the first method call is the last domino to fall, and it returns the division result. Let's try some examples: 12/18: divide(12,18) ---> returns 0, since 12 is less than 18 result is 0. 20/5: divide(20, 5) ---> returns divide(20-5, 5) + 1 ------> returns divide(15-5, 5) +1 ---------> returns divide(10-5, 5) +1 ------------> returns divide(5-5, 5) +1 ---------------> returns 0, since 5-5 is 0, which is less than 5 and now the dominoes fall... ------------> returns 0 + 1 ---------> returns 1 + 1 ------> returns 2 + 1 ---> returns 3 + 1 result is 4. 8/3: divide(8, 3) ---> returns divide(8-3, 3) + 1 ------> returns divide(5-3, 3) +1 ---------> returns 0, since 5-3 is 2, which is less than 3 and now the dominoes fall... ------> returns 0 + 1 ---> returns 1 + 1 result is 2.
{ "pile_set_name": "StackExchange" }
Q: Given two arrays, find the item in array A with unique values in array B I've two arrays and one of them is too large. And the other one's max length is 9. What I tried to achieve is, I want to find items in the larger array by giving small array's items. I did something like that; const largeArray = [ { id: 23 }, { id: 12 }, { id: 43 }, { id: 54 }, { id: 15 }, //and so on and all ids are unique ] const smallArray = [23, 12, 43] smallArray.map(smallArrayItem => { largeArray.map(largeArrayItem => { if (smallArrayItem === largeArrayItem.id) { console.log(largeArrayItem) } }) }) But IMO that is not an efficient way. It's very slow. It takes almost 2 seconds to find the items. How do I make faster this search in a proper way? A: Please use filter and includes const largeArray = [ { id: 23 }, { id: 12 }, { id: 43 }, { id: 54 }, { id: 15 }, ] const smallArray = [23, 12, 43] const diff = largeArray.filter(item => !smallArray.includes(item.id)); console.log(diff);
{ "pile_set_name": "StackExchange" }
Q: min/max number of records on a B+Tree? I was looking at the best & worst case scenarios for a B+Tree (http://en.wikipedia.org/wiki/B-tree#Best_case_and_worst_case_heights) but I don't know how to use this formula with the information I have. Let's say I have a tree B with 1,000 records, what is the maximum (and maximum) number of levels B can have? I can have as many/little keys on each page. I can also have as many/little number of pages. Any ideas? (In case you are wondering, this is not a homework question, but it will surely help me understand some stuff for hw.) A: I don't have the math handy, but... Basically, the primary factor to tree depth is the "fan out" of each node in the tree. Normally, in a simply B-Tree, the fan out is 2, 2 nodes as children for each node in the tree. But with a B+Tree, typically they have a fan out much larger. One factor that comes in to play is the size of the node on disk. For example, if you have a 4K page size, and, say, 4000 byte of free space (not including any other pointers or other meta data related to the node), and lets say that a pointer to any other node in the tree is a 4 byte integer. If your B+Tree is in fact storing 4 byte integers, then the combined size (4 bytes of pointer information + 4 bytes of key information) = 8 bytes. 4000 free bytes / 8 bytes == 500 possible children. That give you a fan out of 500 for this contrived case. So, with one page of index, i.e. the root node, or a height of 1 for the tree, you can reference 500 records. Add another level, and you're at 500*500, so for 501 4K pages, you can reference 250,000 rows. Obviously, the large the key size, or the smaller the page size of your node, the lower the fan out that the tree is capable of. If you allow variable length keys in each node, then the fan out can easily vary. But hopefully you can see the gist of how this all works. A: It depends on the arity of the tree. You have to define this value. If you say that each node can have 4 children then and you have 1000 records, then the height is Best case log_4(1000) = 5 Worst case log_{4/2}(1000) = 10 The arity is m and the number of records is n.
{ "pile_set_name": "StackExchange" }
Q: flexigrid get id of highlighted row I understand this looks like a duplicate question, however its a bit different. I need to get back a value for an input contained in a table i can get the value for the row id but not for the input so any help would be brilliant. A cut down version of the table can be seen below. So how do i return the value for the checkbox on mouseeneter. Thank you. <table id="tblOrder" class="flexigrid autoht"> <tr id="row1081"> <td align="left"> <div class="proper"> <input type="checkbox" id="OrderId[1081]" name="OrderId" value="1081"/> </div> </td> </tr> <tr id="row1082"> <td align="left"> <div class="proper"> <input type="checkbox" id="OrderId[1082]" name="OrderId" value="1082"/> </div> </td> </tr> </table> What i have tried so far is: $('#tblOrder tr[id*="row"]').live('mouseenter', function(){ console.log($('input[name="OrderId"]', '#tblOrder').val()); }); A: It sounds like you're trying to get the checked value (true, false) for the checkbox inside the table, if that's the case try http://jsfiddle.net/82gwa0cn/ $("tr input").on("mouseenter", function(){ alert($(this).is(':checked')); }); If you're trying to get the value of the checkbox try http://jsfiddle.net/82gwa0cn/1/ $("tr input").on("mouseenter", function(){ alert($(this).val()); }); So basically, bind to the mouseenter of input, not the tr.
{ "pile_set_name": "StackExchange" }
Q: PagedCollectionView not found in Silverlight 4 (again? yes) I know this will sound quite redundant, but sadly, no answer I have found to this problem online helped me. I am running Visual Studio 2010, and using the Silverlight 4 SDK (April 2011 version) for my project. (set in the properties, I double-checked) I did add "using System.Windows.Data;" at the beginning of my .cs file. Yet, the compiler still gives me "not found" errors concerning my calls to PagedCollectionView. When I type "System.Windows.Data.", the completion gives me plenty of suggestions, but no "PagedCollectionView"... the first suggestion I get starting with P is "PropertyGroupDescription". Has this useful tool just been erased out of the surface of the Earth? Thanks A: You need to add a reference to assembly System.Windows.Data for PagedCollectionView. The namespace System.Windows.Data is used in multiple assemblies for example System.Windows that contains PropertyGroupDescription
{ "pile_set_name": "StackExchange" }
Q: Easy Bootloader for USB Thumb Drives Are there any bootloaders designed for usb drives that make it easy to boot multiple distributions and utilities. I've installed sysrescuecd, supergrub, ultimate boot cd and other various linux distros on my usb drive. The lame thing is all their installation instructions make it the only thing that boots from your drive, and usb drives can store alot more than one utility. So I was wondering if anybody has made and easy application to setup a multiboot environment on a usb drive. Thanks A: I like using grub for my multiboot USB devices. grub4dos was not reliable enough in my tests. Isolinux/syslinux work fine but aren't as flexible as grub. It's pretty simple to extend the menu.lst/grub.cfg either statically as well as on-demand (thanks to tab completion in the grub shell :)). grml2usb of grml.org should give you an idea how to get a working multiboot USB setup. Tip: grub2 brings a nice feature known as 'loopback'. Using the loopback module/option it's possible to directly boot an (iso9660) ISO without having to manually extract kernel/initrd/.... from it. The following snippet is a configuration example for the grml Linux Live system: menuentry "grml-rescue system - ISO = grml-small_2009.05.iso" { loopback loop (hd0,1)/grml/grml-small_2009.05.iso linux (loop)/boot/grmlsmall/linux26 findiso=/grml/grml-small_2009.05.iso boot=live quiet vga=791 noeject noprompt initrd (loop)/boot/grmlsmall/initrd.gz }
{ "pile_set_name": "StackExchange" }
Q: Search all tables in all databases on server for a string Edit: This question was flagged as a duplicate, but it is not. The other answers on SO show how to search all tables in a single database, I need to search all tables in EVERY database on a given server. I need to search all tables for all databases on a server for a search string. I've got email address littered throughout tables that are going to have a change of domain and I need to prepare a report that shows where these email addresses are located. I am not going to be able to add a stored procedure to all the databases so I need a query to do this that's doesn't involve exec-ing a sp repeatedly. I pulled this code off the net and was using it to search all tables but I haven't been able to figure out how to run it on all databases. drop table #Results CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630)) SET NOCOUNT ON DECLARE @SearchStr nvarchar(100), @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110) SET @SearchStr = '@domaintobereplaced.com' SET @TableName = '' SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''') WHILE @TableName IS NOT NULL BEGIN SET @ColumnName = '' SET @TableName = ( SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName AND OBJECTPROPERTY( OBJECT_ID( QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) ), 'IsMSShipped' ) = 0 ) WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL) BEGIN SET @ColumnName = ( SELECT MIN(QUOTENAME(COLUMN_NAME)) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2) AND TABLE_NAME = PARSENAME(@TableName, 1) AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar') AND QUOTENAME(COLUMN_NAME) > @ColumnName ) IF @ColumnName IS NOT NULL BEGIN INSERT INTO #Results EXEC ( 'SELECT top 10 ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) FROM ' + @TableName + ' (NOLOCK) ' + ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2 ) END END END SELECT ColumnName, ColumnValue FROM #Results A: This question is a bit old at this point and most of the answers seem to miss the mark in terms of searching ALL servers and ALL databases on each server. Turned out my manager was just trying to give me an impossible and time consuming task aka busy work to stall me because our team was getting disbanded in a re-org and we were all being sent to different parts in the company. So, for the sake of writing a comprehensive answer I will say my approach now would be to create a console application that accepts a comma separated list of server names. It would loop through all the server names and connect to them one by one. Once in a server I would query for and loop through all the user created databases and run the search all tables query on each one. If results were found I would write them to a file stored in a directory with a [ServerName]_[DatabaseName]_Results title and then use the outputted list of files to review and develop and action plan for further querying/remediation. It doesn't appear from the answers above that there is a way to do this in SQL Server.
{ "pile_set_name": "StackExchange" }
Q: The number of linearly independent solution of the homogeneous system of linear equations $AX=0$ I came across the following multiple choice question: The number of linearly independent solution of the homogeneous system of linear equations $AX=0$, where $X$ consists of $n$ unknowns and $A$ consists of $m$ linearly independent rows is $(A)$ $m-n$ $\space$$(B)$ $m$ $\space$$(C)$ $n-m$ $\space$$(D)$ none of these I think the answer will be $(D)$ because: When $m=n$, in this case it would mean a square matrix with all linearly independent rows, which implies unique solution. When $m<n$, it would mean that the rank of the matrix is less than number of unknowns in the system, which would mean infinite solutions and these solutions must be linearly dependent (Am I going right?). When $m>n$, there will be no solution (I am not sure about this one) I think there is something wrong about my answer because I remember something like: number of linearly independent solutions = number of unknowns - rank, from my Linear Algebra class. But I am not sure how to relate to it here.. Thanks.. A: When $m=n$, we get unique solution that is trivial and hence linearly dependent. So, we get $0$ linearly independent solution (Here, $n-m=0$). When $m<n$, we also get non-trivial solution along with the trivial solution. We discard the trivial solution because we want only linearly independent solutions. Since we have $m$ linearly independent rows, the rank of $m \times n$ matrix is $m$. Hence $n-m$ linearly independent solutions The number of linearly independent rows is equal to number of linearly independent columns. Thus, number of linearly independent rows cannot exceed the number of columns. So, $m>n$ is an impossible case. The correct option is $(C)$ $n-m$.
{ "pile_set_name": "StackExchange" }
Q: Displaying only one record from json object , using jquery each Below is my code to display some notifications from json object. $.each(valid_result, function(key, element){ jQuery("#notifications_list").html('<a href="#"><i class="fa fa-users text-aqua"></i>'+element.notification+'</a>'; console.log(key+' : '+element.notification); }); The above list will display here <ul class="menu"> <li id="notifications_list"></li> </ul> But it is displaying only one record even though I have more records. Please suggest me where I am doing wrong. Any help would be greatly appreciated. A: You are overwriting results. Please use append() method instead of html(). jQuery.each(valid_result, function(key, element){ jQuery("#notifications_list").append('<a href="#"><i class="fa fa-users text-aqua"></i>'+element.notification+'</a>'); console.log(key+' : '+element.notification); }); If there are many elements in Your JSON object, then better approach is to append only once like so: var list = ''; jQuery.each(valid_result, function(key, element){ list += '<a href="#"><i class="fa fa-users text-aqua"></i>'+element.notification+'</a>'; }); jQuery("#notifications_list").html(list);
{ "pile_set_name": "StackExchange" }
Q: Firebase Pagination - Swift & iOS. When should it be used? I have a database that holds Posts. At a future point, my database may hold a very large number of Posts. I am confused as to what to do, as I cannot decide between the few options that I've thought of so far: 1) Load all Posts at once and store them into an Posts[] array, and just show all posts on the TableView that displays them. 2) Load 10 Posts at once and display those 10 at a time, then implement a function that allows the user to scroll and to load 10 more at a time. These 10 values that are loaded will then be added to the TableView. Now, option #1 seems simple and attractive, as it is what I currently have set up. However, I am not sure if it would be problematic or not to constantly load hundreds of posts every time a user opens the page that displays Posts. Option #2 seems complex, as I have no idea how to only load 10 Posts at once using Firebase. I am using a .childAdded observation to gather the data, and that usually loads all of the Posts. An alternative idea I had that may or may not be useless is loading all Posts into the Posts[] array but only displaying 10 at a time. This option is attractive because users won't have to load every single post every time they view the TableView that contains the posts. I am also hesitant to take this option because I would have to alter my data structure quite a lot. The current set up is: root/posts/post-id/post-info In which the post-info node holds information relevant to the post, and does not contain an index, which I have a feeling that option #2 would require. I'm quite stuck here. What's the best action to take in a situation like this? A: I was having the same problem creating a "forum" like app. There were a lot of threads and loading them all at once was not the right approach. If I were you I would stick to method 2: Load X number of posts, when TableView is scrolled to the bottom (or almost to the bottom) load additional posts and display them. Here is a quick example: You need a variable which will hold information on how much posts should be displayed: var numberOfPosts: Int = 20 Query your posts using queryLimited: reference.child("child").child("child").queryLimited(toLast: UInt(numberOfPosts)) This will return last X posts. You should also order it by some key to make sure you really have latest posts in the right order: reference.child("child").child("child").queryOrdered(byChild:"timestamp").queryLimited(toLast: UInt(numberOfPosts)) So the idea is, first time it will load 20 posts. The next time it should load 40, etc. That is why we need to implement something to recognise that all the posts were displayed and we need to load new ones. I am doing that with scrollView function - each time I am almost reaching the bottom, additional posts load. Implement scrollView didScroll: func scrollViewDidScroll(_ scrollView: UIScrollView) { if (scrollView.contentOffset.y + 100) >= (scrollView.contentSize.height - scrollView.frame.size.height) { // You have reeached bottom (well not really, but you have reached 100px less) // Increase post limit and read posts numberOfPosts += 20 readPosts() } } If you have UITableViewDelegate in the same class, function should be working by itself since TableView uses scrollView delegate. So this should be enough to get you going. I don't have the actual code right here so can't really paste it to help you. By the way, I am using .value and not .childAdded but you should be able to implement something like this anyway.
{ "pile_set_name": "StackExchange" }
Q: Enable i2c on Ubuntu Mate Raspberry Pi 3 I am having trouble utilizing the i2c bus on my raspberry pi. I am attempting to use it through Adafruits python module for their Servo driver board. When I run a method using the i2c I get: IOError: [Errno 2] No such file or directory: '/dev/i2c-1' When I execute i2cdetect -l I get nothing. When I execute i2cdetect 1 I get: Error: Could not open file /dev/i2c-1' or/dev/i2c/1': No such file or directory (The same happens with 0) I have tried issuing the command sudo modprobe --first-time i2c-dev To which I receive: modprobe: ERROR: could not insert 'i2c_dev': Module already in kernel The results of journalctl | grep modules are in the following image: A: Add the following line to /boot/config.txt dtparam=i2c_arm=on Add the following line to /etc/modules i2c-dev Reboot
{ "pile_set_name": "StackExchange" }
Q: Javascript validation for DD/MM/YY I need to check for this in javascript. So i need to pass in something like this var validdate = ^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$; This is throwing a "expected expression" error in VS. Whats wrong with that expression? Thanks for helping guys! A: You're getting an error, because in JS a RegExp literal starts and ends with a slash (/) var validdate = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[.\/-]([0]?[1-9]|[1][0-2])[.\/-]([0-9]{4}|[0-9]{2})$/;
{ "pile_set_name": "StackExchange" }
Q: What does `${1#*=}` mean in Bash? I found an awesome answer on StackOverflow which explains how to pass an associative array to a function. Would someone be able to help me figuring out what the syntax of ${1#*=} in the code below specifies? (Borrowed from that answer by jaypal singh): #!/bin/bash declare -A weapons=( ['Straight Sword']=75 ['Tainted Dagger']=54 ['Imperial Sword']=90 ['Edged Shuriken']=25 ) function print_array { eval "declare -A arg_array="${1#*=} for i in "${!arg_array[@]}"; do printf "%s\t%s\n" "$i ==> ${arg_array[$i]}" done } print_array "$(declare -p weapons)" Here's my guess so far (correct me if I'm wrong on any of these): - 1 means the first parameter passed to the function ($1 or ${1}) - # means the index of $1, which, since $1 is an associative array, makes # the keys of $1 - * means the values of of the # keys in associate array $1 That leaves the =. What does that signify? Is that like a way to show that you want # and * to mean the keys and values of the associate array? A: The snippet ${1#*=} has nothing to do with associative arrays. (Bash's syntax is super consistent, and not at all confusing)* This is a pattern match on the value of the first argument (${1}) of your function or script. Its syntax is ${variable#glob} where variable is any bash variable glob is any glob pattern (subject to pathname expansion) to match against) It deletes the shortest match, starting at the beginning of the line. There is also ## which deletes the longest match starting from the beginning of the variable, %, which deletes the shortest match starting from the end, and %%, which deletes the longest match starting from the end. So, for example, the following code: myVar="abc=llamas&disclaimer=true" echo ${myVar#*=} will print abc= to the screen. On the other hand, myVar="abc=llamas&disclaimer=true" echo ${myVar##*=} will print abc=llamas&disclaimer=, and myVar="foobar is bad" echo ${myVar%%b*" will print bar is bad * This is fully explained in the bash man page; just search for the string ${parameter#word} to find it A: It deletes the string matched (shortest match from start) by pattern *= in the string evaluated by $1. $1 is the first positional parameter passed to the shell. The general format can be written as ${var#patt} too, where patt is matched (shortest match from start) in $var and deleted. Example: var="first=middle=last" echo "${var#*=}" Output: middle=last If ## is used instead of # i.e ${var##pat}, then the pat is matched for the longest match (from start). Example: var="first=middle=last" echo "${var##*=}" Output: last From Bash Manual: ${parameter#word} ${parameter##word} The word is expanded to produce a pattern just as in filename expansion (see Filename Expansion). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ‘#’ case) or the longest matching pattern (the ‘##’ case) deleted. If parameter is ‘@’ or ‘’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.
{ "pile_set_name": "StackExchange" }
Q: Displaying different NSManagedObject entities in the same NSOutlineView Basically I have three different Core Data entities (A, B, C) and A contains a set of Bs and B contains a set of Cs. These three entities are, however, quite different from each other and they don't have common methods to access each other's children or the values to be displayed in the view. I'm trying to display these three enties in an NSOutlineView. There's propably other solutions too but I came up with two different ones: Implementing NSOutlineViewDataSource protocol and handling each of the entities differently. Consolidate the classes with categories and add common (transient) methods/properties for the NSOutlineView to use. These methods/properties get their actual values from the model entities' properties. I chose the second option and added getters for the children and the display value. This way, however, the Key-Value Observing does not work anymore and changes in the model are not reflected to the view. I understand why, but I'm not sure how to solve this the right way. I was thinking of some way to be notified of the actual model value changes and forward them to the view. Is there any easy way to forward those notifications or should I consider some other alternative? In short, I need to display different kinds of entities in an NSOutlineView and I don't want to mess the model. A: After some trial and error, I found out that creating a custom data source is really that simple and decided to go with the first choice. Also, with drag & drop support this feels much more natural way. The only issue was with outlineView:setObjectValue:forTableColumn:byItem: for which one needs to specify column identifier references. I feel that undirect dependencies are always something one should avoid, but this is a small matter in comparison to making this work nicely.
{ "pile_set_name": "StackExchange" }
Q: Spectral norm and maximal inner product of column vectors Let $A \in \mathbb{R}^{m \times n}$ be a matrix with columns $\{ a_k\}$ such that \begin{align*} \max_{j \neq k} \left| \langle a_j, a_k \rangle\right| \leq \epsilon, \;\;\| a_k \| = 1 \;\forall k \end{align*} Can we bound $\| A\|_2$ in terms of $\epsilon$ and the dimensions of the matrix? Clearly, if $\epsilon = 0$, we have orthonormal columns and thus $\| A\|_2 = 1$. I can see that if we relax the orthogonality constraint a little bit, the maximum singular value would grow with $\epsilon$, but I was unable to obtain a tight upper bound. A: Consider $||Ax||^{2}_{2}$. \begin{equation} ||Ax||^{2}_{2} = \langle Ax \,, Ax \rangle = x^T A^T Ax \end{equation} $A^TA$ is symmetric and positive semi-definite. The eigenvalues of $A^TA$ are real and positive. The eigenvectors of $A^TA$ are orthogonal. Let $\{\beta_i\}_{i=1}^{n}$ denote the orthonormal eigenvectors of $A^TA$. The corresponding eigenvalues will be denoted by $\lambda =\{\lambda_i\}_{i=1}^{n}$. Any vector $x \in R^n$ can be expanded in the basis $\{\beta_i\}_{i=1}^{n}$. With this,$||Ax||^{2}_{2}$ can be written as \begin{align*} ||Ax||^{2}_{2} = x^T A^T Ax &=\left(\sum_{i} c_{i} \beta_i^{T}\right) A^T A\left(\sum_{j} c_{j} \beta_{j}\right)\\ & =\left(\sum_{i} c_{i} \beta_i^{T}\right) \left(\sum_{j} c_{j} A^T A\beta_{j}\right) =\left(\sum_{i} c_{i} \beta_i^{T}\right) \left(\sum_{j} c_{j} \lambda_j \beta_{j}\right)\\ &= \sum_{i} \sum_{j} c_{i} c_{j}\lambda_{j} \beta_{i}^T \beta_{j} = \sum_{i} \sum_{j} c_{i} c_{j}\lambda_{j} \delta_{i,j} \\ &= \sum_{i} c_{i}^{2}\lambda_{i} \end{align*} To bound $||Ax||^{2}_{2}$, we note that \begin{equation} \min(\lambda) \sum_{i} c_{i}^{2} \le\sum_{i} c_{i}^{2}\lambda_{i} \le \max(\lambda) \sum_{i} c_{i}^{2} \Longrightarrow \min(\lambda) ||x||^{2} \le ||Ax||^{2}_{2} \le \max(\lambda) ||x||_{2}^{2} \end{equation} It remains to find the minimum and maximum eigenvalues of $A^TA$ via Gre$\check{s}$gorin theorem. Let $A^{i}$ denote the $i$ column of $A$. With the assumption that $A$ has unit-norm columns in consideration, Tthe $(i,j)$ the entry of $A^TA$ is given by \begin{equation} (A^TA)_{(i,j)} = \begin{cases} 1 \quad &i=j \\ \langle A^{i}\,,A^{j}\rangle \quad &i\neq j \end{cases} \end{equation} From Gre$\check{s}$gorin theorem, the eigenvalues of $A^TA$ with entries $(A^TA)_{(i,j)}$, $1\le i,j\le n$, lie in the union of disks $d_i = d_i(c_i,r_i)$, $1\le i\le n$, centered at $1$ with radius $$ r_{i} = \sum_{j\neq i} |A^TA|_{(i,j)} = \sum_{j\neq i} |\langle A^{i}\,,A^{j}\rangle| \le (n-1)\epsilon $$ where the last bound follows from the coherence of $A$ i.e $\mu = \max_{1\le i,j \le n} |\langle A^{i}\,,A^{j}\rangle |$. With this, $\min(\lambda)\ge 1-(n-1)\epsilon$ and $\max(\lambda)\le 1+(n-1)\epsilon$. Using these bounds \begin{equation} \left(1-(n-1)\epsilon\right) ||x||^{2} \le ||Ax||^{2}_{2} \le \left(1+(n-1)\epsilon\right) ||x||_{2}^{2} \end{equation}
{ "pile_set_name": "StackExchange" }
Q: Time of the year A famous Dutch writer once stated that the majority is wrong by definition. Although the point of view might be a bit too drastic, there is some truth in it. On a website like AU, one could expect a hard time, looking from that angle, since practically everything around here is "majority driven". The contrary turns out to be the case. I can't say I always agree with the majority, but the funny thing is that for some reason, it is always acceptable to disagree. Partially, it could be the result of the fact that we are a minority to begin with. I strongly believe however that the way "we" are moderated is the most important reason that things work here like they do, in a good balance of rules and being allowed to be human. Nothing wrong to mention at least once a year the effort of our moderators, and the integrity in what they do. Thanks people, hats off! A: Hear hear. I second that motion. Season's greetings. The force be with you. ...or whatever floats your boat to describe a general kinesthetic and appreciative form of approval. :-) Thank you wonderful people! :-D
{ "pile_set_name": "StackExchange" }
Q: Expression for $E[|X - E[X]|^3]$ I've read in some lecture notes that, for $X$ being a Bernoulli(p) random variable it follows that $$ E[|X - E[X]|^3] = p (1-p)^3 + (1-p)p^3. $$ However, I don't see how to derive this result from the left side. If it wasn't for the modulus, I could simply expand the expression and then use linearity of expectation. But how do I deal with the modulus here? A: $E[X] = p$, so $E[|X - E[X]|^3] = E[|X - p|^3]$. $X = 1$ with probability $p$ and $X = 0$ with probability $1 - p$, so you get that $$ E[|X - E[X]|^3] = E[|X - p|^3] = p\cdot|1 - p|^3 + (1 - p) \cdot |0 - p|^3 = p(1 - p)^3 + (1 - p)p^3. $$
{ "pile_set_name": "StackExchange" }
Q: Can a contract be renewed without consent? I am a contracted software developer in the United States. My contract will expire in about 5 months. Are they able to renew it without my consent? I ask this because I am not familiar with the contracting process. A: Does the contract have a clause which says anything about automatic contract renewal? When it doesn't, the contract is over when it is expired and you both need to explicitly agree to a new contract. Now what if the contract ends, you both act as if it hadn't (you keep working, they keep paying) and then get into a dispute after a while? I (as a legal layman) could imagine that a court of law might rule that you both implicitly agreed to a contract extension through your behavior. But that depends on a lot of factors (ask a lawyer for details). Working with no contract is an ugly situation for everyone involved, so you should better sort out your working arrangement before the contract ends.
{ "pile_set_name": "StackExchange" }
Q: Problemas con Godot Hola tengo un problema instale Godot 3.1.1 de 32Bits y me sale el siguiente error your video card driver does not support any og the supported OpenGL version. Place update your drivers or if you have a very old or integrated GPU upgrade it. Tengo una tarjeta integrada intel Q45/Q43 Express Chipset, el tipo es una intel 4 Series Express Chipset Family. tengo esta tarjeta integrada ya que estoy ejecutandolo desde una Netbook A: actualiza el controlador de la tarjeta, no mencionas el sistema operativo pero por lo que veo en la página de descargas de Intel (https://downloadcenter.intel.com/es/download/21831/controlador-de-gr-ficos-Intel-para-Windows-XP-64-bit-exe-?product=81511) la tarjeta de video es un poco veterana y lo más seguro es que tenga incompatibilidades. Trata de ejecutar Godot con una versión anterior de OpenGL utilizando el parámetro --video-driver desde una consola: Godot_v3.1-stable_win64.exe --video-driver GLES2 Si quieres ver todos los parámetros ejecuta: Godot_v3.1-stable_win64.exe --help
{ "pile_set_name": "StackExchange" }
Q: Spring REST @ResponseStatus with Custom exception class does not change the return Status code I have a exception class like follows @ResponseStatus(value=HttpStatus.UNPROCESSABLE_ENTITY, reason="Unprocessable Entity") // 422 public class UnprocessableEntityException extends RuntimeException { } Now the status is not returned as 422 unless I write a specific handler in the Controller class like : @ExceptionHandler(UnprocessableEntityException.class) @ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY) public String handleException(Exception ex) { ... } As I understand I should not need @ExceptionHandler in first place, not sure what am I missing. A: Throwing a @ResponseStatus annotated exception from a controller method should be enough for the framework to write the HTTP status code - no @ExceptionHandler necessary. The following will write a 422 Status on hitting the webapp root as expected: @Controller public class ExceptionController { @RequestMapping("/") public void action() { throw new ActionException(); } @ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY, reason = "nope") public static class ActionException extends RuntimeException {} } This works courtesy of the ResponseStatusExceptionResolver which is created by Spring MVC by default - if it's not working for you, my guess is that this default exception resolver has been removed (by e.g. overriding WebMvcConfigurationSupport.configureHandlerExceptionResolvers or otherwise configuring your context's HandlerExceptionResolvers so that the ResponseStatusExceptionResolver is trumped.)
{ "pile_set_name": "StackExchange" }
Q: How to create idendical variables in MATLAB from an array of variable names? I have the following code in Matlab: a = zeros(23,1) b = zeros(23,1) c = zeros(23,1) How can I write it more compactly? I was looking for a solution that is something like this: str = {'a','b','c'} for i = str{i} i = zeros(23,1) end But I can't find a way to do it properly without an error message. Can someone help please? A: Here is a compact way using deal : [a, b, c] = deal(zeros(23,1)); A: What you're tempted to do is very bad practise, but can be done like this str = {'a','b','c'}; for ii = 1:numel(str) eval( [str{ii} ' = zeros(23,1)'] ); end Why is this bad practise? Your code legibility has just gone way down, you can't clearly see where variables are declared. eval should be avoided You could use deal to make things a bit nicer, but this doesn't use the array of variable names [a, b, c] = deal( zeros(23, 1) ); Even better, it's likely you can optimise your code by using a matrix or table instead of separate 1D arrays. The table option means you can still use your variable name array, but you're not using eval for anything! % Matrix M = zeros( 23, 3 ); % Index each column as a/b/c using M(:,1) etc % Table, index using T.a, T.b, T.c T = array2table( zeros(23,3), 'VariableNames', {'a','b','c'} ); A: You can also use a struct if the variable name is important: str = {'a','b','c'}; data = struct for ii = 1:numel(str) data.(str{ii}) = zeros(23,1); end The struct is more efficient than the table. You can now address data.a, data.b, etc. But if the name is not useful, it's best to put your data into a cell array: N = 3; data = cell(N,1); for ii = 1:N data{ii} = zeros(23,1); end or simply: data = cell(3,1); [data{:}] = deal(zeros(23,1)); Now you address your arrays as data{1}, data{2}, etc., and they're always easy to address in loops.
{ "pile_set_name": "StackExchange" }
Q: Search for venues annotated by brand I'm specifically looking to find venues which a NY Times has annotated data for. The goal is to call /venues/VENUE_ID/annotations and get links to articles referring to that venue. https://developer.foursquare.com/docs/venues/search.html The above api documentation is clear that providerId and linkedId must be used in conjunction with one another but linkedId seems proprietary and secret to the annotator (the NY Times). Is there any way to just search by providerId? A: There's currently no way to filter search by providerId. The linkedId for a provider is the internal ID they use for referencing the venue. In the case of the NYTs, they put this ID in the URL of their Restaurant Details page (e.g. http://www.nytimes.com/restaurants/1247467962332/abc-kitchen/details.html) /venues/link returns all annotations for a venueId.
{ "pile_set_name": "StackExchange" }
Q: Where to generate arrays in Ember.js UPDATE: I added {{else}} to the nested each and it really seems the template does not iterate over individual spots. It was foolish to think that the log helper would not fire up in such situations. Ill try to dig deeper. UPDATE2 Thanks for the first answer. Probably not counting from 0 on array indexes makes forEach function to behave funny. 1-st level of each works just fine, 2nd not at all. I will try to change my script so I store X Y coordinates differently. Even though this was convienient. So I generated a simple array in my IndexController grid: function(){ //Lets generate a 2-dimensional grid var data = []; var limits = this.get('limits'); // console.log(limits); for(var y = limits.min.y; y <= limits.max.y; y++){ data[y] = new Array(this.get('numberOfColumns')); for(var x = limits.min.x; x <= limits.max.x; x++){ data[y][x] = 0; } } console.log(data); // this.get('spots').forEach(function(spot){ // console.log('Y '+spot._data.y+' X '+spot._data.x); // data[spot._data.y][spot._data.x] = spot._data; // console.log(spot); // }); return data; }.property('limits','numberOfColumns') Problem is, when I try to iterate over this array in my template I get a lot of undefined values and the html content does not render at all. {{#each gridrow in grid}} <div class="gridRow {{unbound is-even _view.contentIndex}}"> {{#each spot in gridrow}} {{!-- {{log spot}} --}} {{!-- {{spot-unit class='inline-block'}} --}} {{log "test"}} <div class="spot"></div> {{/each}} </div> {{/each}} "Test" gets logged 800 times, although it should get logged about 50 times. No div.spot gets rendered. I guess its because of some ember meta data which get appended to the array. I went through quite a lot of API and guides and couldnt find where should I generate such arrays. Should it be in the form of Fixtures? That doesnt seem right. Should it be simple model (therefore no ember data)? Then I would deal with multiple models situation which I would like to avoid if possible. If I generated this array on the server side with data already merged to it, things would be much simpler in the end, but before I go this way, I would really like to know where to properly generate such things on client side. More info on what I am trying to achieve: I need to generate simple grid on client side consisting of empty tiles which I afterwards fill out with server data. Some of them will remain empty, thats why I cant count on server data alone, some tiles would be missing and grid would be broken. A: You're setting array items starting from limits.min.y and limits.min.x indices, which, as I guess, can be greater than 0. So, let's look at your piece of code in this case: var data = []; var limits = this.get('limits'); for(var y = limits.min.y; y <= limits.max.y; y++){ data[y] = new Array(this.get('numberOfColumns')); for(var x = limits.min.x; x <= limits.max.x; x++){ data[y][x] = 0; } } Here, if limits.min.y > 0, data[i] for any i < limits.min.y will equal to undefined. Same thing for limits.min.x. So, better way is to rewrite as follows: var data = []; var limits = this.get('limits'); for(var y = 0; y <= limits.max.y - limits.min.y; y++){ data[y] = new Array(this.get('numberOfColumns')); for(var x = 0; x <= limits.max.x - limits.min.y; x++){ data[y][x] = 0; } }
{ "pile_set_name": "StackExchange" }
Q: Adding Done Button to Only Number Pad Keyboard on iPhone I am successfully adding a done button to my number pad with this handy code below. But I have an email button that launches the MFMailComposeViewController. How would I make sure the done button does not appear on the email keyboard? // // UIViewController+NumPadReturn.m // iGenerateRandomNumbers // // Created by on 12/4/10. // Copyright 2010 __MyCompanyName__. All rights reserved. // #import "UIViewController+NumPadReturn.h" @implementation UIViewController (NumPadReturn) -(void) viewDidLoad{ // add observer for the respective notifications (depending on the os version) if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil]; } else { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; } } - (void)keyboardWillShow:(NSNotification *)note { // if clause is just an additional precaution, you could also dismiss it if ([[[UIDevice currentDevice] systemVersion] floatValue] < 3.2) { [self addButtonToKeyboard]; } } - (void)keyboardDidShow:(NSNotification *)note { // if clause is just an additional precaution, you could also dismiss it if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) { [self addButtonToKeyboard]; } } - (void)addButtonToKeyboard { // create custom button UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom]; doneButton.frame = CGRectMake(0, 163, 106, 53); doneButton.adjustsImageWhenHighlighted = NO; if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.0) { [doneButton setImage:[UIImage imageNamed:@"DoneUp3.png"] forState:UIControlStateNormal]; [doneButton setImage:[UIImage imageNamed:@"DoneDown3.png"] forState:UIControlStateHighlighted]; } else { [doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal]; [doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted]; } [doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside]; // locate keyboard view UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1]; UIView* keyboard; for(int i=0; i<[tempWindow.subviews count]; i++) { keyboard = [tempWindow.subviews objectAtIndex:i]; // keyboard found, add the button if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) { if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES) [keyboard addSubview:doneButton]; } else { if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES) [keyboard addSubview:doneButton]; } } } - (void)doneButton:(id)sender { NSLog(@"doneButton"); [self.view endEditing:TRUE]; } @end I am trying to extend the UIViewController so it automatically does this when I import this subclass, so a boolean flag in my application probably won't work. A: For iOS 3.2+, you should not use this hack anymore, anyway. Instead, assign your custom view to your control's inputAccessoryView property.
{ "pile_set_name": "StackExchange" }
Q: How to print multiple strings(with spaces) using gets() in C? In my C program, I call gets() twice to get input from the user. The first time the user is asked to enter the fullname and the second time the user is asked to enter a friends fullname. However, on the second call of gets() , it doesn't wait for the input from the user it just skips over it and finishes the program. Here is my complete code: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> int main() { char fullname[30]; char friendsname[30]; char sentence[70]= ""; char gender; printf("Enter your full name: "); gets(fullname); printf("\n"); printf("%s , Please enter your gender(m/f)? : ", fullname); scanf("%c", &gender ); puts("\n"); if(gender =='m') { printf("Mr. %s , please enter your friends name:", fullname); gets(friendsname); puts("\n"); } else if(gender =='f') { printf("Mrs. %s , please enter your friends name:", fullname); gets(friendsname); puts("\n"); } strcat(sentence, "Hello Mr./Mrs. "); strcat(sentence, friendsname ); strcat(sentence, ", " ); strcat(sentence, fullname); strcat(sentence, " considered you as a friend. "); puts(sentence); return 0; } Here is a sample output: Enter your full name: Brad Pitt Brad Pitt , Please enter your gender(m/f)? : m Mr. Brad Pitt , please enter your friends name: Hello Mr./Mrs. , Brad Pitt considered you as a friend. Process returned 0 (0x0) execution time : 8.110 s Press any key to continue. The gets(friendsname); line is completely being skipped and the program continues on for some reason. Can anyone explain why this is happening ? A: NEVER NEVER NEVER NEVER use gets. It will introduce a point of failure/security hole in your code. It is no longer part of the standard library. Use fgets instead, just be aware that it will attempt to store the trailing newline to the target buffer if there's room. The reason the gets(friendsname) is being skipped is that you have a trailing newline in the input stream after the scanf call to read gender; gets sees that newline before any other input and returns immediately. One way around this is to have your scanf call consume the trailing newline without assigning it to anything: scanf(" %c%*c", &gender ); The * in the second conversion specifier tells scanf to read a single character and discard it. Also, the leading blank in the format string tells scanf to skip over any leading whitespace and to read the first non-whitespace character.
{ "pile_set_name": "StackExchange" }
Q: Issue cloning GitHub private repo onto remote server Note that this is the original article I've been following along with: http://www.markdotto.com/2011/11/02/how-to-deploy-sites-via-github/ To give you a bit of background: We have a private repo set-up under an organisation account. We have three developers (myself included) who have our own accounts with GitHub and have administrator rights to the private repo. While working on the project we clone the repo and then create a 'dev' branch. We each work from our own dev branch and push changes to the 'dev' branch on GitHub. We want to get this dev branch onto our remote server so we can test the combined code works before merging it into our master branch (which should be clean/always deployable). From here we're following the above article steps which is to connect to our server via SSH, go to the relevant directory where our website is hosted and run the following command... git clone [email protected]:ORGANISATION/REPO.git dev The first issue we had was our server returned the message... Cloning into dev... ssh: connect to host github.com port 22: Connection refused fatal: The remote end hung up unexpectedly ...where I would have it expected it to ask us for a password? So instead we tried the HTTP url... git clone https://[email protected]/ORGANISATION/REPO.git dev ...you'll notice the HTTP url uses my own USERNAME now when cloning. I enter my password and it displays Cloning into dev... but then it displays the following error... error: SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed while accessing https://[email protected]/StormCreative/MoneyRepublic.com.git/info/refs fatal: HTTP request failed ...I don't understand the error. So how do we clone this private repo onto our server? Any help appreciated! Kind regards, Mark A: The first issue happens because you don't have the local rsa key linked to your account on GitHub (and yes, you link the rsa key to your account, and the organisation is linked to your account as well). In the local machine (or remote server) where you are trying to clone the repository, you need to generate a rsa key: ssh-keygen -t rsa When you are generating the key, you chose a password and a place to store the id_rsa.pub file, that actually contains the key. On GitHub, you need to add this key, the exact content of id_rsa.pub, to your ssh keys on your account administration panel.
{ "pile_set_name": "StackExchange" }
Q: JFET stabilised wien bridge component ratios I find myself in need of a sine wave oscillator and have decided on the wien bridge. I have followed all the tutorials but have a few questions that do not seem to be answered elsewhere. Firstly, I understand the ratio between Rf and R3 determines the negative feedback loop gain set to 3, or just above, at a ratio of 2:1. But there are lots of combinations of resistances which would give that ratio, so what effect would say using a 1 OHM : 2 OHM resistance be compared to 10 OHM : 20 OHM? And the same question about the capacitor resistor combinations in the lead lag circuit. Second, how do the values of Rf and R3 get selected when there is a JFET paired with R2? I figured that to get a gain of 3 after the gate voltage comes up then I would add the Rds(on) of the JFET to R3 and count them as one, so then when the JFET is off, there would be no resistance through it and the gain would be higher than 3, allowing oscillations to start. Is this correct? Any particular ratio between the JFET Rds(on) and R3, does one dominate, equal or does not matter? Third, the negative peak detector which drives the gate of the JFET charges a capacitor, which has a resistor in parallel. What is that resistor R4 doing and how is its value determined? How is the capacitors value determined? Lastly, what determines the output voltage? Say, I need a 0.1 v output to feed a BJT amp, what values would I need to change and how would I calculate them? I figured the output would be determined by the maximum peak to peak printed on the datasheet, but how would I bring this down? Thanks for any replies A: Regarding the control loop Diode-C3-R4: This is not a peak detector because the parallele resistor R4 continuously discharges the capacitor which - in turn - is charged by the output amplitude (if it can open the diode at a certain level). This is necessary in order to allow amplitude control in BOTH directions. The opamp gain swings around the nominal value of "3". Hence, the output amplitude is NOT CONSTANT - it will exhibit a small amplitude modulation which is determined by the time constant C3-R4. This time constant should be at least ten times larger than the oscillation period. From this requirement you can select both values (C3 and R4). Regarding the ouput amplitude: An exact computation is not possible (due to the nonlinear Diode characteristics). However, a good estimat is possible if you know the nominal value (during steady-state oscillations) of the FET resistance and the corresponding gate voltage. This give you the mean voltage across C3 and - together with app. 0.5 across the diode - a reasonable guess for the corresponding output amplitude. EDIT (error correction): There is a logical error on your side. You wrote: .....when the JFET is off, there would be no resistance through it and the gain would be higher than 3, allowing oscillations to start..... No, when the JFET is off the RDS resistance is very large and the opamp works as a unity gain amplifier (full feedback). The correct description is as follows: At t=0 the ouput voltage (and the gate voltage) is zero and the FET is open - the RDS resistance is low (max current ID) and the gain larger than "3". Now - for rising amplitudes the gate voltage becomes more and more negative and the RDS resistance goes higher and provides more negative feedback (the gain is decreased until it reaches "3").
{ "pile_set_name": "StackExchange" }
Q: How can i change the Record separator for sed I know that i can chnage the RS =something in awk. Is there any way i can change the \n RS to something for muliline pattern in sed A: Short answer: no, you can't. Sed reads lines of text, not records with fields. Depending on the nature of your text, you could use tr to first change all \ns to an unused character and your desired (single-character) record separator to \n. Make the changes you want in sed, then use tr to change the separators back. You could also manipulate the hold space to let you work with multiple lines of text. This is described in, for example, sed & awk by Dougherty and Robbins. It's probably easier just to use awk, though.
{ "pile_set_name": "StackExchange" }
Q: AWS blocked mixed content when calling API I have a front end application in digitalOcean with domain name testDO. This domain has SSL certificate. So all request origin are from https://testDO.com. I have a backend server sitting in AWS created by deploying war file into beanstalk. It has the name testAWS.us-east-2.elasticbeanstalk.com When I call API directly from the url for example http://testAWS.us-west-2.elasticbeanstalk.com/myAPI/getName it works. When I call the same API from my front end I get blocked:mixed-content. Is this because its http and not https? what is the workaround? A: Yes this is because, your HTTPS site tries to access content through HTTP which is blocked by the browser. You need to either both HTTPS or proxy the request at frontend server and terminate SSL there and forward it to your API Server in Beanstalk. Note: Since the frontend and backend are in two different environments it will be preferred to use both HTTPS than the proxy approach for security.
{ "pile_set_name": "StackExchange" }
Q: exporting an SSRS report to Excel failure When trying to export an SSRS report to excel, I am getting a runtime error. I have looked at the logs and see the following: ERROR: Throwing Microsoft.ReportingServices.Diagnostics.Utilities.ReportServerStorageException: , An error occurred within the report server database. This may be due to a connection failure, timeout or low disk condition within the database.; The report displays fine in Report Manager, and has run successfully in the past. The report is only not very complex, and is approx 40 columns wide. When I run the query in SSMS I get 27,628 records, and it takes 3 seconds to run (again, im SSMS). The report runs fairly quickly in Report Manager also, and exporting the results to .scv format works as expected. If any additional information is needed to help with resolving this, please let me know and I will provide it. Thanks for you help in advance! Additionally, report has been set to not timeout. Report runs in VS2010 and exports to Excel as expected. A: Your connection might be timing out. Try changing the timeout length by: 1.Open the rsreportserver.config with Text Editior(e.g. Visual Studio, NotePad). By default, it is hosted in C:\Program Files\Microsoft SQL Server\MSRS10.MSSQLSERVER\Reporting Services\ReportServer 2.Change the value for 'DatabaseQueryTimeout'. Valid values range from 0 to 2147483647. A value of 0 specifies an unlimited wait time and therefore is not recommended. 3.Save the file, and then restart the Reporting Services to apply the changing. http://msdn.microsoft.com/en-us/library/ms157273.aspx
{ "pile_set_name": "StackExchange" }
Q: If $U$ is uniformly distributed on $S^{d-1} \subset \mathbb{R}^d$, what's the distribution of its orthogonal projection onto any vector? Let $U \in S^{d-1} \subset \mathbb{R}^d$ follow a uniform distribution on a sphere. Let $v \in \mathbb{R}^d.$ Then is the orthogonal projection $U^{T}v=\langle U,v \rangle$ uniformly distributed, and if yes/no, how do I go about proving it? This is motivated by this relevant question for uniform distributions on 2D spheres. If it's wrong, could you give a counterexample? If it's not uniformly distributed, how can we find the PDF of $U^{T}v=\langle U,v \rangle?$ A: Let $v$ be a unit vector. Since the orthogonal group acts transitively on the unit sphere, there exists a rotation matrix $R$ such that $Rv=e$, where $e=(1,0,\ldots,0)'$. Now let $Z=(Z_1,\ldots,Z_d)'$ be a vector of independent identically distributed $N(0,1)$ random variables. The distribution of $Z$ is clearly rotationally invariant, and the normalized vector $U=Z/\|Z\|$ is uniformly distributed over the unit sphere, as is $R'U$. (See, eg, the answer by Henricus V. to this MSE question, and comments, and this one, about this trick. It is a converse to Maxwell's theorem.) The quantity $\langle U, v\rangle=\langle U,Re\rangle=\langle R' U,e\rangle,$ so the distribution of $\langle U, v\rangle$ is the same as that of $\langle U, e\rangle$. So we may as well assume $v=e$ in working out the distribution of $T=\langle U,v\rangle$. With this notation, $T=\langle U,v\rangle=Z_1/\sqrt{\sum_{i=1}^d Z_i^2}$, and $T^2=Z_1^2/\sum_{i=1}^d T_i^2$. The quantities $Z_i^2$ are iid Gamma distributed: $Z_i^2\sim\Gamma(\frac 1 2,\frac 1 2)$ and $\sum_{i=2}^d Z_i^2\sim\Gamma(\frac{d-1}2,\frac 12)$ and hence $T^2$ has the $\operatorname{Beta}(\frac 1 2,\frac {d-1}2)$ distribution. If we write $W=T^2$, the density function of $W$ is proportional to $w^{-\frac{1}2} (1-w)^{\frac{d-1}2-1}$ for $0<w<1$, and the density of $T$ is proportional to $(1-t^2)^{(d-3)/2}$ for $-1<t<1$. Only if $d=3$ does the distribution of $T$ become uniform over its range.
{ "pile_set_name": "StackExchange" }
Q: Google App Engine Example of Uploading and Serving Arbitrary Files I'd like to use GAE to allow a few users to upload files and later retrieve them. Files will be relatively small (a few hundred KB), so just storing stuff as a blob should work. I haven't been able to find any examples of something like this. There are a few image uploading examples out there but I'd like to be able to store word documents, pdfs, tiffs, etc. Any ideas/pointers/links? Thanks! A: The same logic used for image uploads apply for other archive types. To make the file downloadable, you add a Content-Disposition header so the user is prompted to download it. A webapp simple example: class DownloadHandler(webapp.RequestHandler): def get(self, file_id): # Files is a model. f = Files.get_by_id(file_id) if not f: return self.error(404) # Set headers to prompt for download. headers = self.response.headers headers['Content-Type'] = f.content_type or 'application/octet-stream' headers['Content-Disposition'] = 'attachment; filename="%s"' % f.filename # Add the file contents to the response. self.response.out.write(f.contents) (untested code, but you get the idea :)
{ "pile_set_name": "StackExchange" }
Q: Virtual folder data for your Windows Phone app i am thinking to extend my app for Windows Phone (7) with new features like data tranfer to pc. My app can download mp3's in app's isolated storage, so i need a way for user to be able to move theese mp3's directly on his computer. The best scenario will be: When user connect his phone on computer, a folder (as usb disk) will apear with specific content inside (the mp3s)! Maybe this way is in readonly mode, i dont carem, but is possible? If not possible other suggestions? A: No This is not possible. App storage is kept separate from the file system you can access with the explorer. maybe the easiest way is to transfer data to the cloud somewhere and let users download the data from the clould instead of by connecting the phone to your pc.
{ "pile_set_name": "StackExchange" }
Q: Efficiently representing a dynamic transform hierarchy I'm looking for a way to represent a dynamic transform hierarchy (i.e. one where nodes can be inserted and removed arbitrarily) that's a bit more efficient than using a standard tree of pointers . I saw the answers to this question ( Efficient structure for representing a transform hierarchy ), but as far as I can determine the tree-as-array approach only works for static hierarchies or dynamic ones where nodes have a fixed number of children (both deal-breakers for me). I'm probably wrong about that but could anyone point out how? If I'm not wrong are there other alternatives that work for dynamic hierarchies? A: One quite efficient representation is an array of matrices combined with an array of parent indices. If you keep things sorted, and updates is just a loop over the array. See Practical Examples in Data Oriented Design by the BitSquid guys. You might not need to resort that much depending of your change patterns. A: Well.. judging from the discussion, I'd say if the changes are frequent, the tree model wins; if changes are infrequent, the array model wins (it's ok to rebuild the array if it's rare).. In a real-world case some hybrid might be the optimal, leaving most of the hierarchy static while other parts are dynamic. I didn't post this as an answer before though, as someone might have actual experience on the matter, instead of just pondering on it on an algorithmic level. In any case, I'd look into this only after it's found to be an issue.
{ "pile_set_name": "StackExchange" }
Q: Annotation based view mapping I am trying to get my head around annotation based mappings and I am having some trouble mapping requests directly to jsp. Do all request have to go through a controller? Is it possible to make it just go to a jsp without declaring a RequestMapping for GET? I am using a InternalResourceViewResolver. Below is my app-servlet.xml <context:annotation-config/> <context:component-scan base-package="com.pioneer.b2broe.web" /> <mvc:annotation-driven /> <mvc:view-controller path="/" view-name="home"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:viewClass="org.springframework.web.servlet.view.JstlView" p:suffix=".jsp" p:order="2"/> A: You can use the ParameterizableViewController, which redirects the request to the view set in the "viewName" attribute. <bean name="/helloworld.htm" class="org.springframework.web.servlet.mvc.ParameterizableViewController"> <property name="viewName" value="helloworld"/> </bean>
{ "pile_set_name": "StackExchange" }
Q: d3Service/d3-ng2-service TypeScript TS2346 Supplied parameters do not match signature I have a SVG that contains rect elements and text elements. index.html <svg id="timeline" width="300" height="100"> <g transform="translate(10,10)" class="container" width="280" height="96"> <rect x="10" y="30" width="48" cy="10" r="30" height="60" class="timelineSeries_0" id="day1"></rect> <rect x="58" y="30" width="48" cy="10" r="30" height="60" class="timelineSeries_0" id="day2"></rect> <rect x="106" y="30" width="48" cy="10" r="30" height="60" class="timelineSeries_0" id="day3"></rect> <rect x="154" y="30" width="48" cy="10" r="30" height="60" class="timelineSeries_0" id="day4"></rect> <text class="textnumbers" id="day1" x="22.8" y="50">1</text> <text class="textnumbers" id="day2" x="70.8" y="50">1</text> <text class="textnumbers" id="day3" x="118.8" y="50">1</text> <text class="textnumbers" id="day4" x="116.8" y="50">1</text> </g> </svg> Using D3Service from d3-ng2-service, I am doing the following: let day = 1; let rect_id = "rect#day" + day; let ele = D3.select<SVGRectElement>(rect_id).node(); let label_id = rect_id.replace("rect", ".textnumbers"); let numberEle = D3.select<TextElement>(label_id); I'm getting a TS2346 error with the select: error TS2346: Supplied parameters do not match any signature of call target. The index.d.ts for D3Service is : https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/d3-selection/index.d.ts#L155 On line 162 it says: select<DescElement extends BaseType>(selector: string): Selection<DescElement, Datum, PElement, PDatum>; I'm presuming I'm getting the wrong element types there from the index.d.ts and I should be using something else other than SVGRectElement and TextElement, but I can't figure out what. The Angular2 component works fine in practice. How do I read the index.d.ts file to find the correct element types? Thanks! A: As you can see in the select() method signature: select<DescElement extends BaseType>(selector: string): Selection<DescElement, Datum, PElement, PDatum>; The select method returns a Selection element, so the cast to SVRectElement won't be possible. Moreover, the cast (if necessary) should go in front of the method called like this: let ele = <SVGRectElement> D3.select(rect_id).node(); In this case, though, the cast it is not necessary, so the code should be: let rectEle = self.d3.select(rectId);
{ "pile_set_name": "StackExchange" }
Q: Blog Newsletter Delivery Day Why is the newsletter sent in the middle of the week on Tuesday? Can we change this to some other day? A: Why is the newsletter sent in the middle of the week on Tuesday? According to this answer, * we searched Google for "best day of week to send email newsletter" and Tuesday seemed popular Can we change this to some other day? I don't think we can: I think the algorithm is hard-coded and not user-configurable nor site-configurable. There was at the time a request to implement an option like that, but it wasn't a popular request (attracting only 5 up-votes and 5 down-votes), and so that request now has the status-declined tag. FWIW that was apparently somewhat of a relief to the person who might have had to help implement that feature, who commented, phew, less work for me :) I think that in general it's difficult to persuade Stack Exchange to change the current software. One example is this feature request which has 30 up-votes but which so far as we know is not scheduled for implementation. There are currently 19000 feature requests of which 2000 have been completed and 1000 declined.
{ "pile_set_name": "StackExchange" }
Q: Is it possible for two independent variables to be correlated, by chance? I'm reading Introduction to Probability, 2nd Edition by Tsitsiklis and Bertsekas. On page 218, they write "Thus, if X and Y are independent, they are also uncorrelated." Is it possible that there could be two variables where the value of one tends to increase as the value of the other increases, even if they come from totally unrelated and disconnected processes? A: The question is confusing, and so maybe misinterpreted by some commenters and answerers. In your citation, there is two random variables $X$ and $Y$ which are independent. Then, there is a theorem saying that they are uncorrelated. It also have an easy proof, which you can find in many probability texts. But this do not mean that if you have a sample $(X_1,Y_1), \dotsc, (X_n,Y_n)$ from $(X,Y)$, that the sample correlation coefficient will be zero! which is what the answer by @Nutle explains. But, if $n$ is large, the sampling distribution of that correlation coefficient will be concentrated close to zero. So, yes, samples from two independent variables can seem to be correlated, by chance. Especially if $n$ is small. That just means that you risk having a type I error.
{ "pile_set_name": "StackExchange" }
Q: Code Review Question about disposing Don't web.Dispose() dispose parent SPSite object? Is it Ok if I do this in web part? { SPSite site = SPContext.Current.Site; using (SPWeb web = site.OpenWeb(s)) { // .. } } A: The code you written is Ok. using statement will dispose the SPWeb object you have instantiated. Parent Site - This object is not initiantiated by you, you are using SPSite that belongs to SPContext. SPContext objects are managed by the SharePoint framework and should not be explicitly disposed in your code. This is true also for the SPSite and SPWeb objects returned by SPContext.Site, SPContext.Current.Site, SPContext.Web, and SPContext.Current.Web.
{ "pile_set_name": "StackExchange" }
Q: order of code execution with wait and notify I research using wait and notify methods for synchronization. I wrote small example and don't understand why I see this output: take 1 release 1 release 2 my code: main: public class CustomSemaphoreTest { public static void main(String[] args) throws InterruptedException { Semaphore semaphore = new Semaphore(); SendingThread sender = new SendingThread(semaphore); RecevingThread receiver = new RecevingThread(semaphore); sender.start(); Thread.sleep(300); receiver.start(); } } sender: class SendingThread extends Thread { volatile Semaphore semaphore = null; int count = 1; public SendingThread(Semaphore semaphore) { this.semaphore = semaphore; } public void run() { this.semaphore.take(); } } receiver: class RecevingThread extends Thread { volatile Semaphore semaphore = null; int count = 1; public RecevingThread(Semaphore semaphore) { this.semaphore = semaphore; } public void run() { while (true) { try { this.semaphore.release(); Thread.sleep(20); } catch (InterruptedException e) { } // System.out.println("get signal " + count++); } } } semaphore: class Semaphore { private boolean signal = false; int rCount = 1; int sCount = 1; public synchronized void take() { System.out.println("take " + sCount++); this.signal = true; this.notify(); try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } public synchronized void release() throws InterruptedException { System.out.println("release " + rCount++); notify(); while (!this.signal) { wait(); } this.signal = false; } } How did I imagine execution of this program?: time 0: thread1: sender.start() ->...-> public synchronized void take() { System.out.println("take " + sCount++); this.signal = true; this.notify(); //try wake up waiting threads but noone sleep thus have not affect try { wait(); // release monitor and await notify } catch (InterruptedException e) { e.printStackTrace(); } } Thus I see in screen take 1 time 300: thread 2 receiver.start(); -> public synchronized void release() throws InterruptedException { System.out.println("release " + rCount++); //section is rid thus this lines outputes notify(); // notify thread1 while (!this.signal) { wait(); // pass the control to thread1 and await notification ..... } this.signal = false; } Thus I didn't expect to see release 2 Please clarify my misunderstanding. A: You set signal = false after the wait(). Sequence of events. sender calls take() sender prints signal is set to true receiver is notified sender calls wait() receiver wakes receiver prints sender is notified signal is true so no wait() signal is set to false release() method ends receiver loops receiver prints signal is false so wait() sender wakes and exits immediately as nothing to do So you have several issues Your sender doesn't loop You set signal at the wrong time
{ "pile_set_name": "StackExchange" }
Q: How to set default values in the Angular Timepicker? I am using the NgbTimepickerModule and this is my template: <form [formGroup]="form"> <div ngbDropdown> <input class="datepicker btn btn-link" ngbDropdownToggle [value]="_value?(_value|date:'dd/MM/yy, HH:mm'):label"> <div ngbDropdownMenu > <ngb-datepicker #dp [(ngModel)]="date" (dateSelect)="getDatetime()"[ngModelOptions]="{standalone:true}" ></ngb-datepicker> <ngb-timepicker [ngModel]="time" (ngModelChange)="time=$event;getDatetime()"[ngModelOptions]="{standalone:true}" [hourStep]="time?.hour" [minuteStep]="time?.minute"></ngb-timepicker> </div> </div> <button class="btn btn-primary">submit</button> </form> I want time picker to have some default values in the HH and MM inputs and not be blank Here is the link to my Stackblitz⚡ Also is it possible to add "required validation" on my datetime picker? A: I have forked your stackblitz example and tweaked your code to achieve your requirements. here is the codebase I tweaked. // initialized time object from time: any to time: { hour: number, minute: number}; In your if time not set condition added default time if (!this.time) { value = new Date().getDate()+'/'+new Date().getMonth()+'/'+new Date().getFullYear()+' '+ new Date().getHours() +':'+ new Date().getMinutes(); // note this part this.time = { hour: new Date().getHours(), minute: new Date().getMinutes() }; } Checkout the working DEMO
{ "pile_set_name": "StackExchange" }
Q: How to send a value from js file and display in a HTML in Angularjs? I am implementing an Event Handler using Angularjs. User can insert an event and the relevant date. All the details of an event will be stored in an array (which is in controller.js file). Then I need to find out the event with closest date to the current date and display it on the UI. ( I am displaying the all the other events using ng-repeat. Also I want to display this part as the upcoming event) Since I am a newbie to Angularjs, I couldn't understand some solutions on the web. Can you suggest me a best solution to achieve this? Also what is the best way to add a calendar to the UI? Thanks in advance! A: Use module like below which has afterWhere filter or write filter by your self to filter your events array by given date and filter out events after that date. https://github.com/a8m/angular-filter For calendar, use this module. https://angular-ui.github.io/ui-calendar/
{ "pile_set_name": "StackExchange" }
Q: Is there ERC20 token test library? I have a custom ERC20 token project and I would like to cover the token behaviour with tests. As the ERC20 interface is standardized I wonder whether there are some libraries to test ERC20 functionality or to help me with it? I use truffle in my project so I prefer tests specifically for this framework but it is not required. A: I haven't found out nothing similar to what I was looking for. Hence I have came up with the custom package: https://github.com/CryptoverseRocks/token-test-suite With this package all the tests are already written. Just configure and run the test suite contained!
{ "pile_set_name": "StackExchange" }
Q: twitter4j configuration I'm trying to configure twitter4j to stream tweets I got (consumer key/secret, access token & access secret) from twitter already I created a new java project and imported twiiter4j as a library Now I want to know how to configure it ( http://twitter4j.org/en/configuration.html) The first way : Save a standard properties file named "twitter4j.properties". Place it to either the current directory, root of the classpath directory. I'm using netbeans and want to know the file type I should choose when I create properties file and where exactly I have to place it? A: Answer to your questions: Select a normal text file type, add the contents and rename it to twitter4j.properties You may place the file in the root folder of your project, or in any folder in the classpath. Just be sure the folder is in the classpath, thats what needs to be taken care of.
{ "pile_set_name": "StackExchange" }
Q: Signalling to threads waiting at a lock that the lock has become irrelevant I have a hash table implementation in C where each location in the table is a linked list (to handle collisions). These linked lists are inherently thread safe and so no additional thread-safe code needs to be written at the hash table level if the table is a constant size - the hash table is thread-safe. However, I would like the hash table to dynamically expand as values were added so as to maintain a reasonable access time. For the table to expand though, it needs additional thread-safety. For the purposes of this question, procedures which can safely occur concurrently are 'benign' and the table resizing procedure (which cannot occur concurrently) is 'critical'. Threads currently using the list are known as 'users'. My first solution to this was to put 'preamble' and 'postamble' code for all the critical function which locks a mutex and then waits until there are no current users proceeding. Then I added preamble and postamble code to the benign functions to check if a critical function was waiting, and if so to wait at the same mutex until the critical section is done. In pseudocode the pre/post-amble functions SHOULD look like: benignPreamble(table) { if (table->criticalIsRunning) { waitUntilSignal; } incrementUserCount(table); } benignPostamble(table) { decrementUserCount(table); } criticalPreamble(table) { table->criticalIsRunning = YES; waitUntilZero(table->users); } criticalPostamble(table) { table->criticalIsRunning = NO; signalCriticalDone(); } My actual code is shown at the bottom of this question and uses (perhaps unnecessarily) caf's PriorityLock from this SO question. My implementation, quite frankly, smells awful. What is a better way to handle this situation? At the moment I'm looking for a way to signal to a mutex that it is irrelevant and 'unlock all waiting threads' simultaneously, but I keep thinking there must be a simpler way. I am trying to code it in such a way that any thread-safety mechanisms are 'ignored' if the critical process is not running. Current Code void startBenign(HashTable *table) { // Ignores if critical process can't be running (users >= 1) if (table->users == 0) { // Blocks if critical process is running PriorityLockLockLow(&(table->lock)); PriorityLockUnlockLow(&(table->lock)); } __sync_add_and_fetch(&(table->users), 1); } void endBenign(HashTable *table) { // Decrement user count (baseline is 1) __sync_sub_and_fetch(&(table->users), 1); } int startCritical(HashTable *table) { // Get the lock PriorityLockLockHigh(&(table->lock)); // Decrement user count BELOW baseline (1) to hit zero eventually __sync_sub_and_fetch(&(table->users), 1); // Wait for all concurrent threads to finish while (table->users != 0) { usleep(1); } // Once we have zero users (any new ones will be // held at the lock) we can proceed. return 0; } void endCritical(HashTable *table) { // Increment back to baseline of 1 __sync_add_and_fetch(&(table->users), 1); // Unlock PriorityLockUnlockHigh(&(table->lock)); } A: It looks like you're trying to reinvent the reader-writer lock, which I believe pthreads provides as a primitive. Have you tried using that? More specifically, your benign functions should be taking a "reader" lock, while your critical functions need a "writer" lock. The end result will be that as many benign functions can execute as desired, but when a critical function starts executing it will wait until no benign functions are in process, and will block additional benign functions until it has finished. I think this is what you want.
{ "pile_set_name": "StackExchange" }
Q: what is the issue in this android counter i am making a counter. i did this coding for it, but it not working, i tried it in many other ways but not getting success. what problem i am creating here code for the main activity is below public class MainActivity extends Activity implements OnClickListener { Button add; Button reset; TextView count; int counter=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); add=(Button)findViewById(R.id.button1); add.setOnClickListener(this); reset=(Button)findViewById(R.id.button2); reset.setOnClickListener(this); count=(TextView)findViewById(R.id.textView1); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button1: counter++; count.setText(counter); break; case R.id.button2: //count.setText("0000"); break; default: break; } } } My xml coding is as below <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:id="@+id/textView1" android:layout_width="160dp" android:layout_height="160dp" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:gravity="center_vertical" android:text="00000" android:textAppearance="?android:attr/textAppearanceLarge" android:textSize="120dp" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/textView1" android:layout_centerHorizontal="true" android:layout_marginTop="138dp" android:text="ADD" android:textSize="80dp" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="70dp" android:text="RESET" android:textSize="20dp" /> </RelativeLayout> A: Here count.setText(counter); counter is an int, Use count.setText(Integer.toString(counter)); A: You should set : count.setText(""+counter); Instead of : count.setText(counter); A: You need to convert the integer. count.setText(""+counter); To set it to zero, count.setText("0000"); looks fine.
{ "pile_set_name": "StackExchange" }
Q: Implied globals and the global object I'm trying to see a bit how implied globals work by experimenting with my console and plunker. I'm creating a self-invoking function, (function () { toto = 1; })(); According to the book I'm reading, ... implied globals are technically not real variables, but they are properties of the global object. I'm trying to see if after this function call, I can access toto as a property of the global object - which, in the browser, is the window. When I use hasOwnProperty('toto'), (by typing it in the console directly) I get false. I figured I'd use in, and indeed, toto is "in" window (so, it's not in window itself but to a child object of it) Can you shed some light? Any idea how to use Chrome Web Tools in order to inspect the status of all variables declared at any given time? A: You are probably runing your hasOwnProperty from console and you have the wrong frame selected. I ran hasOwnProperty command in all of the frames that consist the plunker website and I get both true and false + in some frames toto is not even initialised (ReferenceError: toto is not defined).
{ "pile_set_name": "StackExchange" }
Q: About sending email for postdocs after finding a potential mentor Two weeks ago one of my emails was replied by a professor who expressed his interests in my work and consider me as a potential postdoc. He told me that he is going to apply for funding then will inform me. At this moment, I do not know whether I keep sending emails to other professors for postdoc position or wait for email from potential mentor? A: I recommend that you keep all your options open up until you have something firm. There are too many things that could go wrong for you to make assumptions that you "have" a position. Interest was expressed. Action was promised. A contract was not offered. Don't mislead people, of course, but don't drop your other efforts.
{ "pile_set_name": "StackExchange" }
Q: Local variable for comparable generic I'm trying to implement sorting for a generic list of Comparable objects. The problem is that I can't define a local variable for such lists and it leads to code duplicates. Basically I need a variable that will maintain a returned value from a method with signature <T extends Comparable<T>> List<Item<T>> getItems(int itemType, Class<T> cl). Here is the code https://ideone.com/mw3K26. The goal is to avoid code duplicates on lines 25, 26 and 29, 30. Is it even possible? A: Put assosiations itemType -> Class to Map and use it instead if-else. private static final Map<Integer, Class<? extends Comparable>> types = new HashMap<>(); static { types.put(1, Long.class); types.put(2, Date.class); } public List<Long> getSortedIds(int itemType) { Class<? extends Comparable> clz = types.get(itemType); if (clz != null) { List<Item> items = (List<Item>)getItems(itemType, clz); Collections.sort(items); return items.stream().map(it -> it.id).collect(Collectors.toList()); } //... return null; }
{ "pile_set_name": "StackExchange" }
Q: Setting up umbraco hello i am trying to set up umbraco on my pc i have followed each step and when i try to lunch the site on iis i get this error Module IIS Web Core Notification BeginRequest Handler Not yet determined Error Code 0x80070032 Config Error The configuration section 'system.web.extensions' cannot be read because it is missing a section declaration Config File \?\C:\inetpub\wwwroot\cms\web.config Requested URL http://localhost:80/cms Physical Path C:\inetpub\wwwroot\cms Logon Method Not yet determined Logon User Not yet determined any idea? please help A: Try changing the version of .NET that the application pool is running under. You've not mentioned which version of Umbraco you are using but I'm guessing 4.7. If so you'll probably need to be running it under .NET4, unless you have specifically downloaded the .NET3.5 version direct from Codeplex.
{ "pile_set_name": "StackExchange" }
Q: Scope of "software tools commonly used by programmers" in Stack Overflow I was reviewing reopen votes on SO and chose the "leave closed" button for this question. In my opinion, that looks like superuser material. To my surprise, not only my review was labeled as incorrect but the question is actually protected by the community. I'm not saying it's a bad question per se, but looking at the topics list on both sites... SO a specific programming problem, or a software algorithm, or software tools commonly used by programmers; and is a practical, answerable problem that is unique to software development SU computer hardware, computer software, or personal and home computer networking I underlined the most suitable items in bold here. So the issue to me lies in the interpretation of "software tools commonly used by programmers". I'm a programmer and I use a number of software tools besides an IDE... Next time I see a SO question about an e-mail client, a spreadsheet or rich text editor, or... a browser, should I just answer it like I do for Java questions? Note Found a similar question here but there isn't really much material to answer my own doubt. A: Use common sense. You'll have to read it as "software tools commonly used when programming". If programmers are likely to play computer games, that doesn't mean that questions about computer games are on-topic. Web browsers are kind of a grey area though, again we have to use common sense. If the question is "I'm having problem surfing the web with Firefox" then the question is definitely off topic. If the question is "I'm doing web development and my page looks strange in Firefox" then the question is on topic. Not because Firefox is a programming tool, but because it is a target platform. If you apply common sense to the particular question linked, it can be boiled down to "I'm having problems with a certain application since I upgraded Firefox" and should be closed. It could have been on topic if the poster had written something like "I'm having problems with my application since I upgraded Firefox. This is what my application does: ... It uses the following resources which I think could be the cause: ... Here is the research of what I have done to trouble-shoot the issue: ..." A: The question is not about Firefox as a tool, it is about a developer having problems using Firefox as a platform. The specific problem involves code signing. It is absolutely on-topic for SO. In the list of SO topics it would fit under "a practical, answerable problem that is unique to software development". Even if the question had been about Firefox as a tool, that wouldn't necessarily have ruled it out as an SO question. Firefox is more than just a browser; it contains many debugging tools and there's even a version with a complete IDE. A: The wording of the topic list for Stack Overflow is perhaps a little bit vague. Perhaps the wording should be tightened up a bit; I see two potential directions this could be accomplished: software tools commonly used by programmers for programming … or software tools commonly specifically used by programmers … Either of these changes would remove the loophole alluded to in the question.
{ "pile_set_name": "StackExchange" }
Q: Want to understand this permission of /usr/bin/sudo I was getting below error while running command sudo -s after changing the permission to 777 of /usr/bin/sudo sudo: /usr/bin/sudo must be owned by uid 0 and have the setuid bit set Ii solved this by below process: Select your OS version in (recovery mode), and press Enter Key. Ex : Ubuntu 14.04 (recovery mode) It will bring you up another screen. Now select “Drop to root shell prompt” and press Enter. It will load a command line at the bottom of the screen. Now run each of the following commands. mount -o remount,rw / mount –all chown root:root /usr/bin/sudo chmod 4755 /usr/bin/sudo restart Now, I just want to understand why it was not working with 777 permission on /usr/bin/sudo Please explain, thanks in advance. A: sudo has the "setuid" bit (the 4 in chmod 4755). It means that when you execute sudo, you automatically get the privileges of sudo's owner, which is root. So any execution of sudo has root privileges, it's just that the first thing the "official" version does is asking for a password to determine it it can continue. If sudo is word-writable, then anyone can patch it to not check passwords or do other things, and so gain access to root privileges. So sudo must be kept R/O for everyone otherwise it should be considered as compromised.
{ "pile_set_name": "StackExchange" }
Q: Using Asterisk and FreePBX how can I map extensions to outbound routes I have a Trixbox server (Asterisk and FreePBX) that has multiple tenants on it. I need these tenants calls to go out via different outbound routes in order to split the bills at the SIP trunk provider end. Essentially the extensions need to be grouped and each group needs to have it's own outbound SIP trunk. This used to be achievable using custom contexts in FreePBX but that functionality no longer exists. How can this be done now? I'd be happy to change to a different VoIP distribution which provides this functionality however I need it to be Asterisk and FreePBX based as that's what the customer knows. A: We usually do this by adding contexts in the extensions_custom.conf file. These custom contexts include the default contexts but listen for your outbound calls such as NXXNXXXXXX, 1NXXNXXXXXX and add your dialing codes such as 7777 to the beginning of the call. Then you simply setup your outbound routes so the specific routes are listening for the relevant codes and stripping them off before pushing the call to the carrier. Phones belonging to client1 would be set in "custom-client1" context while client2 phones would be in "custom-client2". [custom-client1] exten => _NXXNXXXXXX,1,Dial(Local/888${EXTEN}@from-internal) exten => _1NXXNXXXXXX,1,Dial(Local/888${EXTEN}@from-internal) exten => _NXXXXXX,1,Dial(Local/888${EXTEN}@from-internal) include => from-internal [custom-client2] exten => _NXXNXXXXXX,1,Dial(Local/889${EXTEN}@from-internal) exten => _1NXXNXXXXXX,1,Dial(Local/889${EXTEN}@from-internal) exten => _NXXXXXX,1,Dial(Local/889${EXTEN}@from-internal) include => from-internal
{ "pile_set_name": "StackExchange" }
Q: Is there a way to prevent Geb from returning null from void methods? In a Spock Specification any line in expect: or then: block is evaluated and asserted as boolean, unless it has signature with return type void. I've noticed that there is something odd going on for methods declared as void on any class inheriting from Navigator (for example Page or Module classes). Let say we have such example: class NavigationSpec extends GebSpec { def 'Collections page has a right header'() { when: to CollectionsPage then: hasHeaderText('Collections') } } The hasHeaderText() method is defined within CollectionsPage class as follows: class CollectionsPage extends Page { static url = 'movies/collections' void hasHeaderText(String expectedText) { assert true } } On purpose I'm just asserting true over there so it should never fail. Even though it fails with an error: Condition not satisfied: hasHeaderText('Collections') | null How and why a void method call result is evaluated as null? I know how to 'fix it'. It's enough to declare the method return type as boolean and return true. This is ugly though as following all the asserts otherwise unnecessary return true has to be added like: boolean hasHeaderText(String expectedText) { assert header.text() == expectedText return true } This causes only noise though. Is there any way to prevent Geb from returning null from void methods? I'm, of course, aware that this specific case could go like: boolean hasHeaderText(String expectedText) { header.text() == expectedText` } This doesn't explain the oddity of lost void return type, not to mention we loose meaningful assert failure message with such approach. A: It's part of the Groovy language that every method returns a value. This allows any method to be used in expressions or as lambdas. All methods that are declared void return null. If you don't explicitly have any return statement, the result of the last expression in your method is returned. You can look at the bytecode... even if you declare a return type, you don't actually need to return anything as Groovy will, by default, return null: // returns null String callMe() { } static void main(args) { def x = callMe() assert x == null println "OK!" } Because Spock will assert anything in the then block which is not a simple assignment, you need to avoid doing anything other than boolean assertions in the then block. Even assigning a variable, though allowed, should be avoided... It's hard to keep tests clean and clear, and by adhering to these guidelines will really work for you in the long run, not against you. So, the correct way to write the assertion you want is to make your method return a boolean: boolean hasHeaderText(String expectedText) { header.text() == expectedText } And use it in the then block: then: 'The header has the expected text #expectedText' hasHeaderText expectedText Looks pretty good if you ask me. EDIT I've noticed that Groovy/Spock actually will not assert the result of a normal void method even in the then block... What's probably going on here is that you don't have a normal void method, you seem to be calling a dynamic method of CollectionsPage (I guess that's Geb's magic in play), which means that, probably, the Spock AST Transformer does not have the opportunity to check the signature of the method you're calling, so it correctly assumes it must assert the result... at least that's what it looks like. A: @Renato is correct in the edited part of his response - your call to a void method gets asserted by Spock because it's a dynamic call and Spock isn't able to figure out that you are calling a void method and eagerly asserts the call. If you changed your code to: class NavigationSpec extends GebSpec { def 'Collections page has a right header'() { when: CollectionsPage collectionsPage = to CollectionsPage then: collectionsPage.hasHeaderText('Collections') } } then it won't get asserted.
{ "pile_set_name": "StackExchange" }
Q: g++ custom dynamic library linking error undefined symbol Ok, I'm looking for a solution for 2 days now. I didn't find anything to solve my problems. What is currently going on? So, I tried creating a dynamic library (.so) on Linux Mint Maya 13 with g++. foolib.h: #pragma once #include <stdio.h> void foo( void ); foolib.cpp: #include "foolib.h" void foo( void ) { printf ("Hello World!\n"); }; main.cpp: #include "foolib.h" int main( int argc, char** argv ) { foo (); }; I compiled these files with these instructions: libfoo.so: g++ -shared -o libfoo.so -fpic foolib.cpp foo: g++ main.cpp -o foo -L -lfoo Creating libfoo.so works without any errors, but foo throws undefined reference ´foo'. I copied sample code from several web pages and tried to compile it, always the same result. The funny is, I can link do libdl.so (-ldl), load my .so and my function. What am I doing wrong? I hope I could formulate my question correctly. Please tell me if I didn't. : ) A: You should use: g++ main.cpp -o foo -L./ -lfoo or g++ main.cpp -o foo libfoo.so
{ "pile_set_name": "StackExchange" }
Q: How do I wrangle animals? Possible Duplicate: Any way to round up animals in Minecraft? Is nudging the only way to get an animal into my breeding pens, or can I use another, more reliable method? A: If you hold wheat in your hands, the animals will follow you. Good grief, nudging them would take forever. :) You might also be interested in this thread about separating them into pens. Better read it beforehand. ;)
{ "pile_set_name": "StackExchange" }
Q: Find parameters such that the sequence becomes a probability mass function Consider $(q^{|n|})_{n \in \mathbb{Z}}$ for $q \in \mathbb{R}$. Now, I am trying to solve the following: For which parameters $q$ does there exist $c \in \mathbb{R}$ such that the sequence $(cq^{|n|})_{n \in \mathbb{Z}}$ becomes a probability mass function and what is $c$ in these cases? What I notice is that we know that $n$ is an integer, which we can separate into two sums: $0,1,2,...$ and $-1,-2,-3,...$. Since we take the absolute value the second sum goes from $1$ to $\infty$. So the pmf probably consists of two sums that sum up to 1. How do I now determine the needed parameters? A: The sum of the terms of the sequence is $$c\sum_{n=-\infty}^\infty q^{|n|}=c\left(1+2\sum_{n=1}^\infty q^{|n|}\right)=c\left(1+2\frac{q}{1-q}\right)=c\frac{1+q}{1-q}$$ where, in the second step, we applied the formula for the sum of an infinite geometric series, which is only valid if the ratio is between $-1$ and $1$ (otherwise, the sum is infinite). Therefore, the values of $q$ that lead to a probability mass function are $$|q|<1.$$ The value of $c$ is obtained by equating the sum to $1$: $$c\frac{1+q}{1-q}=1 \implies c=\frac{1-q}{1+q}.$$
{ "pile_set_name": "StackExchange" }
Q: how to filter rsyslog messages by tags I have several applications and scripts that I want to redirect the output to custom files. I launch those applications using command | logger -t TAG I would like to filter these messages based on their tags and redirect them to different files. I don't want to use bash redirection as those applications are mainly long running process and need proper log rotation. I have tried to add a custom filter in /etc/rsyslog.d/60-myfilter.conf ; if $syslogtag == 'giomanager' then /var/log/giomanager.log What am I doing wrong ? What is the proper way to filter based on the tag or is there a better option to have similar result? A: I've not used if like that (or syslogtag) but I have used :<blah>,<condition> ... (in particular :msg, contains,...) but try :syslogtag, isequal, "giomanager:" /var/log/giomanager.log & stop The & stop (Or, & ~ in rsyslog v6 and older (Such as on RHEL6)) causes the matched message to be discarded after logging otherwise it will be further parsed by other rules. Update: tested and The syslogtag contains a : and should be enclosed in "" rather than '' A: So I finally found a solution to my problem. Thank you very much to @lain for leading my way. The solution as stated before is to include a ':' in the tag name. Also, and this is very important, the file name must be before 50-default.conf in alphabetical order. To resume, put the following in 30-giomanager.conf : :syslogtag, isequal, "giomanager:" /var/log/giomanager.log & stop Note that the file /var/log/giomanager.log should be writable by the 'syslog' user.
{ "pile_set_name": "StackExchange" }
Q: Complex version of Fourier series Let a be a positive real number and f $2\pi$ periodic function defined by: $f(x)= \begin{cases}0 & \text{if }-\pi\lt x\lt 0 \\ 1 &\text{if }0\le x\le a \\ 0 &\text{if }a\lt x\le \pi\end{cases}$ Find the complex form of Fourier series of $f(x)$ A: The complex form of the Fourier series associated to $f$ is of the form: $$\sum_{n \in \mathbb Z} c_n e^{inx}$$ Where: $$c_n = \begin{cases} \frac{a_n - ib_n}2 &\text{if $n \ge 1$} \\ \frac{a_0}2 &\text{if $n = 0$} \\ \frac{a_{-n} + ib_{-n}}2 &\text{if $n \le -1$} \end{cases}$$ We just have to find the $a_n$'s and $b_n$'s. As $f = 0$ on $(-\pi, 0)$ and $(a, \pi]$, our integrals are just over $[0,a]$. $$a_0 = \frac1{\pi} \int_0^a (1) dx = \frac{a}{\pi}$$ For $n > 0$, we have: $$a_n = \frac{1}{\pi} \int_0^a \cos(nx)dx = \frac{\sin(na)}{n \pi}$$ $$b_n = \frac{1}{\pi} \int_0^a \sin(nx) dx = \frac{1 - \cos(na)}{n \pi}$$ Therefore: $$c_n = \begin{cases} i\frac{e^{-ina} - 1}{2\pi n} &\text{if $n \ge 1$} \\ \frac{a}{2\pi} &\text{if $n = 0$} \\ i\frac{e^{-ina} - 1}{2\pi n} &\text{if $n \le -1$} \end{cases}$$ Therefore: $$ f(x) \sim \frac{a}{2 \pi} +\frac{i}{2\pi} \sum_{n \in \mathbb Z^*} \left( \frac{e^{-ina} - 1}{n} \right) e^{inx} $$
{ "pile_set_name": "StackExchange" }
Q: Does Maven plugin change the action of Run button (green triangle) in Eclipse? I know Maven helps to build project, e.g. to create war. But in Eclipse which benefits does it add? Does it add any magic when I press Run or only helps to get dependencies? A: It does not by default change the Run action. But, as illustrated in this article, it adds to the Run configuration the possibility to define a "Run action", to trigger maven builds:
{ "pile_set_name": "StackExchange" }
Q: Azure Traffic Manager for balancing WebApp slots You can create a Traffic Manager Profile, and then add Ednpoints to balance AppService-WebApps (formerly WebSites) as shown here: When you select the App Service option you can choose the main WebApp, but how can you select any of its slots enviroments? A: Traffic Manager's 'Web App' endpoints only support the production Web App slot (e.g. myapp.azurewebsites.net). However, you can use Traffic Manager with a specific slot by using 'External' endpoints. You can only do this via the ARM API / new portal (the old ASM API does not allow External endpoints to point to Web Apps).
{ "pile_set_name": "StackExchange" }
Q: Package Dependency I have a huge Java Application with numerous packages. Some of the classes in these packages have dependency on classes in other packages. Given a class, I want to know all the dependent classes on it and vice-versa. A GUI tool should be really helpful. A: There's some useful tools described here for the (free) Eclipse IDE. There's also more info on dependency tools with a comparison against depfinder here. A: CDA - Class Dependency Analyzer is incredibly simple to use, and can help you visualize those dependencies between packages and classes.
{ "pile_set_name": "StackExchange" }
Q: How to draw a cushion like rectangle in processing? I am trying to draw a cushion like rectangle in processing like the pic shown. Is there any tricky way to use "light" to realize this? Does anyone have any idea about it? Thanks! Pic reference: http://philogb.github.io/blog/2009/02/05/cushion-treemaps/ A: What you're talking about is called a radial gradient. There are a number of ways to do it. One way would be to simply draw a bunch of circles. Here is a small example: size(200, 200); for(float diameter = 255; diameter > 0; diameter--){ noStroke(); fill(0, 255-diameter, 0); ellipse(width/2, height/2, diameter, diameter); } You'll also have to limit your drawings to a rectangle shape. You might do that using the createGraphics() function to create a buffer, then draw the gradient to the buffer, then draw the buffer to the screen. You should really break your problem down into smaller steps and take those steps on one at a time. First create a sketch that shows a simple gradient. Then create a sketch that uses a buffer. Get those both working by themselves before you combine them into one sketch. Good luck.
{ "pile_set_name": "StackExchange" }
Q: a person who works in a copy shop So far I've found xeroxer but I'm not sure if it's a common term and also if the term is specifically used to describe people who make copies in offices rather than running a business independently and having a shop of their own. I need to check it with an English native speaker. Is it a common word? If not, what do you usually call them? A: New occupational (and avocational) nouns can be formed by analogy as the need arises: photographer, programmer, coder, blogger, gamer, snowboarder. The natural choice here, photocopier, was already used for the device itself. I'm a xeroxer at a print-shop would certainly be understood by most native speakers of American English who are adults (little kids and even some teens might not recognize "xerox") but most people would probably say a desk-clerk at a print-shop or something like that.
{ "pile_set_name": "StackExchange" }
Q: get self as invoking class in parent in Ruby My first class which has constant. I want to make it to work somehow as dynamic value. class Post < ActiveRecord::Base TEST = ["#{self.name}", "test1"] end class FakePost < Post end In rails console I am trying to access TEST constant with FakePost but it is still show self as "Post" object. Is there any way to achieve this? Current: irb(main):004:0> FakePost::Test => ["Post", "test1"] But I want to return this result when I access Constant through Post not vi FakePost. Expected: irb(main):004:0> FakePost::Test => ["FakePost", "test1"] A: The problem is that the code TEST = ["#{self.name}", "test1"] is only interpreted once, when the Post class is instantiated. After that it will be fixed as ["Post", "test1"]. Off the top of my head I can't think of a way of making this work with a constant, but if you were to replace it with a class method it works fine: class Post def self.TEST [self.name, "test1"] end end class FakePost < Post end Post.TEST #=> ["Post", "test1"] FakePost.TEST #=> ["FakePost", "test1"] The reason this works is that the code inside the class method is interpreted at run time (i.e. when you call the method), rather than when the class is interpreted. The timeline for both cases is as follows: With TEST Constant: Post class is instantiated and interpreted line by line. self.name is interpreted and returns 'Post', as self is currently the Post class. Post::TEST is set irrevocably to ["Post", "test1"] FakePost class is instantiated and inherits from Post, including the already-instantiated TEST constant of ["Post", "test1"] FakePost::TEST == Post::TEST == ["Post", "test1"] #=> true With TEST class method: Post class is instantiated and interpreted line by line. Post class method TEST is added (but not interpreted yet). FakePost class is instantiated and inherits TEST class method from Post. Still hasn't been interpreted yet. When you run Post.TEST or FakePost.TEST the method will finally be interpreted. self will now be either Post or FakePost depending on which class called the TEST method.
{ "pile_set_name": "StackExchange" }
Q: refactor javascript for loop to use recursion to find the sum of a sequence of whole numbers I don't have much practice with recursion and I have only some experience with javascript. How do I refactor the code below to use recursion instead of the for loop? function add(a, b) { var sum = 0; for (var i = a; i <= b; i++) { sum += i; } return sum; } console.log(add(3,7)); //25 The for loop makes sense to me; recursion not so much. A: EASY WAY: function recursive(a, b) { if(a > b) { return 0; } return a + recursive(a+1, b); } console.log(recursive(3,7)); HARD WAY: (EASY + EXPLANATION) What is a recursion in a common programming language? according to Wikipedia: Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem (as opposed to iteration). translated in everyday language a recursion is when you iterate n-times a function(in this case) and every time that the function call hisself wait for the result of the invoked function's instance. The invoked functions's intance will invoke himself another time and wait for the result. When this endless loop will stop? When an instance will finally return a value, this happens typically with a check before the recursive call(see the easy way). When a function will return a value all the knots will be loose and the first function that started the cycle will return the final value. if you want to go deep or just my short explanation was not convincing i reccoment you to read this article: https://www.codecademy.com/en/forum_questions/5060c73fcfadd700020c8e54
{ "pile_set_name": "StackExchange" }
Q: r package development - own function not visible for opencpu Hi I am new to writing R packages. r package development imports not loaded advised me to use roxygen2. I once called devtools::document() and the namespace was generated. However when I load this simple package (or try it via opencpu) the functions are NOT available. calling the code in native R seems to work test2::hello() [1] "Hello, world!" Starting opencpu like: 1) start opencpu simple server via library(opencpu) 2) execute opencpu$restartwhich will show a port number 3) http://localhost:myPortNumber/ocpu/library/myPackage/info ---> this endpoint works As mentioned in the comments this is not a "proper" way of calling a function. However opencpu defaults to myfunction/print if a function is called via HTTP as http://public.opencpu.org/ocpu/library/stats/R/quantile/printand even that does not work when I call the hello function. This is a demonstration of how to call a more complex function: curl http://localhost:myPortNumber/ocpu/library/stats/R/quantile/json -d '{"type":1,"x":[1,2,3,4,5,6,7,8,9,10],"probs":[0.05,0.25,0.75,0.95]}' -H "Content-Type: application/json" You can simply test it via: curl http://public.opencpu.org/ocpu/library/stats/R/quantile/json -d \ '{"type":1,"x":[1,2,3,4,5,6,7,8,9,10],"probs":[0.05,0.25,0.75,0.95]}' \ -H "Content-Type: application/json" I did install it via sudo like: sudo R CMD INSTALL test2_0.1.tgz that means it should be available via in the /library/test2 endpoint. Solution: It still was the wrong API endpoint --> I was missing the R sub-directory http://localhost:myPort/ocpu/library/myPackage/R/hello/ Example-code is here: https://github.com/geoHeil/rSimplePackageForOpenCpu A: It still was the wrong API endpoint --> I was missing the R sub-directory http://localhost:myPort/ocpu/library/myPackage/R/hello/
{ "pile_set_name": "StackExchange" }
Q: Determine which day event is on when event is selected in fullcalendar When an event is clicked, is there any way to determine which date this event falls on? Im running into this issue when dealing with events that span multiple days, and since the event only contains a start and end date, I have not found any way to ascertain which date of the multi-day event was selected. A: You can pass additional fields into your JSON object when you bind up your events. For example, I pass in a "leave" parameter that tells me whether an event is an appointment or a part of the day off.
{ "pile_set_name": "StackExchange" }
Q: $EM_T=1 \implies M_t$ is a martingale Fix $T>0$ and let $M_t$ be a non negative supermartingale for all $t\leq T$. I read somewhere that $EM_0=EM_T=1$ implies that $M_t$ is a martingale. Now I know that $EM_t=1$ for all $t$ implies that $M_t$ is a martingale. I saw this proved somewhere on MSE too. However, I cannot prove $EM_T=1 \implies M_t$ is a martingale. Any help is appreciated. A: You have to assume that $EM_0=1$. Otherwise the result is false: just take any supermartingale which is not a martingale and divide it by the constant $EM_T$ to get a counter-example. Now assume that $EM_0=EM_T=1$. From the definition of a supermartingale it follows immediately (by taking expectation)that $EM_t$ is decreasing in $t$: $EM_{t+1} \leq EM_t$. Hence $EM_0=EM_T=1$ implies that $EM_t=1$ for all $t \in [0,T]$ ($1=EM_T\leq EM_t \leq EM_0=1$ so equality must hold throughout) and you already know why this implies that $(M_t)$ is a martingale.
{ "pile_set_name": "StackExchange" }
Q: adding jar files to sunspot solr We are currently using sunspot 1.3.3 gem. We configured solr spellchecker component with JaroWinklerDistance as below in solrConfig.xml. However, it results in ClassNotFoundException. How do we handle this? Is there some specific directory where we need to copy the jar file? How does one configure jetty/solr that is managed through sunspot? <lst name="spellchecker"> <str name="name">jarowinkler</str> <str name="field">spell</str> <str name="distanceMeasure"> org.apache.lucene.search.spell.JaroWinklerDistance </str> <str name="spellcheckIndexDir">./spellchecker</str> </lst> We have already tried putting lucene-spellchecker**.jar under rails_app_root/solr/lib and it doesn't work. Thanks exception stacktrace HTTP ERROR: 500 Severe errors in solr configuration. Check your log files for more detailed information on what may be wrong. If you want solr to continue after configuration errors, change: false in null ------------------------------------------------------------- org.apache.solr.common.SolrException: Error loading class ' org.apache.lucene.search.spell.JaroWinklerDistance ' at org.apache.solr.core.SolrResourceLoader.findClass(SolrResourceLoader.java:373) at org.apache.solr.core.SolrResourceLoader.newInstance(SolrResourceLoader.java:388) at org.apache.solr.spelling.AbstractLuceneSpellChecker.init(AbstractLuceneSpellChecker.java:95) at org.apache.solr.spelling.IndexBasedSpellChecker.init(IndexBasedSpellChecker.java:56) at org.apache.solr.handler.component.SpellCheckComponent.inform(SpellCheckComponent.java:274) at org.apache.solr.core.SolrResourceLoader.inform(SolrResourceLoader.java:486) at org.apache.solr.core.SolrCore.(SolrCore.java:588) at org.apache.solr.core.CoreContainer$Initializer.initialize(CoreContainer.java:137) at org.apache.solr.servlet.SolrDispatchFilter.init(SolrDispatchFilter.java:83) at org.mortbay.jetty.servlet.FilterHolder.doStart(FilterHolder.java:99) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:594) at org.mortbay.jetty.servlet.Context.startContext(Context.java:139) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1218) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:500) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:448) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:147) at org.mortbay.jetty.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:161) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:147) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:117) at org.mortbay.jetty.Server.doStart(Server.java:210) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) at org.mortbay.xml.XmlConfiguration.main(XmlConfiguration.java:929) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:616) at org.mortbay.start.Main.invokeMain(Main.java:183) at org.mortbay.start.Main.start(Main.java:497) at org.mortbay.start.Main.main(Main.java:115) Caused by: java.lang.ClassNotFoundException: org.apache.lucene.search.spell.JaroWinklerDistance at java.net.URLClassLoader$1.run(URLClassLoader.java:217) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:205) at java.lang.ClassLoader.loadClass(ClassLoader.java:321) at java.net.FactoryURLClassLoader.loadClass(URLClassLoader.java:615) at java.lang.ClassLoader.loadClass(ClassLoader.java:266) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:264) at org.apache.solr.core.SolrResourceLoader.findClass(SolrResourceLoader.java:357) ... 32 more RequestURI=/solr/admin/ Powered by Jetty:// A: The class should be included in one of the following jars :- solr-lucene-spellchecker-X.X.0.jar lucene-spellchecker-X.X.0.jar So you can confirm if the jar is included in the classpath when solr starts up and loads external jars. If you are executing it in Jetty, you can update the lib directives in SolrConfig.xml to look into the lib where the library exists. You can also want to look at this Interesting thread. Putting it on a single line :- <str name="distanceMeasure">org.apache.lucene.search.spell.JaroWinklerDistance</str>
{ "pile_set_name": "StackExchange" }
Q: Inject modules conditionally in AngularJS app My Angular app structure is like this: App.js angular.module('RateRequestApp', [ 'RateRequestApp.services', 'RateRequestApp.controllers', 'ui.bootstrap', 'angular-loading-bar', 'textAngular', 'angularFileUpload' ]); I am using different HTML files for different pages and I am not using Angular's $route, but still I want to use same app in all pages with different controllers. As you can see I am injecting third party modules to my app. The problem is that in some pages I don't want some of this modules, How can I avoid them where I don't need them? A: Yes you can do it something like this: var myApp = angular.module('RateRequestApp', [ 'RateRequestApp.services', 'RateRequestApp.controllers', 'ui.bootstrap', 'angular-loading-bar' ]); var lazyModules = ['textAngular', 'angularFileUpload']; angular.forEach(lazyModules, function(dependency) { myApp.requires.push(dependency); }); In this case you may inject the modules conditionally. (But please note, lazy loading of some module may not work where there is some configuration needed.)
{ "pile_set_name": "StackExchange" }
Q: .Net Framework 4 Full and Net Framework 4 Client Profile Targeting I wanted to target my .net application to .NetFramework 4(Client Profile) but later i recognized that a 3rd party control uses System.Design for implementing custom control. Now im concerned about the users, as most will have .Net Framework 4 Client Profile installed on their system rather than .Net Framework 4 Full. Will the users find it annoying to download and install the Full Framework. But there is only a minor size difference client- 41mb and full- 48 mb. Does most .net applications require client profile only? Also is there a alternative way to use ControlDesigner class in c# with client profile. Please help me out. A: You simply need to select the full .NET 4 framework as the Target Framework. Trying to take any shortcut around that is going to blow up in your face. Well, your user's face most of all. This just isn't a problem. Your Setup project needs to ensure that the right profile is available on the user's machine. Which does not involve a 48 megabyte download if she already has the Client profile, the .NET installer only downloads the missing pieces.
{ "pile_set_name": "StackExchange" }
Q: Do you still need a Test Plan when adopting Continuous Delivery? As a test manager, I need to review a Test Plan for the upcoming release. I also need to review the test results. The tests are both automated and manual. As an organization, we would like to move to continuous integration/continuous delivery, where code changes are fully tested automatically e.g. via Jenkins. In the future, we may move to CD to automatically ship those changes Do you still need a Test Plan when using CI/CD? How do you ensure that the product has been tested properly, including functional and non-functional testing? What oversight can QA provide when using CI/CD? A: I don't see CI/CD as something different than non CI/CD process, tests are simply being run by a non human entity. Do you need a test plan (or plan your tests) ? of course you do, you need to think what goes into automation and whether something should be done manually or tested in production (A/B tested, telemetry), analyze risks related to testing this way and not another, and evaluate the level of testing in each stage. You can monitor the quality of the results the same way as before- use reports, dashboards and analyze logs, data and user bug reports A: Do you still need a Test Plan when using CI/CD? YES you do. Because a test plan will tell you at least the thing that you did not specify in your question: how often do you plan to run the tests? Which tests will run with which periodicity? Maybe there is a common practice to do it every night. Is it feasible for your project? Which alternatives do you have? Why is one method better / worse than the other? Which tests will be executed "continuously"? Top level / features-related? Architectural? Unit tests? Can you test everything automatically? Does your system depend on other systems? How are the changes of the other systems managed and tested? Even if "continuous" sounds so great, it is not at all continuous. At best, it is periodic. That is why you actually need to plan ahead. Another question: what will happen when some test-case(s) fail? How will you handle the logging, reporting, monitoring, fixing? Continuous vs. Periodic A river flowing is continuous. Even if there is ice on the top of it. Testing cannot be continuous. The code must achieve certain "maturity" before it can be tested. The minimum pre-requisite is that it is compilable. The minimum pre-requisite for delivery is that certain test-cases must pass. If they fail, the product is not safe for use. A test-suite takes time. You do not execute everything at any point in time. It starts, and then it finishes, and then a new SW version is taken from the repository, and testing starts again and ends again... So such a system can be called "continuous" only if a lot of the practical details of reality are ignored - as it is usually done for marketing and advertising purposes.
{ "pile_set_name": "StackExchange" }
Q: Path not really given path to Python The which command does not seem to be giving the right result: [ray@localhost ~]$ unalias python bash: unalias: python: not found [ray@localhost ~]$ unalias which bash: unalias: which: not found [ray@localhost ~]$ which python /usr/local/bin/python [ray@localhost ~]$ /usr/local/bin/python -V Python 2.7.6 [ray@localhost ~]$ python -V Python 2.6.6 [ray@localhost ~]$ ls -l /usr/local/bin/python* lrwxrwxrwx. 1 root root 11 Jun 10 12:27 /usr/local/bin/python -> python2.7.6 -rwxr-xr-x. 1 root root 8040 Jun 10 12:21 /usr/local/bin/python2.7 -rwxr-xr-x. 1 root root 8040 Jun 10 12:25 /usr/local/bin/python2.7.6 -rwxr-xr-x. 1 root root 1674 Jun 10 12:23 /usr/local/bin/python2.7-config lrwxrwxrwx. 1 root root 16 Jun 10 12:23 /usr/local/bin/python2-config -> python2.7-config lrwxrwxrwx. 1 root root 14 Jun 10 12:23 /usr/local/bin/python-config -> python2-config [ray@localhost ~]$ A: No, which is fine. bash is confused. hash -d python
{ "pile_set_name": "StackExchange" }
Q: DRY Rails Metaprogramming - Use Cases So I've running around my app, applying this particular use case for DRY'ing your app via metaprogramming: http://rails-bestpractices.com/posts/16-dry-metaprogramming In what other ways are you applying metaprogramming to keep your app DRY? A: I wrote a gem called to_lang which makes use of this type of dynamic method definition. It adds a bunch of methods to strings in the form to_language which all call a single method with different parameters. ToLang::StringMethods in particular is where this magic happens. Doing the same thing without metaprogramming would require the definition of hundreds of methods.
{ "pile_set_name": "StackExchange" }
Q: Access UI chart text legend sorted as number I have searched for a solution but I can't find one suitable on this problem. I have a chart in access where the Y-axis is text but starts with a number, so up along the y-axis i get this: I know why, but I don't know how to fix it. They all have an ID which is fine. I can chose to put the ID on the Y-axis, but then the kW range can't be visualized. How is this changed? Changing the text to number is not possible as it needs to be like "a-b kW". Thanks in advance. A: For those who might get this problem, I found out why. When selecting the data, it chose to use the "Total" function, and "Avg" because that is what the values are. (The picture below says "Group By" but it was automaticly set to "Avg". I just forgot to change it when i snipped for stack. That results in: But if i remove the "Total" function i get this: So, removing the "Total" function works here...
{ "pile_set_name": "StackExchange" }
Q: How to find path of my folder We are working on project. Every colleague have different folder for the install In my case the folder of my files is in C:\\p4_3202\\CAR\\car.rt.appl\\dev\\car.components\\cars\\res\\car.rt.components.cars\\resources\\js; for other colleague it could be in C:\\my_3202\\CAR2\\car.rt.appl\\dev\\car.components\\cars\\res\\car.rt.components.cars\\resources\\js; it is depends how you config your perforce. I need to read files from my folder but i don't know the name of the folder ( as i explained it could be different ) File folderFile = new File(folder); How i can find the location of my folder ? ( c:\p4\......test.js ) I tried with System.getProperty("sun.java.command"); System.getProperty("user.home") but it didn't give me the path of my folder A: I would use a system property for each user. So all users tell where perforce is installed (might already exist a property for this, look at the docs). This could then be read by your code like: System.getenv().get("PROP"); On a unix/Linux system you can set the property in a shell/environment variable using: export PROP=thepath Windows was a long time ago for me but if I remember correctly its somewhere under System on control panel :) Update: http://www.itechtalk.com/thread3595.html
{ "pile_set_name": "StackExchange" }
Q: Smooth vector field vanishing at exactly 6 points Let $ E $ be the ellipsoid in $ \mathbb{R}^3 $ given by, $$ E = \left \{ (x,y,z) \mid \frac{x^2}{9} + \frac{y^2}{4} + z^2 = 1 \right \} $$ Find a smooth vector field $ H : \mathbb{R}^3 \rightarrow \mathbb{R}^3 $, such that $ H(v) $ is tangent to $ E $ for each $ v \in E $ and $ H $ vanishes at exactly $ 6 $ points of $ E $. My idea : It suffices to find such vector field $ H $ for $ S^2 $, the unit sphere since there is an orthogonal transformation mapping $ E $ to $ S^2 $. Taking three mutually orthogonal planes through the origin would give us $ 6 $ good points on the sphere, for simplicity, take the coordinate planes $ x=0, y=0, z=0 $. Now, if $ n,s $ are the north and south poles, then planes passing through $ n,s $ and perpendicular to $ z=0 $ cut $ S^2 $ in great circles. For each such circle $ C $, consider $ C \backslash \{n,s\} $ and define $ F $, the field of unit vectors tangent to $ C $ on $ C \backslash \{n,s\} $. Thus $ F $ is defined on $ S^2 \backslash \{n,s\} $. Let $ H $ be the vector field obtained by multiplying the function $ (1-x^2)(1-y^2)(1-z^2) $ with $ F $ on $ S^2 \backslash \{n,s\} $ and $ 0 $ on $ n,s $. Does this work? A: You are working too hard. The fact that the principal axes have different lengths is supposed to help you. Hint: On the sphere, the unit normal vector field is always parallel to the vector field $x\partial_x + y\partial_y + z\partial_z$. But for a general surface this is not true. Why? At how many points are the two vector fields parallel for your surface? Can you use this to construct a good vector field?
{ "pile_set_name": "StackExchange" }
Q: Input type = "file" loses file automatically? I have two inputs of type file, one in a partial view, and another in main page In partial view <input type="file" name="image" id="image" onchange="readURL(this)"/> In main page <input type="file" name="userProfilePic" id="userProfilePic" style="display:none" /> What I want is that when a user changes image/file on the visible file upload, the image/file should be updated on main/other input too. Here's my code. function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#imagePreview').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); // window['profilePic'] = input.files[0]; $('#userProfilePic').get(0).files[0] = input.files[0]; return false; } The Error The error is quite weird, when I open my console, and check for files, it shows up sometime, and a moment later it don't. In my console window $('#userProfilePic').get(0).files[0] File (file object details) .... (after a second) $('#userProfilePic').get(0).files[0] undefined And it isn't happening the first time only. Say sometimes, it shows the values for 5-6 times, then 7th time it won't... $('#userProfilePic').get(0).files[0] File (file object details) .... (after a second) $('#userProfilePic').get(0).files[0] File (file object details) .... (after a second) $('#userProfilePic').get(0).files[0] File (file object details) .... (after a second) $('#userProfilePic').get(0).files[0] undefined That's all the code I have, there is no other code. Now, as you can see in the code, I also set window[profilePic] to the file object. But if I check that in console window, it always shows no matter what? How is this happening? The problem I need to submit the form, but when I do, the image (the input file) is being sent as null, but sometimes as a valid file. As I explained earlier, when I check the value in console, it shows for first time, or some random number of times, then all of a sudden it is gone, while the variable that I set on window (window[profilePic]) always have that file object. In case someone is wondering, the original/visible file input where user actually selects the file always has the value. A: You cant do this for security reasons , all files uploaded via input type="file" have to be done manually by the user. However as long as the user will upload an image anyway , you should do all the process you want in your server side script. for further info , please refer to this post here : How to set a value to a file input in HTML?
{ "pile_set_name": "StackExchange" }
Q: "Unsupported gpu architecture 'compute_30'" while installing gpu tools for R I was trying to install 'gputools' and 'rpud', but got the same "nvcc fatal : Unsupported gpu architecture 'compute_30" error for both. I assume something is wrong with my CUDA kit configuration. I installed: CUDA drivers 3.1.17 CUDA toolkit 3.2.17 GPU computing SDK 3.1 I can see CUDA panel in system preferences, and the path to NVCC is placed as well. Machine is MAC Book Pro with OSX 10.6.8, Nividia gt 330m (with drivers 256.00.35f12), Intel Core i7 Maybe someone could help to solve this problem? A: I believe that at the time of CUDA Toolkit 3.2 there were no devices of compute capability 3.0. However, support for the cards of compute capability 3.0 is obviously required by 'gputools' and 'rpud' so you should simply install newer CUDA Toolkit such as 6.5, latest driver etc., that already support compute capability 3.0. Also, your GPU, GT330m, is only of compute capability 1.2, so in the end, once you do all of the above, you won't be able to run the software using your GPU anyway. Also, I have no knowledge of 'gputools', nor 'rpud', but I presume you are talking about this package. If so, then quoting from linked resource: SystemRequirements: Nvidia's CUDA toolkit (>= release 5.0)
{ "pile_set_name": "StackExchange" }
Q: I submitted my paper in a hijacked journal I encountered a huge problem, I submited my paper in a faked journal. I sent them several times about the result of reviewing process. The email answer was: Dear Author Please clarify what exactly is your problem regarding your paper. We are at your service and ready to assist. Regards Ciencia e Tecnica Vitivinicola Journal Editorial They told me also if I have submitted successfully I will get the review answer at most after 2 weeks, but I have the proof of a successful submitted paper. Now what should I do? I want to resubmit it in another journal, I have an examination in the summer and I need a published paper in my resume. A: If I understand correctly from your link, the journal exists and is legitimate, but you submitted your manuscript to a fake website falsely claiming to be the journal's website. In this case, the proper things to do in my view are: E-mail the editor in chief. Do not simply resubmit with a cover letter explaining what happened: you don't know if and when they are going to read it. You want them to know immediately, and take action quickly. if you have the opportunity, publish a preprint. You should consider your manuscript as leaked and no longer private, and it is very likely that it is being sold or submitted somewhere else by the hackers. If the journal normally wouldn't allow a preprint, discuss it with the editor and see if they are willing to make an exception. If you paid something for the submission, go through the usual procedure for getting your money back: block the credit card payment and inquire with your bank, and contact the authorities to report theft.
{ "pile_set_name": "StackExchange" }
Q: Java and CANopen Background I am required to create a Java program on a laptop to receive/send CANopen messages. RJ45 is chosen to be the network's physical medium. I am new to CANopen and Java communications programming. Pardon me if I appear to be uninitiated. The truth is, I have been reading up a lot, but I still do not know how to get started. Questions Other than connecting a PC to the CANbus network, what else does the CAN-PC adapter do? Is it possible to connect the laptop to the CANbus network without the CAN-PC adapter? If a CAN-PC adapter is required, what sort of adapter should I use? PCMCIA, parallel, serial, usb, etc.? How do I get started in writing the java program to listen/write CANopen messages? What libraries should I use? Do I need to create my own drivers? Should my program handle heart-beat monitoring, error detection, etc.? Or are these taken care of by the CAN-PC adapter? How do I retrieve specific information from a CANbus node? How is the EDS file and object dictionary created? Does every node require them? How do I simulate a CAN network to test my Java program without buying CAN hardware? A: That's a lot of questions. I have never done any CAN related programming in Java, but let's see which questions I might answer anyway: 1) Other than connecting a PC to the CANbus network, what else does the CAN-PC adapter do? It depends mainly on which CAN controller that is embedded in your adapter. But basically it just handles the low-level stuff like bus-arbitration, error-handling, retransmissions and message buffering. 2) Is it possible to connect the laptop to the CANbus network without the CAN-PC adapter? No. 3) If a CAN-PC adapter is required, what sort of adapter should I use? PCMCIA, parallel, serial, usb, etc? On a laptop? I would choose a USB interface. I have good experience with Kvaser's interfaces. 4) How do I get started in writing the java program to listen/write CANopen messages? Depends on the API for your adapter. The API will most probably be C-based, so I would at least start out with some simple C test programs. The CAN-interface supplier probably have some good examples. 5) What libraries should I use? Probably the one supplied with your CAN-interface, at least for the basic CAN part. For the CANopen part, there are some commercial CANopen stacks available and perhaps even some free. I doubt there are any written in Java. You could also implement the necessary parts of the CANopen stack yourself if you are only doing simple communication. 6) Do I need to create my own drivers? Generally no. Depends on your operating system and CAN-interface model. Select a CAN interface with drivers for your operating system. 7) Should my program handle heart-beat monitoring / error detection / etc? Or are these taken care of by the CAN-PC adapter? The CANopen stack should handle that on the CANopen level. The low level CAN bus error handling is taken care of by your interface. 8) How do I retrieve specific information from a CANbus node? I don't know what you mean here. PDOs or SDOs depending on what kind of information you want. 9) How is the EDS file and object dictionary created? Does every node require them? You don't genereally need to create an EDS file, but might be useful for documentation purposes. The object-dictionary is implemented in software. Some parts of the OD are mandatory if making something standards-compliant. 10) How do I simulate a CAN network to test my java program without buying CAN hardware? I wouldn't... A meaningful bus simulator would probably be more expensive to develop than to just bu a CAN adapter. Note that many CAN adapters contain dual interfaces, so you may do communication tests on a real CAN bus with little more hardware than just the adapter and a couple of termination resistors.
{ "pile_set_name": "StackExchange" }
Q: Count occurencies of managed metadata in sharepoint list I have custom list with multi-select managed metadata column. How could I count the number of items (preferably using rest api), which has particular metadata in this column? For example on my list there are items like below: Item1: keyword1, keyword2 Item2: keyword1, keyword4 Item3: keyword3 And now, if I search for "keyword1", I should get value 2 (because 2 items have this metadata). If I search for "keyword4", I should get value 1. A: Here is a syntax to get the count from the search results as we don`t have a way to query to get the total count. siteurl/_api/search/query?querytext='(owstaxId<<metadata field name>>:"<<keyword>>") (IsDocument:True) Path:"<<library path>>" ListID:"library guid"'&selectproperties='Title'&startrow=0&rowlimit=10&trimduplicates=false The example as follows https://tenant.sahrepoint.com/_api/search/query?querytext='(owstaxIdMarket:"HP+Spring+2017") (IsDocument:True) Path:"https://tenant.sharepoint.com/Setup Sheets" ListID:"74df6ac9-6c26-4c17-a6b3-60756cdae097"'&selectproperties='Title'&startrow=0&rowlimit=10&trimduplicates=false Then you can get the "Total Rows" value from the response.
{ "pile_set_name": "StackExchange" }
Q: How may I select a smoothing capacitor to mitigate LED flicker without the use of a scope? I recently replaced a set of incandescent bulbs from the interior of my old car with some very inexpensive festoon LEDs. Unfortunately the LEDs are not 100% compatible with the lighting system as dimming is accomplished via pulsing the voltage signal. The pulsing effectively dims the incandescent bulb, but causes the LEDs to flicker/blink. I think a quick solution to mitigate or eliminate the flicker is to solder a ceramic or film capacitor in parallel with the LED power supply terminals. However, I don't have access to a scope to measure the pulse frequency so I can't calculate an ideal capacitor value to use. The bulbs run at 12V, draw ~250mA of current -- can someone suggest a safe range of capacitor values I can experiment with? Perhaps the frequency needs to be estimated for this question to make any sense. I may also be able to emulate the resistance of the incandescent bulb with a resistor in series, but I don't want to lose the intensity that the LEDs are currently providing. A: There's a visual difference between flicker and blink... Flicker (if you can see it) would be something like 40-60 Hz. Blinking would be much lower, maybe 10 Hz or less. The difference is important, because flicker can be solved with a cap, but blinking could indicate that there is a bit of a problem that won't be solved with a cap. For example, the car's electronics could measure the current drawn by the bulb, then decide that the current is too low (because you installed LEDs instead of incandescents) and then decide the bulb is blown, then sleep for half a second, and then restart the cycle. That would result in blinking. Or the driver chip in your LED bulbs could be "cheap" (ie, braindead), and being driven by PWM pulses could give it a bit of a seizure. I've had good success with sets of lights by not replacing them all with LEDs, but leaving at least one incandescent bulb. This obviously works only in the case where you got several lights in parallel, but it seems to fool the electronics into thinking that the original bulbs are present. So try this first (ie, one LED, the rest incandescent). However if the issue is indeed that the PWM frequency is too low, the problem with a capacitor in parallel with the LED bulb is that the discharged capacitor acts like a short and will draw a high current when the bulb turns on, which may cause problems with the switching MOSFET. In this case, a RC network to filter the voltage, may be a better option, or just use a low quality cap with enough ESR to not cause a current spike. (for example, using a 0.1R ESR cap in parallel with the lights would cause a 12V / 0.1R = 120A current spike at turn-on... but a cap with a few ohms ESR would be okay)
{ "pile_set_name": "StackExchange" }
Q: JSF Lifecycle performed 2 times with PrimeFaces ajax I use PrimeFaces 3.3.1 with Apache MyFaces 2 on WebSphere Application Server. My BackingBean is SessionScoped. I have a form with a selectOneButton should update the whole form. <h:form id="options"> <p:panelGrid> <p:column rowspan="2" style="width:115px;"> <p:selectOneButton value="#{graph.diagramdata}" id="diagramdata"> <f:selectItem itemLabel="WAS-Diagramm" itemValue="1" /> <f:selectItem itemLabel="PSC-Diagramm" itemValue="2" /> <p:ajax listener="#{graph.changeView }" update=":options"/> </p:selectOneButton> <h:outputText>#{graph.diagramdata}</h:outputText> </p:column> <p:column rendered="#{graph.diagramdata eq '1' }"> ... </p:column> </p:panelGrid> </h:form> EDIT: PART OF BACKING BEAN @ManagedBean(name = "graph") @SessionScoped public class MyGraphBean implements Serializable { private int diagramdata; public void changeView(AjaxBehaviorEvent event) { LOGGER.info(this.getDiagramData()); } public int getDiagramdata() { return diagramdata; } public void setDiagramdata(int diagramdata) { if(diagramdata == 1 || diagramdata == 2) { this.diagramdata = diagramdata; } } } But when I change a value the jsf Lifecycle is performed 2 times. At first time the in.getValue is null the second time it is 1 or 2 (from LOGGER). But at the end my h:outputText prints 0... To debug I use BalusC: Debug JSF Lifecycle Why is te Lifecycle perfomed 2 times? How do I have to use my selectOneButton to render the other columns correctly? EDIT: DIRTY SOLUTION I found a solution for my problem (very dirty!!!). I changed the p:ajax component to f:ajax. So now my value is set to the correct value in the second lifecycle phase. <p:selectOneButton value="#{graph.diagramdata}" id="diagramdata"> <f:selectItem itemLabel="WAS-Diagramm" itemValue="1" /> <f:selectItem itemLabel="PSC-Diagramm" itemValue="2" /> <f:ajax listener="#{graph.changeView }" render="options"/> </p:selectOneButton> Also I added a if statement in my setter method to avoid that "0" is set. Now the first jsf lifecycle does nothing and the second sets my value. It works, but is not very fine... A: Seems like a bug with PrimeFaces selectOneButton. When I use e.g. p:selectOneMenu it works fine with 1 JSF Lifecycle! Here is the known issue from primefaces.
{ "pile_set_name": "StackExchange" }
Q: How to use an USB GPS mouse with an Android tablet? I have an goo' ol' Garmin 60csx device with excellent GPS reception. I can connect via USB to a host and provide GPS information this way -- the interface menu allows to send the NMEA data with 4800 baud over USB. On the other hand I have an Android Tablet running 4.1.2 (rooted/CyanoMod) with very poor GPS quality. In the config I find "GPS source" with the only option "internal". A pity, I would like to use the NMEA data incoming over USB. I can find plenty of apps that allow the use of Bluetooth GPS receiver, which is close, but not totally. Is no one using USB anymore? Is there any app that allows me to use the USB GPS device? And if not, it can't be that difficult to write a program recieving the NMEA data -- I did that with Python once. Then I would need to send it to the Android OS. Where is the lever here? A: I've never done this before, but personally I would try setting up the sample BroadcastReceiver referenced below and see if I could get a connection going. http://developer.android.com/guide/topics/connectivity/usb/host.html Then I'd use getInterfaceProtocol() to see if I was able to get the expected protocol.
{ "pile_set_name": "StackExchange" }
Q: ggplot annotate with greek symbol and (1) apostrophe or (2) in between text unable to add greek letters in ggplot annotate, when either: it is sandwiched in between other text, or the text in question contains an apostrophe. For example, the following works fine: df <- data.frame(x = rnorm(10), y = rnorm(10)) temp<-paste("rho == 0.34") ggplot(df, aes(x = x, y = y)) + geom_point() + annotate("text", x = mean(df$x), y = mean(df$y), parse=T,label = temp) However, ggplot explodes when I do: df <- data.frame(x = rnorm(10), y = rnorm(10)) temp<-paste("Spearman's rho == 0.34") ggplot(df, aes(x = x, y = y)) + geom_point() + annotate("text", x = mean(df$x), y = mean(df$y), parse=T,label = temp) ggplot is frustratingly sensitive to these special characters. Other posts do not appear to address this issue (apologies if not). Thanks in advance. A: I've felt your frustration. The trick, in addition to using an expression for the label as commented by @baptiste, is to pass your label as.character to ggplot. df <- data.frame(x = rnorm(10), y = rnorm(10)) temp <- expression("Spearman's"~rho == 0.34) ggplot(df, aes(x = x, y = y)) + geom_point() + annotate("text", x = mean(df$x), y = mean(df$y), parse = T, label = as.character(temp)) A: In case anyone is attempting to adopt this for a dynamic scenario where the correlation variable is not known beforehand, you can also create an escaped version of the expression as a string using: df <- data.frame(x = rnorm(10), y = rnorm(10)) spearmans_rho <- cor(df$x, df$y, method='spearman') plot_label <- sprintf("\"Spearman's\" ~ rho == %0.2f", spearmans_rho) ggplot(df, aes(x = x, y = y)) + geom_point() + annotate("text", x = mean(df$x), y = mean(df$y), parse = T, label=plot_label)
{ "pile_set_name": "StackExchange" }
Q: Deploy contract on EthereumJS TestRPC Following https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-1-40d2d0d807c2 I've tried to create an instance of a contract using: VotingContract = web3.eth.contract(abiDefinition) but I get: TypeError: web3.eth.contract is not a function So I've tried: VotingContract = new web3.eth.Contract(abiDefinition) as suggested here: web3.eth.contract is not a function when making contract But then when I try to deploy the contract on my test blockchaing (launched with EthereumJS TestRPC) I get the following: deployedContract = VotingContract.new(['Rama','Nick','Jose'],{data: byteCode, from: web3.eth.accounts[0], gas: 4700000}) TypeError: VotingContract.new is not a function at repl:1:38 at ContextifyScript.Script.runInThisContext (vm.js:44:33) at REPLServer.defaultEval (repl.js:239:29) at bound (domain.js:301:14) at REPLServer.runBound [as eval] (domain.js:314:12) at REPLServer.onLine (repl.js:433:10) at emitOne (events.js:120:20) at REPLServer.emit (events.js:210:7) at REPLServer.Interface._onLine (readline.js:278:10) at REPLServer.Interface._line (readline.js:625:8) at REPLServer.Interface._ttyWrite (readline.js:905:14) at REPLServer.self._ttyWrite (repl.js:502:7) at ReadStream.onkeypress (readline.js:157:10) at emitTwo (events.js:125:13) at ReadStream.emit (events.js:213:7) at emitKeys (internal/readline.js:420:14) at emitKeys.next (<anonymous>) at ReadStream.onData (readline.js:1006:36) at emitOne (events.js:115:13) at ReadStream.emit (events.js:210:7) at addChunk (_stream_readable.js:252:12) at readableAddChunk (_stream_readable.js:239:11) at ReadStream.Readable.push (_stream_readable.js:197:10) at TTY.onread (net.js:589:20) Any suggestions? A: The API for the web3.js v1.0 changed. The tutorial is using the web3 api v0.x.x. Thus, you must either update your node to use the proper API npm install ethereumjs-testrpc [email protected] or, you must update the code to use the v1.0 implementation. I.E: web3.eth.getAccounts(console.log); You can also refer to the github from mjhm who did a great job converting the tutorial code to v.1.0. https://github.com/mjhm/hello_world_dapp
{ "pile_set_name": "StackExchange" }
Q: jquery .change() prevents.click() on other element My html is: <input type="text" id="t1" /><br/> <a id="a1" href="#">button</a> with javascript $(document).ready(function() { $('#t1').change(function() { alert('text1Change'); }); $('#a1').click(function() { alert('link1Click'); }); }); JSFiddle link When I enter text in t1, then click link a1 without changing focus or leaving textfield, then only change event is fired. Is it possible to fire both events or only click? Thanks for any feedback! A: Since you have an alert on the change handler the click on the anchor element is not completed. If you use a console.log() statement for testing those event handlers you can see that both the methods are fired $(document).ready(function() { $('#t1').change(function() { console.log('text1Change'); }); $('#a1').click(function() { console.log('link1Click'); }); }); Demo: Fiddle
{ "pile_set_name": "StackExchange" }
Q: In Beamer, command to increment the slide count? Is there a way to increment the slide count in a relative way? I assume I could do \setcounter{beamerpauses}{5} if I knew I wanted it set to 5, but I'd like to be able to add something before it, without renumbering everything. One workaround would be just put an uncover with nothing inside it: \uncover<+>{} A: You can use \addtocounter{beamerpauses}{x}, to increase the counter by x. Example-Code: \documentclass{beamer} \begin{document} \begin{frame} \begin{itemize} \item<1-> 1 \item<2-> 2 \item<3-> 3 \item<4-> 4 \item<5-> 5 \item<6-> 6 \end{itemize} \addtocounter{beamerpauses}{2} \pause D (show with 4) \pause E (show with 5) \pause F (show with 6) \end{frame} \end{document} A: If you want more than one pause, you can add this number as optional argument to \pause[<n>]: \documentclass{beamer} \begin{document} \begin{frame} before pause \pause[5] after pauses \end{frame} \end{document}
{ "pile_set_name": "StackExchange" }
Q: Downloading a CSV from tmp folder of PHP project I currently am working on a PHP project that uses the Zend Framework. I am making a CSV without any issues in the controller, but then want the user to be able to download the file by clicking a button in the view. In my .phtml I have: <a class="btn" href="<?php echo $this->download;?>" download>Export to CSV</a> $this->download is being set in the controller: $view["download"] = $this->_createCSV($bqc_jobs, $startDate, $endDate, $processor_id, $defaultTime); The _createCSV function creates the CSV and stores it in the temporary directory that the site uses. It then returns the filepath. private function _createCSV($jobs, $start, $end, $user=null, $minutes){ $format = "Ymd_His"; if(!$start && !$user){ $start = date($format, strtoTime("-" . $minutes . " minutes")); } if(!$end){ $end = \DateTime::createFromFormat($format, date($format))->format($format); } $directory = Config::$tempDir; $fileName = $directory . "/" . ($user ? $user . "_" : "") . ($start ? $start . "_" : "") . $end . "_report.csv"; $file = fopen($fileName, 'w'); foreach ($jobs as $job){ fputcsv($file, $job); } fclose($file); return $fileName; } When the button is clicked, the browser tries to download the file, but errors because it cannot find the file. This makes sense, since the browser should not have access to the temporary folder, but I'm not entirely sure how to get around this. A: If you are unable to see the folder due to the UNIX file permissions, then your only options will be to: Change the file permissions on the tmp folder so that your web server can read/write there using chmod/chown (I assume it is a linux system?) Use a different folder with sufficient permissions Don't store the file on disk - store it in a database instead (not optimal). Once you are sure your file permissions are in order and that the file can be read by apache, it appears that you should be able to use php's readfile function to actually transmit the file back to the browser: <?php $file = '/tmp/monkey.gif'; if (file_exists($file)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.basename($file).'"'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); readfile($file); exit; } ?>
{ "pile_set_name": "StackExchange" }
Q: How to connect apache ignite node by static ip address I have got a hetzner server with config: <bean id="ignite-configuration" class="org.apache.ignite.IgniteSpringBean"> <property name="configuration"> <bean class="org.apache.ignite.configuration.IgniteConfiguration"> <property name="peerClassLoadingEnabled" value="true"/> <property name="igniteInstanceName" value="statistic-server"/> <property name="discoverySpi"> <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi"> <property name="ipFinder"> <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder"> <property name="addresses"> <list> <value>127.0.0.1:47500..47509</value> </list> </property> </bean> </property> </bean> </property> </bean> </property> </bean> I want to connect my Laptop to server like a server node. On my laptop I have next config: <property name="discoverySpi"> <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi"> <property name="ipFinder"> <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder"> <property name="addresses"> <list> <value>hetzner_ip_address:47500..47509</value> </list> </property> </bean> </property> <property name="addressResolver"> <bean class="org.apache.ignite.configuration.BasicAddressResolver"> <constructor-arg> <map> <entry key="192.168.1.10" value="laptop_static_ip_address"/> </map> </constructor-arg> </bean> </property> </bean> </property> Can I connect servers behind NAT by static ip address and how can I do this? A: It's not very clear weather you have a client or server node behind NAT, but actually in Ignite a server node can sometimes establish connection with a client node, so you need to make sure that connections are allowed in both directions. In case of NAT this means that in addition to AddressResolver you need to configure port forwarding on the router, or use SSH tunnel.
{ "pile_set_name": "StackExchange" }
Q: Onselect event doesn't fire on div I have been unable to trigger an onselect event handler attached to a <div> element. Is it possible to force a <div> to emit select events? A: According to w3schools, onSelect is only defined on input and textarea objects. You may however try to catch the MouseUp event and retrieve the selected text in the current window/document. A: You can achieve what you want by using onMouseUp event. See below... <html> <body> <div id="container" style="border: 1px solid #333" contentEditable="true" onMouseUp="checkMe()">Type text here</div> </body> <script language="javascript"> function checkMe() { var txt = ""; if (window.getSelection) { txt = window.getSelection(); } else if (document.getSelection) { txt = document.getSelection(); } else if (document.selection) { txt = document.selection.createRange().text; } alert("Selected text is " + txt); } </script> </html>
{ "pile_set_name": "StackExchange" }
Q: How much math would a non-STEM major have studied in 1950? I've spoken to several people who attended US universities in the decades before I was born, and I was somewhat surprised to find that it seemed to be common (based on the anecdotes I received) for non-STEM majors to top out at what is now considered high school algebra (e.g. things like competing the square, and basic conic sections). What would have been a typical or average mathematics curriculum for a US university student around 1950 who was not majoring in mathematics, a research science, or engineering? Would a student majoring in, say, English, art history, or theology have expected to have gone further than basic algebra? A: I'll quote a few short things from the (fantastic!) articles shared in comments by Dan Fox and user1527. Morris Kline in 1954 wrote: What have we been feeding the liberal arts students? The almost universal diet has been college algebra and trigonometry. I believe that these courses are a complete waste of time... Kline proceeds to outline a plan for a historically-minded math-survey/appreciation course for liberal arts students, revolving around his textbook, Mathematics in Western Culture (published 1953, after having taught 3 sections of such a course at NYU in the prior two years). Apparently the idea of a survey/appreciation course had been floating around for at least some decades before that, because Tucker writes in his 2015 historical survey: While the early MAA educational activities focused on secondary school preparation in mathematics, there was a 1928 MAA report (MAA [22]) addressing complaints about the first two years of college mathematics; also see Schaaf [31]. It acknowledged calls to offer a survey course of mathematical ideas with historical aspects for non-technical students... Tucker notes that calculus didn't become a standard freshman college subject until a major disruption in the 1950's, when the Cold War response to Sputnik -- and observations that WWII was won largely by pure mathematicians working in ballistics, signaling, rocketry, cryptography, and nuclear design -- caused a massive social call and glorification of math and physics. Physics faculty started expecting calculus usage in freshman physics courses, and math departments followed suit. Up until that time, a student taking first-year courses would likely have only college algebra and trigonometry available, from my reading here. On that latter major revolution that Tucker describes in the 1950's, he points out that in the early 1960's, as many as 5% of incoming college students were interested in being mathematics majors, while by 1975 it had dropped to 1.1%, and has stayed at around that level ever since (partly explained by the spin-off of computer science and statistics majors).
{ "pile_set_name": "StackExchange" }
Q: django rest framework file upload with nested writable serializers class AnnotationSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Annotation class ImageSerializer(serializers.HyperlinkedModelSerializer): annotations = AnnotationSerializer(many=True, required=False) class Meta: depth = 1 model = Image exclude = ('owner‘,) An annotation has an image foreign key attribute and so images have potentially multiple annotations. I’d like to create an image with nested annotations via a post request to an images endpoint including the list of annotations for this image. Posting my data json encoded to the images endpoint does work and creates an image with appropriate annotations. But when I try to upload an actual image, I have to use a multipart/form-encoded post request instead of a json one to make fileupload possible. And now I’m having a hard time getting my nested list of image annotations included in this request. Maybe I could put a json encoded string in some form-field and manually parse it in the view, overwriting request.DATA, but this seems to be really ugly. I wonder whether there’s a better way to achieve what I’m trying to do :). A: The neatest way I've found to solve this problem is to write a custom parser which parses the incoming multipart request. I've been using formencode to do the actual parsing but you could use any nested formdata library. This takes surprisingly little code: from rest_framework import parsers from formencode.variabledecode import variable_decode class MultipartFormencodeParser(parsers.MultiPartParser): def parse(self, stream, media_type=None, parser_context=None): result = super().parse( stream, media_type=media_type, parser_context=parser_context ) data = variable_decode(result.data) return parsers.DataAndFiles(data, result.files) And then in your ViewSet class ImageViewSet(viewsets.ModelViewSet): ... parsers = (MultipartFormencodeParser,) ... Formencode represents lists as <key>-<index> entries in the encoded form data and nested properties as <item>.<proprety>. So in your example the client would need to encode annotations as something like "annotation-1.name" in the request. Obviously you will still need to handle the update of nested data manually in the serializer as mentioned in the rest framework documentation here
{ "pile_set_name": "StackExchange" }
Q: How to send Raw notification to azure notification hub I'm new to azure, i've already configured my app to receive raw notification and i'm able to receive them from the debug page of azure website, my question is, how can i send them from my backend? i'm able to send all type of notification but can't figure out how to send that type... A really simple one like the azure one (Windows one not Windows phone one), just one not formatted string A: Asuming you are using WNS (and not MPNS), you simply call SendRaw from the hub.wns object. The syntax is: sendRaw(tags, payload, optionsOrCallbackopt, callback) See the NodeJS docs for the WNS service in Push Notification hubs at http://dl.windowsazure.com/nodedocs/WnsService.html. For a .NET backend, you use NotificationHubClient.SendNotificationAsync as documented at https://msdn.microsoft.com/en-us/library/azure/dn369343.aspx. The notification class you feed in will be a WindowsNotification as described at https://msdn.microsoft.com/en-us/library/azure/microsoft.servicebus.notifications.windowsnotification.aspx. Since you want to send a raw notification, you have to create the payload yourself. The documentation on how to create a raw payload is at https://msdn.microsoft.com/en-us/library/windows/apps/jj676791.aspx, and more specifically: The HTTP Content-Type header must be set to "application/octet-stream". The HTTP X-WNS-Type header must be set to "wns/raw". The notification body can contain any string payload smaller than 5 KB in size.
{ "pile_set_name": "StackExchange" }
Q: Vmware Server 2.02 on Ubuntu 9.04 (64-bit) - Performance problems with guest OS/servers! Hope someone here can help out as I'm pulling out my hair trying to find a way to get some decent performance from my VM box. I'm running Ubuntu 9.04 64-bit with an AMD 4 Core (phenom) and 4Gb or RAM. I also have another system that is running Ubuntu 9.04 32-bit (a notebook) with 2Gb or RAM. I can run an image on the slower/older dual core notebook lightning fast and take that same image and run it on my VM server and it runs noticeably slower. To make matters worst, when I run 2 server images that I have (that I need to run with some decent performance level) they come up very slowly and can almost cause the host OS to come to a halt/run very slow. If I look at the Ubuntu perfomance monitor it doesn't show a huge load on the CPUs or more than 55-65% RAM usage but it still runs like it's about to die. So... Here are my questions: Are there any know issues with the setup I have that would cause such bad performance? Should I be running something other than VMware 2.02? Should I be running some other host OS? Is there any way to change/modify settings some place to fix this? Thanks in advice. A: VMware Server 2 dumped its ability to be managed via the VMware Server Console application in favour of a Tomcat servlet, causing its disk space, CPU, and memory usage to balloon compared to version 1. Whether it's a plot to encourage users to shell out for VMware ESX or just poor judgement, I'd recommend reverting to VMware Server 1.10.
{ "pile_set_name": "StackExchange" }
Q: GPS coordinates to OLEX My goal is to convert gps coordinates to the format which the OLEX plotter has, so I can import them as marks. So I created a point at 64 10.239N and 51 41.523W I exported the point, and the file says 3850.2395026 -3101.5235411 1495562630 The last one seems to be the time, and is not important to me at this point. So my question is: what format does the OLEX plotter have? And possibly how to calculate this? A: The answer to this is simple. The decimal degrees just needed to be multiplied by 60. In other words: The values in the file are minutes. 64.1707 × 60 = 3850.24 -51.692 × 60 = -3101.52
{ "pile_set_name": "StackExchange" }
Q: How to search for string match in specific row of table in database in android I am building an App and dealing with databases for the first time I am trying to get the data TEXT as input and search its match in the specific row. I have failed to do that. I have got the specific row selected. I have six columns and I have got the specific row depending upon the id but comparing the Input Text in the other five columns is giving problematic output. With my approach given in the code below it is giving results after comparing it with the first or last column entry but not all. public Cursor finddata(String name,int ida, int guess){ String Query = "SELECT NAME1 FROM Capital_Names where ID = '" + ida + "' and NAME1='" +name+ "'"; cursor=db.rawQuery(Query,null); check=1; if(cursor==null){ String Query2 = "SELECT NAME1 FROM Capital_Names where ID = '" + ida + "' and NAME2='" +name+ "'"; cursor=db.rawQuery(Query2,null); check=2; } if(cursor==null){ String Query3 = "SELECT NAME1 FROM Capital_Names where ID = '" + ida + "' and NAME3='" +name+ "'"; cursor=db.rawQuery(Query3,null); check=3; } if(cursor==null){ String Query4 = "SELECT NAME1 FROM Capital_Names where ID = '" + ida + "' and NAME4='" +name+ "'"; cursor=db.rawQuery(Query4,null); check=4; } if(cursor==null){ String Query5 = "SELECT NAME1 FROM Capital_Names where ID = '" + ida + "' and NAME5='" +name+ "'"; cursor=db.rawQuery(Query5,null); check=5; } if(cursor==null){ String Query6 = "SELECT NAME1 FROM Capital_Names where ID = '" + ida + "' and NAME6='" +name+ "'"; cursor=db.rawQuery(Query6,null); } return cursor; } I think there is some error in the if condition that I am applying on the cursor as "if(cursor==null)" because it is only giving the answer by comparing the first statement without if even if it is matching in the first statement or not. If there is some direct query statement to do that ????? I have searched a lot on the internet but could not find a solution. And please do not direct me to already answered questions and answer this question if you could. Regards A: What you are doing wrong is that you check if the Cursor object returned by rawQuery() is null. rawQuery() returns a Cursor which may be empty (without any rows) but it can never be null. You can check if there any rows in the Cursor by checking its moveToFirst() method. Also never use concatenation of the parameters of the sql statement. It is not safe. Use placeholders ? and the 2nd argument of rawQuery() to pass the parameters. So change to this: public Cursor finddata(String name, int ida, int guess){ String sql = "SELECT NAME1 FROM Capital_Names " + "WHERE ID = ? AND ? IN (NAME1, NAME2, NAME3, NAME4, NAME5)"; return db.rawQuery(sql, new String[] {ida, name}); } It seems in your code that you don't use the argument guess of finddata(), so you can remove it. Also are you sure that you want to return only the column NAME1? You can replace it with "SELECT * FROM..." to return all the columns.
{ "pile_set_name": "StackExchange" }
Q: is it wrong to treat panic / recover as throw / catch Speaking as a new go enthusiast trying to work with the go way of error handling. To be clear - I like exceptions. I have a server that accepts a connection , processes a set of requests and replies to them. I found that I can do if err != nil{ panic(err) } in the deep down processing code and have defer func() { if err := recover(); err != nil { log.Printf("%s: %s", err, debug.Stack()) // line 20 } }() in the client connection code (each connection is in a goroutine). This nicely wraps everything up, forcefully closes the connection (other defers fire) and my server continues to hum along. But this feels an awful lot like a throw/catch scenario - which golang states it doesn't support. Questions is this stable. ie recovering a panic is an OK thing to do as an ongoing way of life. Its not intended to just slightly defer an immediate shutdown I looked for a discussion on this topic and did not find it anywhere - any pointers? I feel that the answer is 'yes it works' and can be used inside you own code, but panic should NOT be used by a library intended for wider use. The standard and polite way for a library to behave is by error returns A: Yes, you can do what you suggest. There are some situations within the standard packages where panic/recover is used for handling errors. The official Go blog states: For a real-world example of panic and recover, see the json package from the Go standard library. It decodes JSON-encoded data with a set of recursive functions. When malformed JSON is encountered, the parser calls panic to unwind the stack to the top-level function call, which recovers from the panic and returns an appropriate error value (see the 'error' and 'unmarshal' methods of the decodeState type in decode.go). Some pointers: Use error for your normal use cases. This should be your default. If your code would get clearer and simpler by using a panic/recover (such as with a recursive call stack), then use it for that particular case. Never let a package leak panics. Panics used within a package should be recovered within the package and returned as an error. Recovering from a panic is stable. Don't worry about continuing execution after a recover. You can see such behavior in standard library such as with the net/http package which recovers from panics within handlers to prevent the entire http server to go crash when panicing on a single request.
{ "pile_set_name": "StackExchange" }