qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
64,861,831
I am using java 11. Wanted to know whats the best(Most importantly **Recommended**) way to validate if the datetime string is ISO8601 complaint in java. Also how to compare this string value with java.sql.Timestamp?
2020/11/16
[ "https://Stackoverflow.com/questions/64861831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10267860/" ]
Assuming you are using at least Java 8 the simplest way to do so would be something like this: ``` private static boolean isIsoDate(String date) { try { Instant.from(DateTimeFormatter.ISO_INSTANT.parse(date)); return true; } catch (DateTimeParseException e) { //log the failure here e.printStackTrace(); } return false; } ``` Conversely you can validate the format using a `regex` but this is way harder that the above mentioned way. As for your other question, the easiest way would be to first convert your date string to a concrete `Date` object and then follow the recommendations here: [Compare Date object with a TimeStamp in Java](https://stackoverflow.com/questions/8929242/compare-date-object-with-a-timestamp-in-java)
``` public static boolean isValidISODateTime(String date){ try { LocalDateTime.parse(date, DateTimeFormatter.ISO_DATE_TIME); return true; } catch (DateTimeParseException e) { return false; } } ```
9,492,641
I need my sprite to transition to one color to another and on and on... like blue tint then green then purple, but i cannot find any good actions for that and am wondering, should i use animations? or is there an incorporated action for this?
2012/02/29
[ "https://Stackoverflow.com/questions/9492641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1104126/" ]
you can use CCTintTo action to change the color of the sprite ``` [sprite runAction:[CCTintTo actionWithDuration:2 red:255 green:0 blue:0]]; ```
since i saw several questions about replacing pixel colours in sprites, and i did'nt see any good solution (all solution only tint the color, and none of them is able to change an array of colours without forcing you into creating multiple image layers which construct the final image you want, i.e: one layer for pans, other for show, other for shirt, another for hair colour... and it goes on - note that they do have their advantages like the ability to use accurate gradients) my solution allows you to change array of colors, meaning you can have a single image with a known colors (you dont want any gradiants in this layer, only colours that you KNOW their values - PS this only applies to colors you intent to change, other pixels can have any colour you want) if you need gradiants over the colours you change, create an additional image with only the shading and place it as a child of the sprite. also be aware that i am super-new to cocos2d/x (3 days), and that this code is written for cocos2dx but can be ported to cocos2d easily. also note that i didnt test it on android only on iOS, i am not sure how capable is android official gcc and how will it deal with the way i allocate \_srcC and \_dstC, but again, this is easily portable. so here it goes: ``` cocos2d::CCSprite * spriteWithReplacedColors( const char * imgfilename, cocos2d::ccColor3B * srcColors, cocos2d::ccColor3B * dstColors, int numColors ) { CCSprite *theSprite = NULL; CCImage *theImage = new CCImage; if( theImage->initWithImageFile( imgfilename ) ) { //make a color array which is easier to work with unsigned long _srcC [ numColors ]; unsigned long _dstC [ numColors ]; for( int c=0; c<numColors; c++ ) { _srcC[c] = (srcColors[c].r << 0) | (srcColors[c].g << 8) | (srcColors[0].b << 16); _dstC[c] = (dstColors[c].r << 0) | (dstColors[c].g << 8) | (dstColors[0].b << 16); } unsigned char * rawData = theImage->getData(); int width = theImage->getWidth(); int height = theImage->getHeight(); //replace the colors need replacing unsigned int * b = (unsigned int *) rawData; for( int pixel=0; pixel<width*height; pixel++ ) { register unsigned int p = *b; for( int c=0; c<numColors; c++ ) { if( (p&0x00FFFFFF) == _srcC[c] ) { *b = (p&0xFF000000) | _dstC[c]; break; } } b++; } CCTexture2D *theTexture = new CCTexture2D(); if( theTexture->initWithData(rawData, kCCTexture2DPixelFormat_RGBA8888, width, height, CCSizeMake(width, height)) ) { theSprite = CCSprite::spriteWithTexture(theTexture); } theTexture->release(); } theImage->release(); return theSprite; } ``` to use it just do the following: ``` ccColor3B src[] = { ccc3( 255,255,255 ), ccc3( 0, 0, 255 ) }; ccColor3B dst[] = { ccc3( 77,255,77 ), ccc3( 255, 0 0 ) }; //will change all whites to greens, and all blues to reds. CCSprite * pSprite = spriteWithReplacedColors( "character_template.png", src, dst, sizeof(src)/sizeof(src[0]) ); ``` of course if you need speed, you would create an extension for a sprite that create a pixel shader that does it hw accelerated at render time ;) btw: this solution might cause some artefacts on the edges on some cases, so you can create a large image and scale it down, letting GL minimise the artefact. you can also create "fix" layers with black outlines to hide the artefacts and place it on top etc. also make sure you don't use these 'key' colors on the rest of the image you don't want the pixels changed. also keep in mind that the fact that the alpha channel is not changed, and that if you use basic images with pure red/green/blue colors only, you can also optimize this function to eliminate all artefacts on edges automatically (and avoid in many cases, the need for an additional shade layer) and other cool stuff (multiplexing several images into a single bitmap - remember palette animation?) enjoy ;)
395,100
If $g\in C^{\infty}\_c$ defined on $\Bbb R^n$ and K is the support of function $g$. I want to find the support of $g\_\epsilon$. Where $g\_\epsilon$ is regularization of $g$. --- Regularization of $g$ is defined as: $g\_\epsilon$:= $g\*\omega\_\epsilon$ (convolution of g and a test function) i.e. $g\_\epsilon(x )$=$\int\_{\Bbb R^n}g(x-y).\omega\_\epsilon(y)dy $ I think, this process is also known as mollification. Here $ \omega\_\epsilon (x)= \begin{cases} \frac{C^{-1}}{\epsilon^n} e^{{\frac{-\epsilon^2}{{\epsilon^2}-|x|^2}}}, &\text{for |x|< $\epsilon$ } \\ 0, & \text{otherwise} \\ \end{cases} $ --- I only know that support of convolution of two compactly supported functions is again a compact set. And, as support of $\omega\_\epsilon $ is a ball $B(0,\epsilon)$ and support of g is a compact set K(given) then support of their convolution should be the intersection of the support of $g(x-y)$ and $\omega\_\epsilon(y)$. Because for non zero function integration remains non zero...
2013/05/18
[ "https://math.stackexchange.com/questions/395100", "https://math.stackexchange.com", "https://math.stackexchange.com/users/76098/" ]
Definition: Let $f:\mathbb{R}^N\to\mathbb{R}$ be a function. Consider the family $\omega\_i$ of all open sets on $\mathbb{R}^N$ such that for each $i$, $f=0$ a.e. in $\omega\_i$, then $f=0$ a.e. on $\omega=\cup\omega\_i$ and we define the support of $f$ by $$\operatorname{supp}(f)=\mathbb{R}^N\setminus\omega$$ Suppose that $f,g\in C^\infty(\mathbb{R})\cap L^1(\mathbb{R})$. We can prove that $\operatorname{supp}(f\ast g)\subset\overline{\operatorname{supp}(f)+\operatorname{supp}(g)}$. Take any $x\in\mathbb{R}$ and note that $$(f\ast g)(x)=\int\_\mathbb{R}f(x-y)g(y)=\int\_{(x-\operatorname{supp}(f))\cap \operatorname{supp}(g)}f(x-y)g(y)$$ For $x\notin \operatorname{supp}(f)+\operatorname{supp}(g)$, we have that $(x-\operatorname{supp}(f))\cap \operatorname{supp}(g)=\emptyset$ and then $(f\ast g)(x)=0$. It follows that if $x\in (\operatorname{supp}(f) + \operatorname{supp}(g))^c$ then $$(f\ast g)(x)=0$$ Therefore $$\operatorname{supp}(f\ast g)\subset\overline{\operatorname{supp}(f)+\operatorname{supp}(g)}$$ Now let's prove that the equality is not necessary. Consider the functions in $\mathbb{R}$ defined by $f(x)=x\chi\_{[-1,1]}(x)$ and $g(x)=\chi\_{[-2,2]}(x)$, where $\chi\_A$ is the characteristic function of the set $A$. Note that in this case $\overline{\operatorname{supp}(f)+\operatorname{supp}( g)}=[-3,3]$, however, the interval $(-1,1)$ does not belong to the support of $f\star g$ (which is equal to $[-3,-1]\cup [1,3]$). Remark 1: The proof I gave here can be found in Brezis's book of Functional Analysis. Remark 2: I don't know a expliclty characterization of the support of the convolution, but by the given formula, you can see that if the two functions has compact support, then does the convolution. Update: I have corrected some errors in the text.
Reminder: The sum of two compact sets, e.g. K an the closed ball $M := B\_\varepsilon(0)$ is compact again, as it is the continuous image of a compact set $K \times M$ in the product domain. Therefore, if both supports are compact you can omit the closure on the right hand side.
11,787,043
I have an ActiveRecord and when i click on save all records are saved except the date. My contorller ``` class UsersController < ApplicationController def create puts params[:user] @user1 = User.new(params[:user]) if @user1.save saveduser = User.where("fbid = ?",params[:user][:fbid]) unless saveduser.first.nil? session[:user] = saveduser.first end puts "user saved " redirect_to "/users/dashboard" else puts "error while saving user" end end ``` The view ``` <h3>User Details</h3> <%= form_for(@user) do |f| %> <table> --some columns <tr> <td><%= f.label :state %></td> <td> <%= f.text_field :state %></td> </tr> <tr> <td><%= f.label :dob %></td> <td> <%= f.text_field :dob %></td> </tr> <%= f.hidden_field :fbid %> </table> <%= f.submit %> <% end %> <table> ``` In console when create method is called in UserController . I can see ``` {"username"=>"xxxx.xx.94", "firstname"=>"xxxx", "lastname"=>"Raxxstogi", "emaild"=>"xx.xxx@gmail.com", "city"=>"Los Angeles", "country"=>"USA", "state"=>"CA", "dob"=>"08/13/1983", "fbid"=>"xxx"} ``` My DB table column is `dob | date | YES | | NULL |` Where is it going wrong? Thanks
2012/08/02
[ "https://Stackoverflow.com/questions/11787043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/67476/" ]
Ruby doesn't understand your date format. You can fix this by explicitly parsing the date with [`Date::strptime`](http://www.ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/Date.html#method-c-strptime), perhaps in the model as a setter method: ``` class User < ActiveRecord::Base def dob=(date) date = Date.strptime(date, '%m/%d/%Y') if date.is_a?(String) write_attribute(:dob, date) end end ``` I would, however, second jordanpg's recommendation to use the date helpers in Rails, unless you know that the format will be the same every time.
it could be the problem with your date format. You can either configure active record to accept this format or convert your date param to Date object using strftime or something like it
73,362,668
I have an array (images\_lst) having shape (250,500,500), it is basically a list of 250 images having dimensions 500X500. How do I select only the first dimension of the array to use it in a loop given below ``` for n in images_lst: p=n print(p) #some other lines in the loop which works fine while p>=10: p+=1 sys.exit() #basically I want to exit the code after the 10th image ``` when I print p I get an array > > [[[19 18 27 ......88 90 84]]] > > > what I want to print is > > 0 1 2 ... 10 > > > Also, the while loop will not work here because the array has more than one element and is unable to perform the Boolean expression `p>=10`.
2022/08/15
[ "https://Stackoverflow.com/questions/73362668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15358982/" ]
The way to do it **efficiently** is to iterate over all combinations of the positions of the letters 'A', and for each such combination - iterate over all the ways *other letters* can be positioned, and just insert the 'A's there. **Be warned that with your inputs this will produce almost 3 million words!** On my machine it was printing the words for so long that I had to manually stop execution. So here is the smaller example: ```py letters = ['A', 'b', 'c'] num_As = 2 num_total = 4 from itertools import combinations, product for indices_A in combinations(range(num_total), num_As): for rest in product(letters[1:], repeat=num_total - num_As): rest = list(rest) for index_A in indices_A: rest.insert(index_A, 'A') print(''.join(rest)) ``` ```py AAbb AAbc AAcb AAcc AbAb AbAc AcAb AcAc AbbA AbcA AcbA AccA bAAb bAAc cAAb cAAc bAbA bAcA cAbA cAcA bbAA bcAA cbAA ccAA ```
First determine the two indices where the letter "A" will occur, then produce the letters at the other 8 indices: ``` from itertools import combinations, product def solve(): for i, j in combinations(range(10), 2): for b in map(list, product("BNME", repeat=8)): b.insert(i, "A") b.insert(j, "A") yield "".join(b) ``` To print: ``` for s in solve(): print(s) ``` ...but don't wait for it. There are 9\*10/2 \* 48 possible combinations, which is almost 3 million.
1,477,740
Using method: `System.IO.File.Create()` After the file gets created, it still remains used by a process, and I can't delete it. Any idea how I can better create the file, should be a 0byte file, and then somehow close and dispose?
2009/09/25
[ "https://Stackoverflow.com/questions/1477740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41543/" ]
JL, You should wrap your call to .Create in a using statement so that the FileStream that .Create returns will be closed properly. IE: ``` using (File.Create("path")){...} ```
nikmd23 has the short answer, the long answer is: the `FileStream` that `File.Create(...)` is returning is not being deterministically disposed of, therefore it's file handle is not closed when you're trying to delete it. As nikmd23 put it, wrapping your `File.Create(...)` call will with a `using` statement will make sure the stream is closed and disposed of: ``` using (FileStream fs = File.Create(path)) { // do anything with the stream if need-be... } File.Delete(path); //after it's been disposed of. ``` The `using(...)` block is really just compiler-sugar for: ``` FileStream fs = File.Create(path); try { // do anything with the stream if need-be... } finally { fs.Dispose(); } File.Delete(path) ```
108
As per [The 7 Essential Meta Questions of Every Beta](http://blog.stackoverflow.com/2010/07/the-7-essential-meta-questions-of-every-beta/), we should decide on a good FAQ. This will grow organically, but IMO, it deserves its own question. Right now, [this is what we have](https://ux.stackexchange.com/faq). As I opined (loudly) [in this question](https://ux.meta.stackexchange.com/questions/53/open-ended-discussion-questions-another-take), this passage is a bit poisonous: > > Avoid asking questions that are > subjective, argumentative, or require > extended discussion. This is not a > discussion board, this is a place for > questions that can be answered! > > > I think we should also update the top *What kind of questions can I ask here?* section (see [StackOverflow's FAQ](https://stackoverflow.com/faq) -- it's quite a bit longer there) to include the limits we decide on in [other meta questions](https://ux.meta.stackexchange.com/questions/100/implementation-specific-questions) (though it should still be short & succinct). Otherwise, I think the template looks good as-is.
2010/08/26
[ "https://ux.meta.stackexchange.com/questions/108", "https://ux.meta.stackexchange.com", "https://ux.meta.stackexchange.com/users/114/" ]
The FAQ has been updated, but let's continue to evolve it by editing and commenting on this question. > > ### What makes a good question? > > > Prefer questions that elicit > definitive answers or solutions rather > than prolonged discussions. Remember, > this a Q&A site, not a discussion > board. > > > More context yields better answers. Fill your question with details such as: > > > * Description of the users' experience levels and goals > * Mockups, screenshots, or photos of existing designs > * Software platform, if applicable (Is it an Android app? A web form? A kiosk with a 20"×20" touch screen?) > > > If you're familiar with other Stack Exchange sites, questions on UX tend to be a little more subjective than usual. That's okay, as long as the question follows the guidelines outlined in [Good Subjective, Bad Subjective](http://blog.stackoverflow.com/2010/09/good-subjective-bad-subjective/). > > > Feedback is still much appreciated.
I think we should pull from this great post on the SE blog <http://blog.stackoverflow.com/2010/09/good-subjective-bad-subjective/> In summary we could write: > > What makes a good question? > --------------------------- > > > 1. Questions inspire answers that explain “why” and “how”. > 2. Questions tend to have long, not short, answers. > 3. Questions have a constructive, fair, and impartial tone. > 4. Questions invite sharing experiences over opinions. > 5. Questions insist that opinion be backed up with facts and > references. > 6. Questions are more than just mindless social fun. > > >
46,941,498
I've been through itertools inside and out and I cannot figure out how to do the following. I want to take a list. `x = [1,2,3,4,5,6,7,8]` and I want to get a new list: ``` y = [[1],[1,2],[1,2,3],.......[2],[2,3],[2,3,4].....[8]] ``` I need a list of all slices, but not combinations or permutations. `x = list(zip(x[::2], x[1::2]))` is close, but doesn't do exactly what I'm hoping
2017/10/25
[ "https://Stackoverflow.com/questions/46941498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2843275/" ]
You can utilize list comprehension if you insist on a one-liner: ``` > x=[1,2,3,4] > [x[a:b+1] for a in range(len(x)) for b in range(len(x)) if a<=b] ``` > > [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]] > > > Or you can even get rid of that `if`: ``` > [x[a:b+1] for a in range(len(x)) for b in range(a, len(x))] ```
I think this is a good aproach, an iterative way, I could understand it well: ``` lst = [1,2,3,4,5,6,7,8] res = [] ln= len(lst) for n in range(ln): for ind in range(n+1, ln+1): res.append(lst[n:ind]) ```
5,221,270
I'm making my own forum software. Well its normal to have smileys in your forum. So i made an array with all the smileys and putted them in a function: ``` function si_ubb($string){ $smileys = array( '0<:)' => 'angelnot.gif', '>:(' => 'angry.gif', ':@' => 'blush.gif', ':*' => 'cencored.png', ':?' => 'confused.gif', ';(' => 'cry.png', ':D' => 'grin.gif', ':)' => 'happy.gif', ':|' => 'hmm.png', '0:)' => 'hypocrite.gif', ':x:' => 'lock.gif', '<3' => 'love.gif', '8)' => 'rolleyes.gif', ':(' => 'sad.png', '|)' => 'shifty.gif', 'O_o' => 'shock.gif', '8)' => 'sunglasses.gif', '^_^' => 'sweatingbullets.gif', ':p' => 'tongue.gif', ':P' => 'tongue.gif', ';)' => 'wink.gif', '>.<' => 'wry.gif', 'XD' => 'wry.gif', 'xD' => 'wry.gif' ); foreach($smileys as $code => $image){ $string = str_replace($code, $image, $string); } return $string; } ``` But, ehm, when i do this now: `echo si_ubb('0<:)');` It gives this? 0<![Image](https://i.stack.imgur.com/0D9dk.gif) But how? And why? Why isn't it showing the right smiley? Greetings
2011/03/07
[ "https://Stackoverflow.com/questions/5221270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/528370/" ]
``` ':)' => 'happy.gif' ``` You have already on case. Your `0<:)` is part of `:)`. After first replacement you get `0<happy.gif` You'll get same issue with `':(' => 'sad.png'`
Like Michiel said. It does a 'non-greedy' replace. You might want to read up on greedy-regexp's (@see preg\_replace)
62,374,331
I need some help with converting an MS Access table with data in Rows into Columns. Created some sample data table that suits my scenario. I need to convert "**Table 1**" to "**Table 3**". If possible using the "**Table 2**" to identify the column order of the Fruits. [![enter image description here](https://i.stack.imgur.com/n4Azp.png)](https://i.stack.imgur.com/n4Azp.png) I think this can be done using Pivot option in SQL Server. How can I achieve the same in Access Database? Thanks.
2020/06/14
[ "https://Stackoverflow.com/questions/62374331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4939564/" ]
I would not use multiple `setInterval` just one should do... Here is an example: ```js var paper = document.getElementById('paper'); var brush = paper.getContext('2d'); var y = 100; var speed = 1; function draw() { if ((y < 10) || (y > 150)) { speed *= -1 } y += speed brush.clearRect(0, 0, 160, 300); brush.fillRect(10, y, 10, 10); } function play() { setInterval(draw, 10); } draw() ``` ```html <canvas height="160" width="300" id="paper" onclick="play()"></canvas> ``` In your code, both intervals are running simultaneously that could create the strange behavior you are seeing where the object is lagging and taking more time to go up but coming down is fine. Instead of the two `setInterval` I introduced the variable `speed` that will determine the direction of the movement and we will "flip" it `speed *= -1` when the position exceeds our boundaries ... with this pattern in your canvas animation it's easy to transition to `requestAnimationFrame` if performance becomes critical, but for simple practice code like this, setInterval works fine.
For animations running smoothly on the browser, you should really use a requestAnimationFrame loop instead of setInterval checkout the example here: <https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations> here is why: [Why is requestAnimationFrame better than setInterval or setTimeout](https://stackoverflow.com/questions/38709923/why-is-requestanimationframe-better-than-setinterval-or-settimeout#:~:text=The%20question%20is%20most%20simply,or%20completely%20remove%20frame%20skips).
66,123,643
**UPDATE** This works in the snippet example with the var data array, when I try to implement it into my REST example, nothing is populating the html list. I am going to move the working example to a fiddle and update the snippet with the implementation that isn't working. Fiddle (working hard coded array): <https://jsfiddle.net/v24kagL8/> I am searching through my data by WeekOf variable which is a date/time SharePoint column. In this example the date format is YYYY-MM-DD. Here is a test case: Everything on load is shown. Once the search bar is utilized, and the right date is entered, the values correlated with that date appear. When the search bar is cleared, no data is populated and I want that to work. **UPDATED SNIPPET WITH FETCH** In @freedomn-m's answer, the fix was this which works, but when I implement, nothing populates ``` $("#myInput").on("keyup", function() { var value = $(this).val().toLowerCase(); $('#under_txt').text(value); if (value == "") { $("li").fadeIn(); } else { $('li').fadeOut(10); $('[data-weekof=' + value + ']').fadeIn(); } }); ``` Here is my updated JS which is not working: ``` function loadData(url) { url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('WeeklyReport')/items?$select=DeliverablesSubmitted,MajorTasks,UpcomingTasks,UpcomingDeliverables,PersonnelActions,SupportRequest,ResourceRequest,Team/Value,Training,Upcoming,WeekOf,TravelODC"; return fetch(url, { headers: { accept: "application/json; odata=verbose" } }) // make request .then((r) => { if (!r.ok) throw new Error("Failed: " + url); // Check for errors return r.json(); // parse JSON }) .then((data) => data.d.results); } loadData() .then((results) => { let data = results; var listContent = ''; console.log(data); for (var i = 0; i < data.length; i++) { var currData = data[i]; listContent += '<li class="test" data-weekOf="'+currData.WeekOf.split("T")[0]+'">'; console.log(currData.WeekOf.split("T")[0]); if(currData.Team !== null){ listContent += '<h2>' + currData.Team.results.join(', ') +'</h2>'; }else{ listContent += '<h2>' + "Null" +'</h2>'; } if(currData.MajorTasks !== null){ listContent += '<h4> Major Tasks Completed </h4>'; listContent += '<ul>' + "- " + currData.MajorTasks.replace(/(<([^>]+)>)/gi, "") + '</ul>'; }else{ } if(currData.DeliverablesSubmitted !== null){ listContent += '<h4> Deliverables Submitted</h4>'; listContent += '<ul>' + "- " + currData.DeliverablesSubmitted.replace(/(<([^>]+)>)/gi, "") + '</ul>'; }else{ } if(currData.UpcomingTasks !== null){ listContent += '<h4> Upcoming Tasks</h4>'; listContent += '<ul>' + "- " + currData.UpcomingTasks.replace(/(<([^>]+)>)/gi, "") + '</ul>'; }else{ } if(currData.UpcomingDeliverables !== null){ listContent += '<h4> Upcoming Deliverables</h4>'; listContent += '<ul>' + "- " + currData.UpcomingDeliverables.replace(/(<([^>]+)>)/gi, "") + '</ul>'; }else{ } if(currData.PersonnelActions !== null){ listContent += '<h4> Personnel Actions </h4>'; listContent += '<ul>' + "- " + currData.PersonnelActions.replace(/(<([^>]+)>)/gi, "") + '</ul>'; }else{ } if(currData.Upcoming !== null){ listContent += '<h4> Upcoming G3G Events </h4>'; listContent += '<ul>' + "- " + currData.Upcoming.replace(/(<([^>]+)>)/gi, "") + '</ul>'; }else{ } listContent += '</li>'; } $('#report-summary').html(listContent); $('#under_txt').text(' '); }); $(document).ready(function(){ loadData(); }); $("#myInput").on("keyup", function() { var value = $(this).val().toLowerCase(); $('#under_txt').text(value); if (value == "") { $("li").fadeIn(); } else { $('li').fadeOut(10); $('[data-weekof=' + value + ']').fadeIn(); } }); function sortNewestFirst(){ var elements = $('[data-weekOf]'); elements.sort(function (a, b) { return new Date($(b).attr('data-weekOf')) - new Date($(a).attr('data-weekOf')); }); $('#report-summary').html(elements); } function sortOldestFirst(){ var elements = $('[data-weekOf]'); elements.sort(function (a, b) { return new Date($(a).attr('data-weekOf')) - new Date($(b).attr('data-weekOf')); }); $('#report-summary').html(elements); } $('a.printPage').click(function(){ $('.container').show(); window.print(); return false; }); ```
2021/02/09
[ "https://Stackoverflow.com/questions/66123643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13983399/" ]
Add a check for `value==""` then show all rather than filter to none: ``` $("#myInput").on("keyup", function() { var value = $(this).val().toLowerCase(); $('#under_txt').text(value); if (value == "") { $("li").fadeIn(); } else { $('li').fadeOut(10); $('[data-weekof=' + value + ']').fadeIn(); } }); ``` Updated snippet ```js var data = [ { "Team": "Eagles", "WeekOf": "2021-01-31", "Tasks": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "Deliverables": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "Actions": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "Billable": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "NonBillable": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "UpcomingEvents": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "Training": null, "Resource": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", "Support": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." }, { "Team": "Raiders", "WeekOf": "2021-01-31", "Tasks": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "Deliverables": null, "Actions": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "Billable": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "NonBillable": null, "UpcomingEvents": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "Training": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "Resource": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", "Support": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." }, { "Team": "Vikings", "WeekOf": "2021-03-30", "Tasks": null, "Deliverables": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "Actions": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "Billable": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "NonBillable": null, "UpcomingEvents": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "Training": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "Resource": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", "Support": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." } ]; function onSuccess(data) { console.log("onsuccess") var listContent = []; for (var i = 0; i < data.length; i++) { listContent += '<li data-weekof="'+data[i].WeekOf+'">'; listContent += '<h2>' + data[i].Team +'</h2>'; listContent += '<h4> Tasks </h4>'; if(data[i].Tasks !== null){ listContent += '<ul>' + "- " + data[i].Tasks + '</ul>'; }else{ listContent += '<ul>' + "- There were no notes attached to this section." + '</ul>'; } listContent += '<h4> Deliverables </h4>'; if(data[i].Deliverables !== null){ listContent += '<ul>' + "- " + data[i].Deliverables + '</ul>'; }else{ listContent += '<ul>' + "- There were no notes attached to this section." + '</ul>'; } listContent += '<h4> Personnel Actions </h4>'; if(data[i].Actions !== null){ listContent += '<ul>' + "- " + data[i].Actions + '</ul>'; }else{ listContent += '<ul>' + "- There were no notes attached to this section." + '</ul>'; } listContent += '<h4> Finance (Billable) </h4>'; if(data[i].Billable !== null){ listContent += '<ul>' + "- " + data[i].Billable + '</ul>'; }else{ listContent += '<ul>' + "- There were no notes attached to this section." + '</ul>'; } listContent += '<h4> Finance (Non-Billable) </h4>'; if(data[i].NonBillable !== null){ listContent += '<ul>' + "- " + data[i].NonBillable + '</ul>'; }else{ listContent += '<ul>' + "- There were no notes attached to this section." + '</ul>'; } listContent += '<h4> Upcoming Events </h4>'; if(data[i].UpcomingEvents !== null){ listContent += '<ul>' + "- " + data[i].UpcomingEvents + '</ul>'; }else{ listContent += '<ul>' + "- There were no notes attached to this section." + '</ul>'; } listContent += '<h4> Training </h4>'; if(data[i].Training !== null){ listContent += '<ul>' + "- " + data[i].Training + '</ul>'; }else{ listContent += '<ul>' + "- There were no notes attached to this section." + '</ul>'; } listContent += '<h4> Resource Request </h4>'; if(data[i].Resource !== null){ listContent += '<ul>' + "- " + data[i].Resource + '</ul>'; }else{ listContent += '<ul>' + "- There were no notes attached to this section." + '</ul>'; } listContent += '<h4> Support Request </h4>'; if(data[i].Support !== null){ listContent += '<ul>' + "- " + data[i].Support + '</ul>'; }else{ listContent += '<ul>' + "- There were no notes attached to this section." + '</ul>'; } listContent += '</li>'; } $('#report-summary').html(listContent); $('#under_txt').text(' '); } $(document).ready(function(){ onSuccess(data); }); $(document).ready(function(){ $("#myInput").on("keyup", function() { var value = $(this).val().toLowerCase(); $('#under_txt').text(value); if (value == "") { $("li").fadeIn(); } else { $('li').fadeOut(10); $('[data-weekof=' + value + ']').fadeIn(); } }); }); function sortNewestFirst(){ var elements = $('[data-weekOf]'); elements.sort(function (a, b) { return new Date($(b).attr('data-weekOf')) - new Date($(a).attr('data-weekOf')); }); $('#report-summary').html(elements); } function sortOldestFirst(){ var elements = $('[data-weekOf]'); elements.sort(function (a, b) { return new Date($(a).attr('data-weekOf')) - new Date($(b).attr('data-weekOf')); }); $('#report-summary').html(elements); } ``` ```css h2{ text-align: left; text-decoration: underline; font-size: 20px; } h1{ font-size: 25px; text-align: center; } ul { list-style-type: none; padding: 0px; margin-left: 0px; } li{ list-style-type: none; } span{ font-size: 15px; } #report-summary{ margin-left: 15px; margin-right: 15px; } #search{ text-align: center; } p { text-align: center; } h4{ font-size: 17px; font-weight: normal; text-decoration: underline; margin-top: -10px; margin-bottom: -10px; } #myInput{ text-align: center; } #under_txt{ margin-left: 5px; padding: 0px 10px 0px 10px; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link type="text/css" media="all" rel="stylesheet"> <div class="container"> <div id="search"> <input id="myInput" type="text" placeholder="Search for Week Of"> </div> <h1> Weekly Manager Report </h1> <p>Week Of<span id="under_txt"></span></p> <div id="report-summary"> </div> </div> ```
I dunno if you want to keep the last data displayed when cleared or the data displayed at the initialization: here i display the initialization data when `value ==''` You just relaunch Onsuccess(data) when you clear input: ```js var data = [ { "Team": "Eagles", "WeekOf": "2021-01-31", "Tasks": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "Deliverables": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "Actions": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "Billable": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "NonBillable": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "UpcomingEvents": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "Training": null, "Resource": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", "Support": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." }, { "Team": "Raiders", "WeekOf": "2021-01-31", "Tasks": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "Deliverables": null, "Actions": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "Billable": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "NonBillable": null, "UpcomingEvents": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "Training": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "Resource": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", "Support": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." }, { "Team": "Vikings", "WeekOf": "2021-03-30", "Tasks": null, "Deliverables": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "Actions": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "Billable": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "NonBillable": null, "UpcomingEvents": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "Training": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "Resource": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", "Support": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." } ]; function onSuccess(data) { var listContent = []; for (var i = 0; i < data.length; i++) { listContent += '<li data-weekOf="'+data[i].WeekOf+'">'; listContent += '<h2>' + data[i].Team +'</h2>'; listContent += '<h4> Tasks </h4>'; if(data[i].Tasks !== null){ listContent += '<ul>' + "- " + data[i].Tasks + '</ul>'; }else{ listContent += '<ul>' + "- There were no notes attached to this section." + '</ul>'; } listContent += '<h4> Deliverables </h4>'; if(data[i].Deliverables !== null){ listContent += '<ul>' + "- " + data[i].Deliverables + '</ul>'; }else{ listContent += '<ul>' + "- There were no notes attached to this section." + '</ul>'; } listContent += '<h4> Personnel Actions </h4>'; if(data[i].Actions !== null){ listContent += '<ul>' + "- " + data[i].Actions + '</ul>'; }else{ listContent += '<ul>' + "- There were no notes attached to this section." + '</ul>'; } listContent += '<h4> Finance (Billable) </h4>'; if(data[i].Billable !== null){ listContent += '<ul>' + "- " + data[i].Billable + '</ul>'; }else{ listContent += '<ul>' + "- There were no notes attached to this section." + '</ul>'; } listContent += '<h4> Finance (Non-Billable) </h4>'; if(data[i].NonBillable !== null){ listContent += '<ul>' + "- " + data[i].NonBillable + '</ul>'; }else{ listContent += '<ul>' + "- There were no notes attached to this section." + '</ul>'; } listContent += '<h4> Upcoming Events </h4>'; if(data[i].UpcomingEvents !== null){ listContent += '<ul>' + "- " + data[i].UpcomingEvents + '</ul>'; }else{ listContent += '<ul>' + "- There were no notes attached to this section." + '</ul>'; } listContent += '<h4> Training </h4>'; if(data[i].Training !== null){ listContent += '<ul>' + "- " + data[i].Training + '</ul>'; }else{ listContent += '<ul>' + "- There were no notes attached to this section." + '</ul>'; } listContent += '<h4> Resource Request </h4>'; if(data[i].Resource !== null){ listContent += '<ul>' + "- " + data[i].Resource + '</ul>'; }else{ listContent += '<ul>' + "- There were no notes attached to this section." + '</ul>'; } listContent += '<h4> Support Request </h4>'; if(data[i].Support !== null){ listContent += '<ul>' + "- " + data[i].Support + '</ul>'; }else{ listContent += '<ul>' + "- There were no notes attached to this section." + '</ul>'; } listContent += '</li>'; } $('#report-summary').html(listContent); $('#under_txt').text(' '); } $(document).ready(function(){ onSuccess(data); }); $(document).ready(function(){ $("#myInput").on("keyup", function() { var value = $(this).val().toLowerCase(); if($.trim(value)==''){ onSuccess(data); return; } $('#under_txt').text(value); $('li').fadeOut(10); var test = $('[data-weekOf='+value+']'); console.log(test); if(test.length == 0) return; $('[data-weekOf='+value+']').fadeIn(); }); }); function sortNewestFirst(){ var elements = $('[data-weekOf]'); elements.sort(function (a, b) { return new Date($(b).attr('data-weekOf')) - new Date($(a).attr('data-weekOf')); }); $('#report-summary').html(elements); } function sortOldestFirst(){ var elements = $('[data-weekOf]'); elements.sort(function (a, b) { return new Date($(a).attr('data-weekOf')) - new Date($(b).attr('data-weekOf')); }); $('#report-summary').html(elements); } ``` ```css h2{ text-align: left; text-decoration: underline; font-size: 20px; } h1{ font-size: 25px; text-align: center; } ul { list-style-type: none; padding: 0px; margin-left: 0px; } li{ list-style-type: none; } span{ font-size: 15px; } #report-summary{ margin-left: 15px; margin-right: 15px; } #search{ text-align: center; } p { text-align: center; } h4{ font-size: 17px; font-weight: normal; text-decoration: underline; margin-top: -10px; margin-bottom: -10px; } #myInput{ text-align: center; } #under_txt{ margin-left: 5px; padding: 0px 10px 0px 10px; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link type="text/css" media="all" rel="stylesheet"> <div class="container"> <div id="search"> <input id="myInput" type="text" placeholder="Search for Week Of"> </div> <h1> Weekly Manager Report </h1> <p>Week Of<span id="under_txt"></span></p> <div id="report-summary"> </div> </div> ```
16,282,219
I'm beginner in Excel VBA and your help is much appreciated. Please advice how can I create a common function to Open and database connection, and another function to close it, to avoid duplication of coding? --- Here is my code. I'm stuck on how to move on... ``` Const connection_string As String = "Provider=SQLOLEDB.1;Password=XXX;Persist Security `Info=True;User ID=sa;Initial Catalog=TESTDB;Data Source=XXXX;" Sub DuplicateDBConnection() 'Declare variables Set cn1 = New ADODB.Connection Set cmd1 = New ADODB.Command Set rs1 = New ADODB.Recordset 'Open Connection cn1.ConnectionString = connection_string cn1.Open 'Set and Excecute SQL Command Set cmd1.ActiveConnection = cn1 cmd1.CommandText = "Select stock_code, name, sector_id from stock_master" cmd1.CommandType = adCmdText cmd1.Execute 'Open Recordset Set rs1.ActiveConnection = cn1 rs1.Open cmd1 'Copy Data to Excel ActiveSheet.Range("A1").CopyFromRecordset (rs1) 'Close Connection rs1.Close cn1.Close 'Throw Object Set rs1 = Nothing Set cn1 = Nothing End Sub ``` --- My wish is to write common functions so that I don't need to keep writing code to connect and close connection. ``` Sub ConnectDB() 'Codes to connect DB End Sub Sub CloseConnnection() 'Codes to close connection End Sub Sub ExecuteCode() ConnectDB 'Execute SQL command to manipulate data on excel and SQL database CloseConnection End Sub ``` --- Edit based on Kittoe's suggestions and works properly now. Thanks! 1. Class: a. Created a class called AdoDbHelper, Private Instancing b. In AdoDbHelper, change "Option Compare Database" to "Option Compare Text" 2. Module: Create a function like this. Code below: ``` Const connection_string As String = "Provider=SQLOLEDB.1;Password=XXX;Persist Security `Info=True;User ID=sa;Initial Catalog=TESTDB;Data Source=XXXX;" Sub Test() Dim sourceDb As New AdoDbHelper Dim sourceRs As New ADODB.Recordset sourceDb.Connect (connection_string) Set sourceRs = sourceDb.OpenRecordset("Select stock_code, name, sector_id from stock_master") With sourceRs 'Do stuff! ActiveSheet.Range("A1").CopyFromRecordset sourceRs .Close End With sourceDb.Disconnect Set sourceRs = Nothing Set sourceDb = Nothing End Sub ```
2013/04/29
[ "https://Stackoverflow.com/questions/16282219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2294485/" ]
This type of stuff is best done in a class. Right click your VBA project in the "IDE" and go to Insert -> Class Module. Name your class something meaningful like clsAdoHelper (if Hungarian Notation is your thing), AdoDbHelper, or something. The following is an example of the code you'd put in this class: ``` Option Compare Database Option Explicit Private WithEvents conn As ADODB.Connection Private WithEvents rs As ADODB.Recordset Public Sub Connect(ConnectionString As String) If Not conn Is Nothing Then Debug.Print "A connection is already open." Exit Sub End If If ConnectionString = CurrentProject.Connection.ConnectionString Then Set conn = CurrentProject.Connection Else Set conn = New ADODB.Connection conn.Open ConnectionString End If End Sub Public Sub Disconnect() If Not conn Is Nothing Then If conn.State <> 0 Then conn.Close End If Set conn = Nothing End If End Sub Public Sub Execute(SQL As String) If conn Is Nothing Then Debug.Print "No connection open." Exit Sub End If conn.Execute (SQL) End Sub Public Function OpenRecordset(SQL As String, Optional CursorLocation As ADODB.CursorLocationEnum = adUseClient, Optional CursorType As ADODB.CursorTypeEnum = adOpenForwardOnly, Optional LockType As ADODB.LockTypeEnum = adLockReadOnly) As ADODB.Recordset If conn Is Nothing Then Debug.Print "No connection open." Exit Function End If If Not rs Is Nothing Then Debug.Print "A recordset is already open." Exit Function End If Set rs = New ADODB.Recordset With rs .CursorLocation = CursorLocation .CursorType = CursorType .LockType = LockType .Open SQL, conn End With Set OpenRecordset = rs End Function Public Sub BeginTransaction() conn.BeginTrans End Sub Public Sub CommitTransaction() conn.CommitTrans End Sub Public Sub RollbackTransaction() conn.RollbackTrans End Sub Private Sub conn_BeginTransComplete(ByVal TransactionLevel As Long, ByVal pError As ADODB.Error, adStatus As ADODB.EventStatusEnum, ByVal pConnection As ADODB.Connection) Debug.Print "Transaction started." End Sub Private Sub conn_CommitTransComplete(ByVal pError As ADODB.Error, adStatus As ADODB.EventStatusEnum, ByVal pConnection As ADODB.Connection) Debug.Print "Transaction committed." End Sub Private Sub conn_ConnectComplete(ByVal pError As ADODB.Error, adStatus As ADODB.EventStatusEnum, ByVal pConnection As ADODB.Connection) End Sub Private Sub conn_Disconnect(adStatus As ADODB.EventStatusEnum, ByVal pConnection As ADODB.Connection) End Sub Private Sub conn_ExecuteComplete(ByVal RecordsAffected As Long, ByVal pError As ADODB.Error, adStatus As ADODB.EventStatusEnum, ByVal pCommand As ADODB.Command, ByVal pRecordset As ADODB.Recordset, ByVal pConnection As ADODB.Connection) Debug.Print "SQL execution complete." End Sub Private Sub conn_RollbackTransComplete(ByVal pError As ADODB.Error, adStatus As ADODB.EventStatusEnum, ByVal pConnection As ADODB.Connection) Debug.Print "Transaction rolled back." End Sub ``` **Using your new class:** ``` Dim sourceDb As New AdoDbHelper Dim sourceRs as New ADODB.Recordset sourceDb.Connect (<insert connection string here>) Set sourceRs = sourceDb.OpenRecordSet(<insert SQL string here>) With sourceRs 'Do stuff! .Close End With sourceDb.Disconnect Set sourceRs = Nothing Set sourceDb = Nothing ``` It's not exactly the best code I've ever written but it should give you a decent start. If you have trouble understanding how the class works I encourage you to do a little research on OOP and classes in VBA. You'll notice that you still have a little bit of necessary biolerplate code here but the bulk of the normal work has been taken care of for you in the class methods. If you wanted to put the data manipulation logic into a function of it's own you could pass it the ADODB.Recordset object that you create using the class (this would replace the `WITH` blocks). I wouldn't suggest polluting the class with such logic as you want the class to handle all of your generic connect/disconnect/exception handling for any possible ADODB connections. That way you can reuse it in other projects =D.
Use the Microsoft ActiveX Data Objects Library x.x: In your VBA window go to Tools> References > Microsoft ActiveX Data Objects Library x.x I usually use 2.7 for downward compatibility. Now you can create ADODB objects to open connections, perform queries (select/update/delete/...) and use the query results (called record sets) to the rest of your excel, into tables, in specific cells. To be sure to use the same connection all the time, create a Public connection object and refer to that in all your subroutines. In each subroutine first check if it is already set up by (`conn` being my `ADODB.Connection` object): ``` If conn = Nothing Then Call Setup_Connection ``` And the Subroutine Setup\_Connection being something like: ``` Private Sub Setup_Connection Dim strConnection as String If conn = Nothing Then 'Choose your own database connection details strConnection = "Provider=SQLOLEDB.1;Integrated Security=SSPI;" & _ "Persist Security Info=False;" & _ "Initial Catalog=DatabaseName;" & _ "Data Source=DATABASESERVER" Set conn = New ADODB.Connection With conn .Open strConnection .CommandTimeout = 30 End With End If End Sub ```
15,107,553
I have been using SOAP UI Tool to test my web service for Schema Compliance. I would like to export the Schema Compliance failures to an Excel or Text File. Is there a possible way to do this? Thanks
2013/02/27
[ "https://Stackoverflow.com/questions/15107553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1129805/" ]
In C++11 you have the option of initializing non static member variables at the point of declaration: ``` class A{ public: A(); private: std::string a = "a"; // curly braces allowed too: std::string a{"a"}; }; ``` C++11 also adds delegating constructors, so you can call a class' constructor from other constructors. This allows you to initialize `a` in only one place: ``` #include <iostream> #include <string> struct Foo { Foo() : a("Hello, Foo!") {} Foo(int) : Foo() {} Foo(int, int) : Foo() {} std::string a; }; int main() { Foo f1(42); Foo f2 (1,2); std::cout << f1.a << "\n"; std::cout << f2.a << "\n"; } ``` Otherwise, use the constructor initialization list as suggested in the other answer: ``` class A{ public: A() : a("a") {} private: std::string a; }; ```
You initialize it in the class constructors [*initializer list*](http://en.cppreference.com/w/cpp/language/initializer_list): ``` A::A() : a("a") { } ```
10,030,505
I am working on a mathematical problem that has the advantage of being able to "pre-compute" about half of the problem, save this information to file, and then reuse it many times to compute various 'instances' of my problem. The difficulty is that uploading all of this information in order to solve the actual problem is a major bottleneck. More specifically: I can pre-compute a huge amount of information - tons of probabilities (`long double`), a ton of `std::map<int,int>`, and much more - and save all this stuff to disk (several Gb). The second half of my program accepts an input argument *D*. For each *D*, I need to perform a great many computations that involve a combination of the pre-computed data (from file), and some other data that are specific to *D* (so that the problem is different for each *D*). Sometimes I will need to pick out certain pieces of pre-computed information from the files. Other times, I will need to upload every piece of data from a (large) file. Are there any strategies for making the IO faster? I already have the program parallelized (MPI, via `boost::mpi`) for other reasons, but regardless, accessing files on the disk is making my compute time unbearable. Any strategies or optimizations? Currently I am doing everything with `cstdio`, i.e. no `iostream`. Will that make a big difference?
2012/04/05
[ "https://Stackoverflow.com/questions/10030505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1023645/" ]
It really depends on how much memory is available and what the access pattern is. --- The simplest solution is to use memory mapped files. This generally requires that the file has been layed out as if the objects were in memory, so you will need to only use POD data with no pointers (but you can use relative indexes). You need to study your access pattern to see if you can group together the values that are often used together. This will help the OS in better caching those values (ie, keeping them in memory for you, rather than always going to the disk to read them). --- Another option will be to split the file into several chunks, preferably in a logical way. It might be necessary to create an index file that map a range of values to the file that contain them. Then, you can only access the set of files required. --- Finally, for complex data structures (where memory mapped files fail) or for sparse reading (when you only ever extract only a small piece of information from a given file), it might be interesting to read about LRU caches. The idea will be to use *serialization* and *compression*. You write several files, among which an index, and compress all of them (zip). Then, at launch time, you start by loading the index and save it in memory. Whenever you need to access a value, you first try your cache, if it is not it, you access the file that contains it, decompress it in memory, dump its content in your cache. *Note: if the cache is too small, you have to be picky about what you dump in... or reduce the size of the files.* The frequently accessed values will stay in cache, avoiding unnecessary round-trip, and because the file is zipped there will be less IO.
> > More specifically: I can pre-compute a huge amount of information - tons of probabilities (long double), a ton of std::map, and much more - and save all this stuff to disk (several Gb). > > > Don't reinvent the wheel. I'd suggest using a key-value data store, such as berkeley db: <http://docs.oracle.com/cd/E17076_02/html/gsg/C/concepts.html> This will enable saving and sharing the files, caching the parts you actually use a lot and keeping other parts on disk.
47,815,232
Assume I have two classes A and B. ``` Class A{ public String methodA(String name) { B b = new B(); b.methodB(name); } } Class B{ public String methodB(String name) { return name+name; } } ``` Now I want to mock methodA which has a nested method call to Class B.I have tried writing the below TestCase but getting **methodNotImplementedException**. ``` @Test public void testCase() { A a = new A(); B b = PowerMock.createPartialMock(B.class, "methodB"); EasyMock.expect(b.methodB(anyString())).andReturn("HELLO PTR"); PowerMock.replayAll(); String result = a.methodA("hello ptr"); assertEquals(result, "HELLO PTRHELLO PTR"); PowerMock.verifyAll(); } ``` Can anybody tell how to solve nested method calls using PowerMock..?? Thanx in advance
2017/12/14
[ "https://Stackoverflow.com/questions/47815232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5453286/" ]
Several issues here. First, don't use two mocking frameworks at the same time. There's no reason to expect when creating expectations in one framework, that the other would know about it. Second, if, as stated, you want to mock `methodA`, supposedly as a part of a test of something that uses `A`, then there's no reason to mock anything from `B`, since the result of `methodA` is mocked, and will not invoke `B`. Third, [mock roles, not objects](http://www.jmock.org/oopsla2004.pdf). Meaning, if object `C` accepts an `A`, it shouldn't get the concrete implementation, instead it should get the interface it uses. Then in the test, you mock that interface, not a class. Given these, if you create an interface for `A`, and stub the response from that interface, your test will be much simpler, and you won't have to resort to these kinds of tools.
If you want to mock `methodA` then there is no need to do anything with class B. Just do ``` @Test public void testCase() { A a = mock(A.class); expect(a.methodA()).andReturn("HELLO"); replay(a); // use the mock to test something String result = a.methodA("hello ptr"); assertEquals(result, "HELLO"); verify(a); } ``` But it looks like you want to test A and mock B. That's different. First, I would recommend refactoring. Even a really basic one like ``` public class A{ public String methodA(String name) { B b = newB(); b.methodB(name); } protected B newB() { return new B() } } ``` That way, you won't need PowerMock at all. You can do ``` @Test public void testCase() { A a = partialMockBuilder().addMockedMethod("newB").mock(A.class); B b = mock(B.class); expect(a.newB()).andReturn(b); expect(b.methodB()).andReturn("HELLO"); replay(a, b); String result = a.methodA("HI"); assertEquals(result, "HELLO"); verify(a, b); } ``` And then, if you really need for some weird reason to mock `new B()`, yes, using `Powermock.expectNew` is the solution.
26,478,687
I keep seeing CSS with ``` content:""; ``` but often, there's nothing in the quotations. What's the purpose for this?
2014/10/21
[ "https://Stackoverflow.com/questions/26478687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3321223/" ]
Defining `content`, even empty, is a requirement if you want CSS applied to the `:before` or `:after` selectors to work. ```css div:after { display: block; width: 20px; height: 20px; background: red; } div#withcontent:after { content: ''; } ``` ```html <div></div> <div id="withcontent"></div> ```
"Content" is needed for pseudo elements like `::before` and `::after`. It is set to `''` when no text content is desired, such as when the element is used just as a vanilla container for styling. <https://developer.mozilla.org/en-US/docs/Web/CSS/content>
60,132,617
Let's say that we have a random number generator that can generate random 32 or 64 bit integers (like [rand.Rand](https://golang.org/pkg/math/rand/#Rand) in the standard library) Generating a random int64 in a given range `[a,b]` is fairly easy: ``` rand.Seed(time.Now().UnixNano()) n := rand.Int63n(b-a) + a ``` Is it possible to generate random 128 bit decimal (as defined in specification IEEE 754-2008) in a given range from a combination of 32 or 64 bit random integers?
2020/02/09
[ "https://Stackoverflow.com/questions/60132617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6858274/" ]
Possible, but by no means easy. Here is a sketch of a solution that might be acceptable — writing and debugging it would probably be at least a day of concerted effort. Let `min` and `max` be [primitive.Decimal128](https://godoc.org/go.mongodb.org/mongo-driver/bson/primitive#Decimal128) objects from go.mongodb.org/mongo-driver/bson. Let `MAXBITS` be a multiple of 32; 128 is likely to be adequate. 1. Get the significand (as big.Int) and exponent (as int) of `min` and `max` using the `BigInt` method. 2. Align min and max so that they have the same exponent. As far as possible, left-justify the value with the larger exponent by decreasing its exponent and adding a corresponding number of zeroes to the right side of its significand. If this would cause the absolute value of the significand to become >= `2**(MAXBITS-1)`, then either * (a) Right-shift the value with the smaller exponent by dropping digits from the right side of its significand and increasing its exponent, causing precision loss. * (b) Dynamically increase `MAXBITS`. * (c) Throw an error. 3. At this point both exponents will be the same, and both significands will be aligned big integers. Set aside the exponents for now, and let `range` (a new `big.Int`) be `maxSignificand - minSignificand`. It will be between 0 and `2**MAXBITS`. 4. Turn `range` into `MAXBITS/32` `uint32`s using the `Bytes` or `DivMod` methods, whatever is easier. 5. If the highest word of `range` is equal to `math.MaxUint32` then set a flag `limit` to `false`, otherwise `true`. 6. For n from 0 to `MAXBITS/32`: * if `limit` is true, use `rand.Int63n` (!, *not* `rand.Int31n` or `rand.Uint32`) to generate a value between 0 and the nth word of `range`, inclusive, cast it to `uint32`, and store it as the nth word of the output. If the value generated is equal to the nth word of `range` (i.e. if we generated the maximum possible random value for this word) then let `limit` remain true, otherwise set it false. * If `limit` is false, use `rand.Uint32` to generate the nth word of the output. `limit` remains false regardless of the generated value. 7. Combine the generated words into a `big.Int` by building a `[]byte` and using `big/Int.SetBytes` or multiplication and addition, as convenient. 8. Add the generated value to `minSignificand` to obtain the significand of the result. 9. Use `ParseDecimal128FromBigInt` with the result significand and the exponent from steps 2-3 to obtain the result. The heart of the algorithm is step 6, which generates a uniform random unsigned integer of arbitrary length 32 bits at a time. The alignment in step 2 reduces the problem from a floating-point to an integer one, and the subtraction in step 3 reduces it to an *unsigned* one, so that we only have to think about one bound instead of 2. The `limit` flag records whether we're still dealing with that bound, or whether we've already narrowed the result down to an interval that doesn't include it. Caveats: 1. I haven't written this, let alone tested it. I may have gotten it quite wrong. A sanity check by someone who does more numerical computation work than me would be welcome. 2. Generating numbers across a large dynamic range (including crossing zero) will lose some precision and omit some possible output values with smaller exponents unless a ludicrously large `MAXBITS` is used; however, 128 bits should give a result at least as good as a naive algorithm implemented in terms of decimal128. 3. The performance is probably pretty bad.
Go has a large number package that can do arbitrary length integers: <https://golang.org/pkg/math/big/> It has a pseudo random number generator <https://golang.org/pkg/math/big/#Int.Rand>, and the crypto package also has <https://golang.org/pkg/crypto/rand/#Int> You'd want to specify the max using <https://golang.org/pkg/math/big/#Int.Exp> as `2^128`. Can't speak to performance, though, or whether this is compliant if the IEEE standard, but large random numbers like what you'd use for UUIDs are possible.
58,043,066
So I am writing a program to work out the number of days you have been alive after imputting your birthday. There is a problem as i am getting the wrong number of days but can figure out why. i inputted my birthday as 04/04/19 and i got 730625 days which is clearly wrong. ``` import datetime #imports module year = int(input("What year were you born in")) month = int(input("What month where you born in (number)")) date = int(input("What date is your birthday? ")) birthdate = datetime.date(date, month, year) #converts to dd/mm/yy today = datetime.date.today() #todays date daysAlive = (today - birthdate).days #calculates how many days since birth print("You have been alive for {} days.".format(daysAlive)) #outputs result ```
2019/09/21
[ "https://Stackoverflow.com/questions/58043066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12100405/" ]
You have the parameters the wrong way round in `datetime.date` they should be `(year,month,day)`
[`class datetime.date(year, month, day)`](https://docs.python.org/3/library/datetime.html#datetime.date) should be in the format `yy/mm/dd`. Try this code for Python **3.6** or higher, because of [f-stings](https://realpython.com/python-f-strings): ``` import datetime year = int(input("What year were you born in: ")) month = int(input("What month were you born in (number): ")) day = int(input("What day were you born in: ")) birth_date = datetime.date(year, month, day) # converts to yy/mm/dd today = datetime.date.today() # todays date days_alive = (today - birth_date).days # calculates how many days since birth print(f"You are {days_alive} days old.") # outputs result ``` Check the answer using [other sources](http://jalu.ch/coding/days/en).
15,106,490
``` <!DOCTYPE html> <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script> <script> $(document).ready(function(){ $("p").click(function(){ $(this).hide(); }); }); </script> </head> <body> <p>If you click on me, I will disappear.</p> <p>Click me away!</p> <p>Click me too!</p> </body> </html> ``` above written is the code i am using for testing jquery.. when i run the html file its not working in my browser. this code runs well in my browser when i run it from w3schools.com. please let me know what could be the reason for not working of this code. the java script is enable in my browser.
2013/02/27
[ "https://Stackoverflow.com/questions/15106490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2034961/" ]
Your jQuery path can only work if your file is on the server. If not then use this path: <http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js>
The `<script>` source is wrong ``` <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script> ```
42,736,828
After I Binding the ObversableCollection to the DataGrid,The DataGrid Can't show my data.[![enter image description here](https://i.stack.imgur.com/GfKvY.jpg)](https://i.stack.imgur.com/GfKvY.jpg) this picture show that the xx.xaml can use the Staff\_Show.but this picture that the data can't be shown normaly. [![enter image description here](https://i.stack.imgur.com/3oNLu.png)](https://i.stack.imgur.com/3oNLu.png) my program are as follows: ``` <Grid> <DataGrid x:Name="DataGrid1" CanUserAddRows="False" CanUserDeleteRows="False" CanUserReorderColumns="False" ItemsSource="{Binding Staff_Show}"> <DataGrid.Columns> <DataGridTextColumn Header="姓名" Binding="{Binding Name}"/> <DataGridTextColumn Header="税前金额" Binding="{Binding TB_Sum}"/> </DataGrid.Columns> </DataGrid> </Grid> ``` and the .cs code : ``` public ObservableCollection<Staff> Staff_Show = new ObservableCollection<Staff>(); public TaxBefore_Sum(ObservableCollection<Staff> StaffAccept) { InitializeComponent(); Staff_Show = StaffAccept; DataGrid1.DataContext = this.Staff_Show; } ```
2017/03/11
[ "https://Stackoverflow.com/questions/42736828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7433705/" ]
For the given directory structure, You can put your static files on same level as of the directory with file, `mr_doorbeen/settings.py` ``` mrdoorbeen manage.py mr_doorbeen setting.py mrdoorbeen migrations templates index.html profile profile.html static/ ``` You can set the static files to the said location as follows. ``` # Static files configurations. STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') ```
I had this same problem and solved it by adding to my settings file the import of os from pathlib and the STATICFILES\_DIRS line provided in one of the other responses: ``` from pathlib import Path, os STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) ``` STATIC\_URL was already properly specified to '/static/'. I couldnt solve the problem with just the STATICFILES line until I realized os is a function in pathlib that needed to be imported first.
60,055,587
The database I'm designing needs to store matrices of arbitrary size where each column has a description attribute and many-to-one relation with a table representing quantity (length, area, speed etc). Current design has a table "ValueMatrix" which has a one-to-many relationship with table "MatrixColumn" (allowing for arbitrary width of the matrix). "MatrixColumn" in turn has a one-to-many relation with "ColumnRow", representing an element in the matrix (allowing for arbitrary length for each column). **Is this considered correct/good design for storing a matrix in a relational database?** I realize that this is kind of an open ended question, but any comment and/or suggestions are greatly appreciated ![Diagram of current design](https://i.stack.imgur.com/ocdml.png)
2020/02/04
[ "https://Stackoverflow.com/questions/60055587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12838175/" ]
It's hard to comment on what would be a good design without a more detailed use-case but I think I would have a design with two tables:- **Table one** PK MatrixName All other matrix level data **Table two** FK X-coord Y-coord Value There's some basic questions to consider:- -How do you ensure the matrix retains it's basic structure at all times with the values you'd expect to be populated (especially if others going to be able to edit the values or add elements)? -How to create them efficiently in the first place - Cartesian joins can sometimes help Because the matrices are arbitrary sizes, I think you're forced into this x/y design which loses the conventional tabular design RDMS' are so good at. Other software (like R) have a whole different way of handling matrices - it's free and efficient and might be worth a look if you can consider other options. Best of luck to you, Phil
I *think* your problem domain can be described thus: ``` They system has many *matrices* A matrix has 0 or more *cells* A cell is identified within the matrix by *coordinates* (x, y) A cell has exactly one *numerical value* A cell has exactly one *description* A description applies to 0 or more cells ``` If that's the case, I think your tables are: ``` Matrix -------------------- MatrixID (pk) .... Description -------------------- DescriptionID (pk) DescriptionText Cell ------------------- MatrixID (pk)(fk) X (pk) Y (pk) DescriptionID (fk) CellValue ``` This would allow you to retrieve the entire matrix in a single query: ``` select m.matrixID, c.X, c.Y, c.CellValue, d.DescriptionText from matrix m inner join Cell c on c.matrixId = m.matrixID inner join Description d on c.descriptionID = d.DescriptionID order by c.x, c.y ```
21,432,708
I'm working with ASP.NET and I want to load once a big object (specific by user) in my controller and then use it in my view. I though about a static property but I find some problems with it. See : [Is it a bad idea to use a large static variable?](https://stackoverflow.com/questions/21432228/is-it-a-bad-idea-to-use-a-large-static-variable) I'm not familiar with this language and I have no idea how to properly share the same object between the different methods for each user. Could you tell me how to do that ? Do you know if singleton could be a solution ?
2014/01/29
[ "https://Stackoverflow.com/questions/21432708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2377449/" ]
A singleton won't help you here if this big object is going to be different for every user. Without knowing all the details, I'd say perhaps your best option is to store it in the Session object, ``` HttpContext.Current.Session["bigObject"] = bigObject; ``` Depending on the size & traffic, this can have performance problems, so I'd suggest you read up on the pros and cons of using Session
If you want to get to use something for the next simultaneous request, then use `TempData` - which is a bucket where you can hold data that is only needed for the following request. That is, anything you put into TempData is discarded after the next request completes. If you want to persist the information specific to user, then go for [Session](http://www.mindstick.com/Articles/ef06aed6-fa5f-47c1-b04f-e61f81cf4ab1/?Session%20Management%20in%20ASP.NET%20MVC). With session, you will have timeout, so that after certain amount of time the data stored in session will be lost. You can configure this value to much more bigger value. Apart from that when you go for Webfarm of servers, then maintaining session will be a problem, probably you might need to go for managing session in SQL Server or in some other store. Alternatively you can Use [Runtime Cache](http://msdn.microsoft.com/en-us/library/system.runtime.caching%28v=vs.110%29.aspx) object in ASP.Net MVC to keep all the common data. Cached data can be accessed fast and we have other benefits like expiring cache etc. You can share this Cache object across users, or you can maintain different cache objects for different users, that is purely dependent on your logic. In case of webfarms, yo u have distributed cache servers like redis, Azure Cache service etc., which you can use them.
28,273
I know there are lots of programs for drawing chemical molecules, but I cannot find the most advanced/suitable one for my needs: * Drawing eye-catching 3D molecules with glassy colors. * Having a large database of organic molecules to find a molecule by name. * Any OS is acceptable, but it should not be a web-app * I am not looking for "basic" free programs; price is not important if it is in a reasonable range
2016/01/25
[ "https://softwarerecs.stackexchange.com/questions/28273", "https://softwarerecs.stackexchange.com", "https://softwarerecs.stackexchange.com/users/18761/" ]
You could try using [OneDrive](https://onedrive.live.com/about/en-us/). Music stored in OneDrive can be automatically played through Groove, Microsoft's music platform available on the web or as an app. I use it for many of my music needs and I don't really have any issues with it.
Try [Mega](https://mega.nz/) or Dropbox. Their Android apps have offline folder.
54,808,474
This is just small part of my complete query I have some data where am calculating This Year and last year (a lot other things) values using aggregation and subquery. Below is the working and simplest version of my query: ``` SELECT distinct t1.country, t1.manufacturer, t1.category, t1.month, t1.year, (SELECT SUM(value) FROM data ----- value is the column name which i want to aggregate WHERE mar_short_desc = t1.mar_short_desc AND category = t1.category AND manufacturer = t1.manufacturer AND month = t1.month AND year = t1.year ----- This Is the only difference Filter ) AS Company_TY, (SELECT SUM(value) FROM data WHERE mar_short_desc = t1.mar_short_desc AND category = t1.category AND manufacturer = t1.manufacturer AND month = t1.month AND year = t1.year -1 ----- This Is the only difference Filter ) AS Company_LY, FROM data t1 ----- Other filters are here ignored for simplicity ) a ``` I want to optimize it. So trying to merge both subqueries to one and using a 'case' statement to calculate the same values. Here is the modified version: ``` SELECT distinct t1.country, t1.manufacturer, t1.category, t1.month, t1.year, (SELECT SUM(CASE WHEN year = t1.year THEN value END) AS Company_TY, SUM(CASE WHEN year = t1.year -1 THEN value END) AS company_LY FROM data WHERE mar_short_desc = t1.mar_short_desc AND category = t1.category AND manufacturer = t1.manufacturer AND month = t1.month ) FROM data t1 ) a ``` > > This giving me ERROR : "Multiple columns are specified in an > aggregated expression containing an outer reference. If an expression > being aggregated contains an outer reference, then that outer > reference must be the only column referenced in the expression." > > > All i want to do is to make a frame of all common filters and then aggregate that result with the unique filter (reason: so i don't have to filter same thing again and again. its a big code and lots of data so, want to optimize)
2019/02/21
[ "https://Stackoverflow.com/questions/54808474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3001015/" ]
The following should replicate your idea: 1 event emitted before completition. ```js import { of } from 'rxjs'; import { expand, takeWhile, reduce } from 'rxjs/operators'; let count = 0; const FINISH = "finished"; const limit = 5; const send$ = () => of(count++ < limit ? "sent" : FINISH); const expander$ = send$().pipe( expand(resp => send$()), takeWhile(resp => resp !== FINISH), reduce((acc, val) => acc ? acc + val : val, null) ); const subscribe = expander$.subscribe(console.log); ``` You can see it working in [this blitz](https://stackblitz.com/edit/typescript-t6rzid?file=index.ts)
Not tested but you can try this pattern ``` exec=()=>http.get(....) exec().pipe( expand((resp)=>exec()), takeWhile(resp=>resp !== 'end'), scan((acc,curr)=>acc.concat(curr),[]) ).subscribe() ```
4,203,174
I'm editing orgmode, a time-management mode for emacs. I'm adding some new time functions. In my addition i need to determine the day of the week for a given date. I use the following code: ``` (defun org-day-of-week (day month year) (nth-value 6 (decode-universal-time (encode-universal-time 0 0 0 day month year 0) 0))) ``` Executing this code gives me the error: nth-value: Symbol's function definition is void: decode-universal-time I'm new to lisp, and can't find any info related to this error. I presume some libraries aren't loaded or available. Can anyone please shed a light on this? Regards, Erwin Vrolijk Snow.nl
2010/11/17
[ "https://Stackoverflow.com/questions/4203174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/510605/" ]
A cleaner version of Vatine's [answer](https://stackoverflow.com/questions/4203174/lisp-decode-universal-time-is-void/4203576#4203576) is: ``` (defun day-of-week (year month day) "Return the day of the week given a YEAR MONTH DAY" (nth 6 (decode-time (encode-time 0 0 0 day month year)))) ``` `decode-time` and `encode-time` are [documented here](http://www.gnu.org/software/emacs/manual/html_node/elisp/Time-Conversion.html).
I haven't found the source of this problem, but found a workaround: ``` (defun day-of-week (day month year) "Returns the day of the week as an integer. Sunday is 0. Works for years after 1752." (let ((offset '(0 3 2 5 0 3 5 1 4 6 2 4))) (when (< month 3) (decf year 1)) (mod (truncate (+ year (/ year 4) (/ (- year) 100) (/ year 400) (nth (1- month) offset) day -1)) 7))) ```
212,062
![Source signs behavior](https://i.stack.imgur.com/EWKua.png) Hello, friends. Well, a picture is worth a thousand words. I would like the behavior on the left rather than on the right, the latters are CircuitTikZ defaults. A helpful guy helped me to do it with independent voltage sources,unfortunately I forgot about asking him for these ones. Does anyone have the same concern out there? Thanks in advance. ``` \documentclass{article} \usepackage{circuitikz} \makeatletter \pgfcircdeclarebipole{}{\ctikzvalof{bipoles/vsourceam/height}}{vsourceAM}{\ctikzvalof{bipoles/vsourceam/height}}{\ctikzvalof{bipoles/vsourceam/width}}{ \pgfsetlinewidth{\pgfkeysvalueof{/tikz/circuitikz/bipoles/thickness}\pgfstartlinewidth} \pgfpathellipse{\pgfpointorigin}{\pgfpoint{0}{\pgf@circ@res@up}}{\pgfpoint{\pgf@circ@res@left}{0}} \pgfusepath{draw} \pgfscope \pgftransformxshift{\ctikzvalof{bipoles/vsourceam/margin}\pgf@circ@res@left} \pgftext[rotate=-\pgf@circ@direction]{$-$} \pgfusepath{draw} \endpgfscope \pgfscope \pgftransformxshift{\ctikzvalof{bipoles/vsourceam/margin}\pgf@circ@res@right} \pgftext[rotate=-\pgf@circ@direction]{$+$} \pgfusepath{draw} \endpgfscope } \makeatother \begin{document} \begin{circuitikz}[american voltages] \ctikzset{bipoles/vsourceam/margin=.5}% default too big \draw (0,0) to[V={v1}] (3,0) to[V={v2}] (3,3) to[V={v3}] (0,3) to[V={v4}] (0,0); \draw (4,0) to[V={v5}] (6,2); \end{circuitikz} \end{document} ``` As specific code.
2014/11/13
[ "https://tex.stackexchange.com/questions/212062", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/48128/" ]
Some more free available versions: ``` % arara: lualatex \documentclass{article} \usepackage{fontspec} \begin{document} Script Capital H: {\fontspec{arialuni.ttf}\symbol{"210B}} {\fontspec{code2000.ttf}\symbol{"210B}} {\fontspec{dejavusans.ttf}\symbol{"210B}} {\fontspec{freeserif.otf}\symbol{"210B}} {\fontspec{mathcadunimath.otf}\symbol{"210B}} {\fontspec{quivira.otf}\symbol{"210B}} {\fontspec{symbola.ttf}\symbol{"210B}} \end{document} ``` ![enter image description here](https://i.stack.imgur.com/2Z9W7.png) --- In case, you do not want to use one of the script H letters, you might want to choose one of the following which look a bit similar: ``` % arara: pdflatex \documentclass{article} \usepackage{amssymb} \begin{document} $\ae\varkappa\aleph$ \end{document} ``` ![enter image description here](https://i.stack.imgur.com/3h6S0.png)
You can get something very similar to what Mico showed using `\mathscr{H}` and `mathrsfs`, which is free. ![enter image description here](https://i.stack.imgur.com/NXQ7n.png) ``` \documentclass{standalone} \usepackage{mathrsfs} \begin{document} $\mathscr{H}$ \end{document} ```
62,082,621
I try to join two tables: ``` var data = from request in context.Requests join account in context.AutolineAccts on request.PkRequest.ToString() equals account.AccountCode select new { ID = request.PkRequest.ToString(), Location = request.FkLocation, RequestDate = request.RequestDate.Value, Requestor = request.FkRequestor, DebitorNr = request.FkDebitor.ToString(), NewDebit = request.Debit.ToString(), ApprovalStatus = request.ApprovalStatus.ToString(), RecommendationStatus = request.RecommendationStatus.ToString(), DebitorName = account.CustomerSname, Limit = account.CreditLimit }; ``` Now I want to filter the result set depending on the status of the user: ``` // Accounting user if (ActiveDirectoryHelper.CheckIfUserIsInADGroup(userLogin, AdGroups.ACCOUNTING) ) req = data.Where(x => x.RecommendationStatus == null).ToList(); // After sales manager else if (ActiveDirectoryHelper.CheckIfUserIsInADGroup(userLogin, AdGroups.SAV_LEADERS)) req = data.OrderByDescending(x => x.ID).ToList(); // Everybody else else req = data.OrderByDescending(x => x.PkRequest).ToList(); ``` And that's where I'm stuck. When I don't have the join and only retrieve a "Request" type, I can just declare a list of Requests ``` List<Requests> req; ``` But with that combination of Requests and AutolineAccts I would have to declare and initialize a list of "items" (req) to assign the result set to in the if-else segments. But I don't know how that anonymous variable should look like. Later on I have to map the result set to a list of my IndexViewModels: ``` foreach (var item in req) viewModel.CLModels.Add(new IndexViewModel { ID = item .PkRequest.ToString(), Location = item .FkLocation, RequestDate = item .RequestDate.Value, Requestor = item .FkRequestor, DebitorNr = item .FkDebitor.ToString(), NewDebit = item .Debit.ToString(), ApprovalStatus = item .ApprovalStatus.ToString(), RecommendationStatus = item .RecommendationStatus.ToString(), DebitorName = item.CustomerSname, Limit = item.CreditLimit }); ``` Any idea to solve this issue?
2020/05/29
[ "https://Stackoverflow.com/questions/62082621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10429263/" ]
You have splitted the query errorneously. Must be: ``` SELECT (months*salary) as earnings, -- 2 and 4 COUNT(*) -- 4 FROM Employee -- 1 GROUP BY earnings -- 3 ORDER BY earnings DESC -- 5 LIMIT 1; -- 6 ``` Step 1 - table `Employee` is used as data source Step 2 - the value of the expression `(months*salary)` for each record in the table is calculated Step 3 - the records which have the same value of the expression from (2) are treated as a group Step 4 - for each group the value of the expression from (2) is put into output buffer, and the amount of records in a group is calculated and added to output buffer Step 5 - the rows in output buffer are sorted by the expression from (2) in descending order Step 6 - the first row from the buffer (i.e. which have greatest value of the expression from (2)) is returned.
**Step 3:** `GROUP BY earnings` was used to GROUP TOGETHER same value earnings. If you have, for example, earnings of $3,000, and there were 3 of them, they will be grouped together. `GROUP BY` is also required in combination with the aggregate function `COUNT(*)`. Otherwise, `COUNT(*)` will not work and return an error. **Step 4:** `ORDER BY earnings DESC` was used to order the GROUPED EARNINGS in DESCENDING order. Meaning, from HIGHEST EARNINGS down to the LOWEST EARNINGS. **Step 5:** `LIMIT 1` limits the returned row count to only 1. Hope this helps! :)
18,195
Is it possible to completely disable Bulk Edit functionality? I'm using Wordpress 3.1.
2011/05/25
[ "https://wordpress.stackexchange.com/questions/18195", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3545/" ]
``` add_filter( 'bulk_actions-' . 'edit-post', '__return_empty_array' ); add_filter( 'bulk_actions-' . 'upload', '__return_empty_array' ); ``` That will do the job
You can completely disable bulk edit input by removing all actions from this filter: ``` function removeBulkActionsInput ($actions) { // remove all actions return array(); } add_filter ('bulk_actions-edit-' . POST_TYPE, 'removeBulkActionsInput' ); ``` POST\_TYPE ist your custom post type as string or e.g. 'post' for usual posts.
16,835,478
I'm trying to round a **float** down to 6 decimal places. Converting from double to float seems to pretty much do this, however in the process I've noticed some weirdness. Whatever I do I seem to end up with fictitious extra decimal values on the end if I convert back to a **double** later on. I cannot avoid the conversion back to double - this in part of the application I cannot change, so I'm just trying to understand why my code is producing extra decimal places which never originally existed. Eg; I start with the following value and convert it to a double: ``` float foo = 50.8467178; double bar = Convert.ToDouble32(foo); // Sorry line above originally said ToInt32 which was a typo :( ``` ..then "bar" will be: **50.846717834472656** in the debugger. **However**: ``` Convert.ToDouble(50.8467178).ToString() ``` ...produces: **50.8467178** (in the debugger). Ie it does not have the extra values. Why have extra digits appeared on the end? How can I stop this? And finally: Why does calling ToString() on any of the above, often output a different number of decimal places compared with what the debugger shows?
2013/05/30
[ "https://Stackoverflow.com/questions/16835478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/229587/" ]
There's actually a few subtly different things happening in this example: > > I'm trying to round a float down to 6 decimal places. Converting from double to float seems to pretty much do this > > > If you need to round, use the [Round](http://msdn.microsoft.com/en-us/library/75ks3aby.aspx) method. Converting can result in a loss of precision, and floating point types aren't infinitely precise to begin with. > > Why have extra digits appeared on the end? > > > Internally floats and doubles are represented in binary according to the [IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point) standard. Your number, 50.8467178 can't be exactly represented in binary, much like 1/3 can't be exactly represented in decimal (without repeating digits). According to the standard, the number as a float is stored as `0x424B6304`. This is precise to 24 bits, or 6-9 decimal digits. Now, reinterpreting that number according to the standard we get: ``` 0x424B6304 = 1.58895993232727 * 2^5 = 50.84671783447264 ``` The display, whether it be the debugger or calling the `ToString()` method, is smart enough to know that only the first 6-9 digits mattered (which is consistent with the IEEE standard). Taking the maximum 9 digits, the float would be displayed as `50.8467178`. However, when this number is converted to a double, it's binary value **does not change.** Its internal bit pattern sure does, but the binary number is still interpreted as `1.58895993232727 * 2^5`. The problem is that doubles are precise to 53 bits, or 15-17 decimal digits. So now when displayed, 15-17 digits are shown rather than the original 6-9. So, its not that there are extra digits when its converted to a double, *the digits were already there*. Now when there is no intermediate float conversion, 50.8467178 can be more precisely represented using a double. This is stored as `0x40496C613FB5F875`. Now I haven't done the math on that one yet, but with the above procedure, we would get something like `50.84671780000000000000000000023155`. Considering only the first 15-17 digits, results in the 50.8467178 seen in the display (with the significant 0s omitted). > > How can I stop this? > > > Don't round by casting to floats, they only have 6-9 accurate digits. The decimal type is normally appropriate for when decimal precision is needed, but since you can't change that part of the code, using the `Round` method should be precise enough for your application (as long as you stay under 1,000,000,000). > > Why does calling ToString() on any of the above, often output a different number of decimal places compared with what the debugger shows? > > > I've been skirting around this issue to try and keep things simple and sequential. I've been giving a range for precision in decimal digits: 6-9 for floats, 15-17 for doubles. Taking doubles for example, the `ToString()` method by default returns a string with 15 decimal digits. You could, however, force it to return 17 decimal digits by calling `ToString("G17")` [(doc)](http://msdn.microsoft.com/en-us/library/kfsatb94.aspx), but there would be no guarantee those two digits are significant. I suspect that the debugger calls this version for its display, which is why it differs from `ToString()`. --- **Further reading:** [IEEE Arithmetic, by Oracle](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_math.html). It's quite technical though.
The literal 50.8467178 is a double by default so it is implicitly converted to a float when asigned to foo. And because float has a smaller percision it is rounded and not so acurate. You should use 50.8467178f when you asign to foo because it is a float literal. In the second example you are converting a double literal to double so there is no change and it prints it as is.
1,544,006
I am trying to chain multiple compiled linq queries together. I have succeeded in chaining two queries together, but I cannot get a chain of three to work correctly. So here is a reduction of my code to recreate the issue. My two questions are: 'Why isn't this working?' and 'Is there a better way to keep the performance benefit of compiled queries and also avoid duplication of base query logic that is commonly used?' Define the following two queries: ``` Func<DataContext, IQueryable<User>> selectUsers = CompiledQuery.Compile( (DataContext dc)=>dc.Users.Select(x=>x) ); // Func<DataContext, string, IQueryable<User>> filterUserName = CompiledQuery.Compile( (DataContext dc, string name) => selectUsers(dc).Where(user=>user.Name == name) ); ``` Calling and enumerating the chain works fine: ``` filterUserName(new DataContext(), "Otter").ToList(); ``` Add a third query to the chain: ``` Func<DataContext, string, int, IQueryable<User>> filterUserAndGroup = CompiledQuery.Compile( (DataContext dc, string name, int groupId) => filterUserName(dc, name).Where(user=>user.GroupId == groupId) ); ``` Calling the chain does not work: ``` filterUserAndGroup(new DataContext(), "Otter", 101); ``` > > System.InvalidOperationException: > Member access 'String Name' of 'User' > not legal on type > 'System.Linq.IQueryable`1[User].. at > System.Data.Linq.SqlClient.SqlMember.set_Expression(SqlExpression > value) at > System.Data.Linq.SqlClient.SqlFactory.Member(SqlExpression > expr, MemberInfo member) at > System.Data.Linq.SqlClient.SqlBinder.Visitor.AccessMember(SqlMember > m, SqlExpression expo) at > System.Data.Linq.SqlClient.SqlBinder.Visitor.VisitMember(SqlMember > m) at > System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode > node) at > System.Data.Linq.SqlClient.SqlBinder.Visitor.VisitExpression(SqlExpression > expr) at > System.Data.Linq.SqlClient.SqlBinder.Visitor.VisitBinaryOperator(SqlBinary > bo) at > System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode > node) at > System.Data.Linq.SqlClient.SqlBinder.Visitor.VisitExpression(SqlExpression > expr) at > System.Data.Linq.SqlClient.SqlBinder.Visitor.VisitSelect(SqlSelect > select) at > System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode > node) at > System.Data.Linq.SqlClient.SqlBinder.Visitor.VisitAlias(SqlAlias > a) at > System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode > node) at > System.Data.Linq.SqlClient.SqlVisitor.VisitSource(SqlSource > source) at > System.Data.Linq.SqlClient.SqlBinder.Visitor.VisitSelect(SqlSelect > select) at > System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode > node) at > System.Data.Linq.SqlClient.SqlBinder.Visitor.VisitIncludeScope(SqlIncludeScope > scope) at > System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode > node) at > System.Data.Linq.SqlClient.SqlBinder.Bind(SqlNode > node) at > System.Data.Linq.SqlClient.SqlProvider.BuildQuery(ResultShape > resultShape, Type resultType, SqlNode > node, ReadOnlyCollection`1 > parentParameters, SqlNodeAnnotations > annotations) at > System.Data.Linq.SqlClient.SqlProvider.BuildQuery(Expression > query, SqlNodeAnnotations annotations) > at > System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Compile(Expression > query) at > System.Data.Linq.CompiledQuery.ExecuteQuery(DataContext > context, Object[] args) at > System.Data.Linq.CompiledQuery.Invoke(TArg0 > arg0, TArg1 arg1) at TestMethod() in > .... > > >
2009/10/09
[ "https://Stackoverflow.com/questions/1544006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66101/" ]
Looks like you need to convert your first compiled query to a list before executing the second one. In theory that should have caused an error with your two queried chain as well. From [MSDN CompiledQuery](http://msdn.microsoft.com/en-us/library/system.data.linq.compiledquery.compile.aspx): > > If a new query operator is applied to the result of the delegate execution, an exception is generated. > > > When you want to execute a query operator over the result of executing a compiled query, you must translate the result to a list before operating on it. > > > Perhaps this code will fix it although that could have implications for the roundtrips back to the database if you're using LINQ to SQL. ``` filterUserName(dc, name).ToList().Where(user=>user.GroupId == groupId) ```
Do you need to use the CompiledQuery class? Try this... ``` static Func<DataContext, IQueryable<User>> selectUsers = (dc) => dc.Users.Select(x => x); // static Func<DataContext, string, IQueryable<User>> filterUserName = (DataContext dc, string name) => selectUsers(dc).Where(user => user.Name == name); // static Func<DataContext, string, int, IQueryable<User>> filterUserAndGroup = (DataContext dc, string name, int groupId) => filterUserName(dc, name).Where(u => u.GroupID == groupId); ``` ... test code (I know my DataContext here is not LINQ2SQL but that is the fun and beauty of LINQ) ... *Also, I do use this method against my own databases so I know they build into single queries to be sent to the database. I have even used normal instance methods that return IQueryable<> instead of Func<> delegates.* ``` public class DataContext { public static Func<DataContext, IQueryable<User>> selectUsers = (dc) => dc.Users.Select(x => x); // public static Func<DataContext, string, IQueryable<User>> filterUserName = (DataContext dc, string name) => selectUsers(dc).Where(user => user.Name == name); // public static Func<DataContext, string, int, IQueryable<User>> UsrAndGrp = (DataContext dc, string name, int groupId) => filterUserName(dc, name).Where(u => u.GroupID == groupId); public DataContext() { Users = new List<User>() { new User(){ Name = "Matt", GroupID = 1}, new User(){ Name = "Matt", GroupID = 2}, new User(){ Name = "Jim", GroupID = 2}, new User(){ Name = "Greg", GroupID = 2} }.AsQueryable(); } public IQueryable<User> Users { get; set; } public class User { public string Name { get; set; } public int GroupID { get; set; } } } class Program { static void Main(string[] args) { var q1 = DataContext.UsrAndGrp(new DataContext(), "Matt", 1); Console.WriteLine(q1.Count()); // 1 var q2 = DataContext.filterUserName(new DataContext(), "Matt"); Console.WriteLine(q2.Count()); // 2 } } ```
20,073,638
I've table with accounts rest with following data: ``` T_ID T_RESTDATE T_RESTSUM T_INCOME T_OUTCOME 1135782 20.04.2013 16714,31 16714,31 0 1135782 20.05.2013 33362,4 16648,09 0 1135782 20.06.2013 49179,59 15817,19 0 1135782 20.07.2013 64207,42 15027,83 0 1135782 20.08.2013 78485,35 14277,93 0 1135782 20.09.2013 92050,89 13565,54 0 1135782 20.10.2013 104939,65 12888,76 0 ``` To generate range between dates i usually use following query: ``` SELECT :dateBeg+level-1 turndate FROM dual CONNECT BY level <= :dateEnd-:dateBeg+1 ``` How do I get the following result: ``` T_ID T_RESTDATE T_RESTSUM T_INCOME T_OUTCOME 1135782 20.04.2013 16714,31 16714,31 0 1135782 21.04.2013 16714,31 16714,31 0 1135782 22.04.2013 16714,31 16714,31 0 1135782 23.04.2013 16714,31 16714,31 0 ... 1135782 20.05.2013 33362,4 16648,09 0 1135782 21.05.2013 33362,4 16648,09 0 1135782 22.05.2013 33362,4 16648,09 0 ... ```
2013/11/19
[ "https://Stackoverflow.com/questions/20073638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1063474/" ]
**Why neither `data-remote` or `href` work on remote sites like youtube** Twitter bootstrap's modal uses AJAX to load remote content via `data-remote`/`href`. AJAX is constrained by the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy) so accessing a site with a different origin, like youtube, will produce this error: > > No 'Access-Control-Allow-Origin' header is present on the requested resource > > > So neither `data-remote` or `href` will do what you want. **JSON**: If you were getting json data then you could potentially use [JSONP](http://en.wikipedia.org/wiki/JSONP). But since you need html, not json, from sites like youtube we need another approach: **Solution using `<iFrame>`** An `<iframe>` will work for youtube and many other remote sites (even this solition doesn't work for all sites as some, like Facebook, explicitly block iframes by setting X-Frame-Options' to 'DENY') . One way to use an iframe for dynamic content is to: **1)** add an empty iframe inside your modal's body: ``` <div class="modal-body"> <iframe frameborder="0"></iframe> </div> ``` **2)** add some jquery that is triggered when the modal dialog button is clicked. The following code expects a link destination in a `data-src` attribute and for the button to have a class `modalButton`. And optionally you can specify `data-width` and `data-height`- otherwise they default to 400 and 300 respectively (of course you can easily change those). The attributes are then set on the `<iframe>` which causes the iframe to load the specified page. ``` $('a.modalButton').on('click', function(e) { var src = $(this).attr('data-src'); var height = $(this).attr('data-height') || 300; var width = $(this).attr('data-width') || 400; $("#myModal iframe").attr({'src':src, 'height': height, 'width': width}); }); ``` **3)** add the class and attributes to the modal dialog's anchor tag: ``` <a class="modalButton" data-toggle="modal" data-src="http://www.youtube.com/embed/Oc8sWN_jNF4?rel=0&wmode=transparent&fs=0" data-height=320 data-width=450 data-target="#myModal">Click me</a> ``` `**[Demo Fiddle using youtube](http://jsfiddle.net/2AU6q/3/)**`
Probably an old post, I had a similar problem a time ago, i wanted to press a link, which would pass the href of a text file (or any other file) to an iframe inside a modal window, i solved like this: ```js function loadiframe(htmlHref) //load iframe { document.getElementById('targetiframe').src = htmlHref; } function unloadiframe() //just for the kicks of it { var frame = document.getElementById("targetiframe"), frameHTML = frame.contentDocument || frame.contentWindow.document; frameHTML.removeChild(frameDoc.documentElement); } ``` ```html <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css" rel="stylesheet"/> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> <a class=" btn btn-danger" onClick="loadiframe('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css')" data-toggle="modal" data-target="#myModal">LINK</a><!--link to iframe--> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header" style="border:hidden"> <button type="button" class="close" onClick="unloadiframe()" data-dismiss="modal" aria-label="Close"><span aria- hidden="true">&times;</span></button> </div> <div class="modal-body" style="padding-top:10px; padding-left:5px; padding-right:0px; padding-bottom:0px;"> <iframe src="" frameborder="0" id="targetiframe" style=" height:500px; width:100%;" name="targetframe" allowtransparency="true"></iframe> <!-- target iframe --> </div> <!--modal-body--> <div class="modal-footer" style="margin-top:0px;"> <button type="button" class="btn btn-default pull-right" data-dismiss="modal" onClick="unloadiframe()">close</button> </div> </div> </div> </div> ``` So in this case you have only one modal, one iframe, which you load and unload.
44,948
John 5:3-5 NIV > > 3 Here a great number of disabled people used to lie—the blind, the lame, the paralyzed. [4] [b] 5 One who was there had been an invalid for thirty-eight years. > > > John 5:3-5 KJV > > 3 In these lay a great multitude of impotent folk, of blind, halt, withered, waiting for the moving of the water. > 4 For an angel went down at a certain season into the pool, and troubled the water: whosoever then first after the troubling of the water stepped in was made whole of whatsoever disease he had. > 5 And a certain man was there, which had an infirmity thirty and eight years. > > > John 5:3-5 NASB > > . 3 In these lay a multitude of those who were sick, blind, lame, and withered, [[c]waiting for the moving of the waters; 4 for an angel of the Lord went down at certain seasons into the pool and stirred up the water; whoever then first, after the stirring up of the water, stepped in was made well from whatever disease with which he was afflicted.] 5 A man was there who had been [d]ill for thirty-eight years. > > > John 5:4 is missing in the NIV but in the other versions its there. Why is this verse missing in this translation?
2020/02/12
[ "https://hermeneutics.stackexchange.com/questions/44948", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/16527/" ]
The Revised Standard Version and some others omit this fourth verse with the reason given that it was insufficiently supported by earlier text. **However, John 5:3 and 7 could not be properly understood without this verse.** **Also**, at the excavation site of the pool of Bethesda, archaeologists found a faded fresco on the wall depicting an angel and water - so there is at least support for what this verse says.
E.W.Bullinger is pretty good at noting textual issues in The Companion Bible. He offers no note of concern about authenticity . > > Verse 4 > > > **For an angel**. The water was intermittent from the upper springs of the waters of Gihon (see App-68 , and 2 Chronicles 32:33 , Revised Version) The common belief of the man expressed in John 5:7 is hereby described. All will be clear, if we insert a parenthesis, thus: "For [it was said that] an angel", &c. > > > **at a certain season** = from time to time. Greek. kata ( App-104 . kairon . > > > **into**. Greek. en. App-104 . > > > **troubled**. Greek. tarasso. Compare John 11:33 ; John 12:27 ; John 13:21 ; John 14:1 , John 14:27 . > > > **whole** = well or sound. Greek. hugies. Seven times in John. Compare John 7:23 . > > > **he** had = held him fast. See note on "withholdeth", 2 Thessalonians 2:6 . > > > Source <https://www.studylight.org/commentaries/eng/bul/john-5.html>
107,059
Which famous movie is suggested by the following chess position (by Trevor Tao)? [![enter image description here](https://i.stack.imgur.com/I2Meu.png)](https://i.stack.imgur.com/I2Meu.png)
2021/02/02
[ "https://puzzling.stackexchange.com/questions/107059", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/70146/" ]
This is also (one would hope) not the intended answer, but I'll go with the [garbagious](https://www.imdb.com/event/ev0005190/2018/1?ref_=ttawd_ev_4) > > [Transformers: The Last Knight](https://www.imdb.com/title/tt3371366/?ref_=adv_li_tt). > > > That would be because to my eye white can only win by > > sacrificing the Last Knight in the corner: > > [![enter image description here](https://i.stack.imgur.com/mRmM3m.png)](https://i.stack.imgur.com/mRmM3.png) > > > after which there are a lot of transformers, as > > white and black [both promote three queens](https://lichess.org/Vw2tUMAo#3), which immediately get exchanged away at H1. > > ``` > > [FEN "8/8/P7/P4N1p/P7/7p/P6p/n1K3k1 w - - 0 1"] > 1. Ng3 h4 > 2. Nh1 Kxh1 > 3. a7 Kg1 > 4. a8=Q h1=Q > 5. Qxh1+ Kxh1 > 6. a6 Kg1 > 7. a7 h2 > 8. a8=Q h1=Q > 9. Qxh1+ Kxh1 > 10. a5 h3 > 11. a6 h2 > 12. a7 Kg1 > 13. a8=Q h1=Q > 14. Qxh1+ Kxh1 > > ``` > > > > The sequence seems forced: white wins this way, and any deviation from black leads to being down a queen. After this, the white king will step to b2, confining the black's Last Knight into the corner, and the final pawn is free to march to a8. If you have a better suggestion for a movie based on the solution to the chess part (and you probably do), please drop a comment.
I already posted this in a comment, but might as well make it an actual guess: > > [*Henry VIII* (2003)](https://www.imdb.com/title/tt0382737/?ref_=fn_al_tt_1) (or maybe [*Henry VIII* (1979)](https://www.imdb.com/title/tt0080860/?ref_=fn_al_tt_3), or even [*Henry VIII: Man, Monarch, Monster*](https://www.imdb.com/title/tt10619810/?ref_=fn_al_tt_2) - last one doesn't have a date associated with it, and it's a TV series not a movie, unsure if it was officially released or not. I'm surprised there aren't more of these, and none were theatrical releases. Maybe there's some other famous Henry VIII movie that just doesn't have his name in the title?) > > > Explanation being: > > Henry had 6 queens, most of whom didn't last for very long. In this sequence, we see 6 pawns promoted to queens and then pretty much immediately captured. (In reality, 2 of Henry's wives outlived him, but whatever - point is except for the first, none of them were queens for very long.) > > >
156,628
The [2019 UA artificer](https://media.wizards.com/2019/dnd/downloads/UA-Artificer2-2019.pdf) can infuse any simple or martial weapon that has the thrown weapon property with the [Returning Weapon](https://media.wizards.com/2019/dnd/downloads/UA-Artificer2-2019.pdf#page=14) infusion. The net is a martial ranged weapon with the thrown property. A returning net comes flying back into the hands of the creature that threw it, regardless of whether it hits or not. It’s easy to imagine the net flying back to its thrower when it misses. But once it has restrained its target, I can’t figure what happens. Does it bring back its taget?
2019/09/22
[ "https://rpg.stackexchange.com/questions/156628", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/57038/" ]
The rules simply don’t cover this case; it is entirely up to the DM to decide what happens. Four possibilities spring to my mind: 1. The net returns, without the target, making the endeavor pointless. 2. The *returning* property fails entirely, the net being pinned in place by the target. 3. The target is dragged back to the artificer. 4. The *returning* is delayed until the target extricates itself from the net, at which point the net returns to the artificer. None of these possibilities has any real rules support: *returning* does not mention that it frees any targets of a *returning net*, does not mention any situation in which the weapon can fail to return, **certainly** doesn’t mention any ability to bring a creature back with it, and doesn’t mention any opportunity for the returning to happen at any point later than immediately after the weapon hits or misses. Really, taken literally, the only thing the rules really do support is [having the net return but the target remain restrained even so, as Amethyst Wizard’s fine answer explains](https://rpg.stackexchange.com/a/156654/4563). If that’s all the rules have to offer, I think it’s pretty clear that the DM needs to come up with something else. For me, I think #4 is the most reasonable and balanced of these options. It seems most true to the purpose of the features, without causing any extra benefits—the *returning* property does its job and allows the artificer to retrieve their net at no extra effort on their part, but the net does its job restraining the target without giving the artificer any new or extra features not explicitly indicated by either *returning* or nets.
[UA Eberron Arificer](https://media.wizards.com/2019/dnd/downloads/UA-Artificer2-2019.pdf) states: > > **Returning Weapon**: This magic weapon grants a +1 bonus to attack > and damage rolls made with it, and **it returns to the wielder’s hand immediately after it is used to make a ranged attack** > > > So immediately after the net is used to make a ranged attack, it is returned to the owner's hands. [D&D Beyond states](https://www.dndbeyond.com/equipment/net): > > **A Large or smaller creature hit by a net is restrained until it is freed.** [...] A creature can use its action to make a DC 10 Strength check, freeing itself or another creature within its reach on a success. Dealing 5 slashing damage to the net (AC 10) also frees the creature without harming it, ending the effect and destroying the net. > > > Here we describe what the net does. It imposes restrained until the target is freed. The rules text also lists two ways to become free; a DC 10 Strength check, or dealing 5 slashing damage to the net (which also destroys it). Now, 5e D&D has no flavour text. So the first line still applies, and nothing here states those are the only 2 ways to become freed from a net. Any other situation must, by the rules as written, be interpreted by the DM. The DM now has a choice. The net **is going to return**. This return happens **immediately** after the attack. The question the DM must answer is, "The net that was restraining the target is now 30' away in another creature's hands, and not touching the target. Is the target freed?" What, exactly, the DM answers there is **completely up to the DM**, but the rules explicitly tell the DM to answer that question to determine if the creature is restrained or not; it places a condition on the restrained condition, and the DM is responsible to determine if it happens or not. The DM could decide that a magic net (it is +1, after all) can restrain things without touching them or being anywhere near them. Or they could decide that being on the other side of a room from a net is one way of being "freed" from that net. --- Now there is one ambiguity. When the net returns, nothing states what happens to the creature it is restraining. One possible interpretation is that the restrained creature is also moved to the thrower of the net, and ends up in the throwers hands. I cannot find rules text to support either of these two options.
96,790
I just had a lecture from someone who has been a senior scientist (and has completed a PhD, post-doc) at a hospital for already 15 years. So I'm assuming this person is experienced in giving talks in English. However, almost one out of three words was completely unintelligible because of a very strong Spanish accent where every word gets morphed into a Spanish-English hybrid word. I spoke to two people after the lecture and they both said they couldn't follow along because of the strong accent. The questions after the talk were also not about the lecture but about the speaker's field. My impression is that the talk was a waste of time for the two dozen people present. Now I wonder if the speaker is aware of this problem, my guess is no and as such I feel the need to bring this to the speaker's attention. If it was me I'd very much like to know that I have a problem communicating because I feel like a lack of communication skills can be a very serious barrier to being a good scientist but I don't know if she feels the same way. My plan is to use an anonymous email address to send this feedback, sandwiched between two compliments to avoid coming off as a negative person.
2017/10/02
[ "https://academia.stackexchange.com/questions/96790", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/80681/" ]
**Don't send the email**. Based on my experience, I predict that the anonymous email you are proposing to send almost certainly won't tell the speaker any information she does not already know, only something that she is either in denial about or that she is (for whatever mysterious reasons of human psychology) helpless or unwilling to do anything about. On the other hand, especially due to its anonymous nature, the email is quite likely to come across as hurtful and to cause her negative feelings such as guilt, self-loathing, low self-esteem, depression, etc., that would make her situation worse without leading to any progress towards resolving her accent/language problem. There is a time and a place to offer people negative feedback that might help them improve, e.g., when such feedback is directly solicited from you or when you are a person whose job it is to offer such feedback. That time and place is not your current situation. So don't.
**Yes, you might want to send the email**. I think it will have good and productive effect overall, and help the speaker further in her career a lot. Such criticism, though very unpleasant and even hurtful to hear at first, opens the opportunity to self-improvement. Your act thus shows that you do care for the speaker. Much more than a person who simply wants to minimize his or her in-comfort, shy away from confrontation and leave the speaker alone and deserted without knowing that secretly the community ignores and disdain her. As for the fact that the email is anonymous, something that have alerted many commenters here, I disagree with the overall opinion. Academia is full of anonymous feedback, most of which has the potential to be much more hurtful and cardinal than a somewhat amusing email about one's accent. I'm sure the speaker got many harsh and brutal rejections through anonymous peer review, throughout her career, and she's not going to break down because some guy decided to write an anonymous email, peculiar as it sounds. Indeed, academia itself has reserved the right for people "not to stand behind their own opinions" and ideas, so that they feel protected to speak freely, through endless forms of anonymous feedback (reviews and student's feedback, to name a few).
1,612,723
I was trying to solve another integral when then I reached this, I've no idea of how to select the contour for the integration.
2016/01/14
[ "https://math.stackexchange.com/questions/1612723", "https://math.stackexchange.com", "https://math.stackexchange.com/users/304873/" ]
Let $t^2= e^x-1$. We have $$2tdt = e^xdx = (1+t^2)dx \implies dx = \dfrac{2tdt}{1+t^2}$$ Hence, we have $$I = \int\_0^{\infty} \dfrac{xdx}{\sqrt{e^x-1}} = \int\_0^{\infty} \dfrac{2t \log(1+t^2)dt}{(1+t^2)t} = 2\int\_0^{\infty} \dfrac{\log(1+t^2)}{(1+t^2)}dt$$ Let $$I(a) = \int\_0^{\infty} \dfrac{\log(1+a^2t^2)}{1+t^2}dt \,\,\, (\clubsuit)$$ We need $2I(1)$. Differentiating $(\clubsuit)$, we obtain $$I'(a) = \int\_0^{\infty} \dfrac{2at^2}{(1+a^2t^2)(1+t^2)}dt = \dfrac{2a}{a^2-1}\left(\int\_0^{\infty} \dfrac{dt}{1+t^2} - \int\_0^{\infty} \dfrac{dt}{1+a^2t^2} \right)$$ Hence, $$I'(a) = \dfrac{2a}{a^2-1}\left(\dfrac{\pi}2 - \dfrac{\pi}{2a}\right) = \dfrac{\pi}{(1+a)} \,\,\, (\spadesuit)$$ Further, we have $I(0) = 0$. Hence, integrating $(\spadesuit)$, we obtain $$I(a) = \pi \log(1+a)$$ The desired integral is $2I(1) = \pi \log(2)$.
$\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,} \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace} \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack} \newcommand{\dd}{\mathrm{d}} \newcommand{\ds}[1]{\displaystyle{#1}} \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,} \newcommand{\ic}{\mathrm{i}} \newcommand{\mc}[1]{\mathcal{#1}} \newcommand{\mrm}[1]{\mathrm{#1}} \newcommand{\on}[1]{\operatorname{#1}} \newcommand{\pars}[1]{\left(\,{#1}\,\right)} \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}} \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,} \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}} \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$ With $\ds{t \equiv \expo{x} - 1 \implies x = \ln\pars{1 + t}}$: \begin{align} &\bbox[5px,#ffd]{\int\_{0}^{\infty} {x \over \root{\expo{x} - 1}}\,\dd x} = \int\_{0}^{\infty} t^{-1/2}\,\,\,{\ln\pars{1 + t} \over 1 + t}\,\dd t \\[5mm] = &\ \int\_{0}^{\infty} t^{\color{red}{1/2} - 1}\bracks{% -\sum\_{k = 0}^{\infty}H\_{k}\,\pars{-t}^{k}}\,\dd t \\[5mm] = &\ -\int\_{0}^{\infty} t^{\color{red}{1/2} - 1} \bracks{% \sum\_{k = 0}^{\infty} \color{red}{H\_{k}\,\Gamma\pars{1 + k}} {\pars{-t}^{k} \over k!}}\dd t \end{align} With the [Ramanujan's Master Theorem](https://en.wikipedia.org/wiki/Ramanujan%27s_master_theorem): \begin{align} &\bbox[5px,#ffd]{\int\_{0}^{\infty} {x \over \root{\expo{x} - 1}}\,\dd x} \\[5mm] = &\ -\ \underbrace{\Gamma\pars{\color{red}{1 \over 2}}} \_{\ds{\root{\pi}}}\ \underbrace{\quad H\_{\color{red}{-1/2}}\quad} \_{\ds{\int\_{0}^{1}{1- t^{\color{red}{-1/2}} \over 1 - t} \,\dd t}}\ \Gamma\pars{1 \color{red}{- {1 \over 2}}} \\[5mm] = &\ -\pi\int\_{0}^{1}{1- t^{-1} \over 1 - t^{2}}\,2t\,\dd t = 2\pi\int\_{0}^{1}{\dd t \over 1 + t} \\[5mm] = &\ \bbx{2\pi\ln\pars{2}} \approx 4.3552 \\ & \end{align}
10,115,234
Is there any way I can save all the things that is happening on my Windows 7 Command Prompt in a file. So that I can see what are the things that got printed on the console. I am running a multithreaded Java Program from the command prompt as- ``` java -server -Xms512m -Xmx512m -XX:PermSize=512m -XX:MaxPermSize=512m -Duser.timezone=GMT-7 –jar BatchMain.jar -taskId V3-PERSONALIZATIONGEO-SAMPLE-TASK -noofthreads 1 -timeout 5 -numberOfIP 1000 -privateIPAddress false ``` And it prints lot of things on to the command prompt, And I want to store all these things that are getting printed on the console into a file.
2012/04/11
[ "https://Stackoverflow.com/questions/10115234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/663148/" ]
You can record mouse clicks using the clientX and clientY properties of the mouse event object: ``` document.addEventListener('click', function(event){event.clientX;event.clientY;}, false); ``` The above code is just a demonstration, it isn't even cross browser compatible. `event.clientX` and `event.clientY` hold the mouse coordinates.
*[demo](http://jsbin.com/uzadoy/edit#javascript,html,live)* ----------------------------------------------------------- I used the jQuery library. ``` var boxX = 0; var boxY = 0; var box = '<div class="box" />'; // define the .box element for(var i = 0; i<100;i++){ // create 100 boxes $('#grid').append(box); } $('.box').on('click',function(){ boxX = $(this).position().left; boxY = $(this).position().top; $(this).text('X='+ boxX +' , Y='+ boxY); }); ``` Instead of `.position()` (to get the element position from the parent element) you can use `.offset()` to get the element offset from window boundaries.
37,007,271
In Octave, I have this cell array: `y = { 'hello' 'world' 'a' 'world' 'g' 'I' 'w' 'hi'};` I need to be able to remove the duplicates of an element. So for example I want to remove the duplicates of `'world'`, this should be the output: ``` ans = { [1,1] = hello [1,2] = a [1,3] = g [1,4] = I [1,5] = w [1,6] = hi } ``` Aside from the usual loop until n times, is there a function in Octave that does this? I've been looking for ways to do this but found nothing. From what I've seen, `unique` does not do this as it removes all duplicates.
2016/05/03
[ "https://Stackoverflow.com/questions/37007271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6213337/" ]
As you already have inside your code (but commented out) you can use `json_decode($_POST['table'],true);` When you us this function you get a array, with 7 entrys (in this example). Like this: ``` $data = json_decode($_POST['table'], true); ``` The error occurs, because you `echo` the variable. Use `var_dump($data)` to see, that its really a array. `$data[0]`, `$data[1]`, ... holds then the data. EDIT: Because you have nested array, you have to access the subarray again, like this: ``` $data = json_decode($_POST['table'], true); $var = $data[0][0]; // holds "Cadastrado em" $var2 = $data[0][1]; // holds "Data da Venda" ``` I'm not sure, if this is intended, that you have an array in an array.
Your commented line ``` $data = json_decode($_POST['table'],true); ``` is good, but you can't echo an array. This will fail: ``` echo $data; ``` This will work: ``` print_r($data); ```
115,530
I have a big shapefile that contains all the buildings and houses of the town that I work in (approx. 90,000 features). The data of the buildings/houses are saved by the town's surveying engineers and due to bad practice and the access of different surveyors to that data, many buildings/houses have been saved twice and show up in the map as duplicates. Some of them are exactly duplicated (they appear one over the other) while others are duplicated with a space between the two objects (like one object is inside the other - see the attached screen shot). ![enter image description here](https://i.stack.imgur.com/sJIsk.png) I want to clean that data so that I have only the correct buildings/houses in the town so my question is: Is there any GIS analysis or SQL expression that I can run to find all the duplicated features (both the exact ones and the ones that are located inside others)? I have both ArcGIS and QGIS so I am open to all your suggestions.
2014/09/29
[ "https://gis.stackexchange.com/questions/115530", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/22887/" ]
You can do this in SQL using a spatial self join. You don't state which SQL dialect you are using, so this example uses Postgres/Postgis, but it could be easily adapted to Oracle or SQL Server. Assuming a table called buildings, with geometry stored in a column called geom: ``` SELECT a.id, b.id from buildings a, buildings b WHERE ST_INTERSECTS(a.geom, b.geom) AND a.id < b.id; ``` This will find the intersects. If you want total equality then replace ST\_Intersects with ST\_Equals. Or, just combine the two: ``` SELECT a.id, b.id from buildings a, buildings b WHERE (ST_INTERSECTS(a.geom, b.geom) OR ST_EQUALS(a.geom, b.geom)) AND a.id < b.id; ``` Note, the a.id < b.id means that you only consider half the cases in the self join, which makes it a) faster and b) gives you a list you can use to delete half of the overlapping polygons without deleting them all. Clearly, this is still an O(n²) algorithm, but in practice, will be a lot quicker if you have a spatial index in place -- which is really a total requirement for any non-trivial data set. You might need to massage this a little bit to fit some definition of overlapping -- you don't want to delete neighboring houses that have been badly surveyed.
In QGIS you can create a Virtual Layer with the query: ``` select a.id, a.geometry from yourlayername a join yourlayername b on st_equals(a.geometry, b.geometry) where a.id<b.id ``` Which will join the layer to itself where the geometries are the same but have different id's
54,116,784
I have a JTable application. I need to change the cell values and save the data, but only cells with index smaller than or equal to 4 are within the array bounds. ``` package fi.allu.neliojuuri; import com.sun.glass.events.KeyEvent; import javax.swing.*; import javax.swing.table.AbstractTableModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.File; import javax.swing.event.CellEditorListener; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; public class Neliojuuri extends JPanel implements ActionListener, ItemListener, TableModelListener { String newline = "\n"; private JTable table; private JCheckBox rowCheck; private JCheckBox columnCheck; private JCheckBox cellCheck; private ButtonGroup buttonGroup; private JTextArea output; private String[] sarakenimet = new String[70]; private String[] sisakkainen = new String[70]; private Object[][] ulkoinen = new String[71][71]; private DefaultTableModel oletusmalli = null; private CellEditorListener solumuokkaaja = null; public Neliojuuri() { super(); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); for (int i = 0; i < 70; i++) { sarakenimet[i] = String.valueOf(i + 1); } for (int i = 0; i < sisakkainen.length; i++) { sisakkainen[i] = String.valueOf(i + 1); } for (int i = 0; i < ulkoinen.length; i++) { ulkoinen[i] = sisakkainen; } table = new JTable(ulkoinen, sarakenimet); table.setPreferredScrollableViewportSize(new Dimension(500, 210)); table.setFillsViewportHeight(true); table.setRowHeight(30); TableColumnModel sarakeMalli = table.getColumnModel(); for (int i = 0; i < 70; i++) { sarakeMalli.getColumn(i).setPreferredWidth(75); } oletusmalli = new javax.swing.table.DefaultTableModel(); table.setModel(oletusmalli); String[] sarakenimet = new String[70]; for (int i = 0; i < 70; i++) { sarakenimet[i] = String.valueOf(i + 1); } String[] sisakkainen = new String[70]; for (int i = 0; i < sisakkainen.length; i++) { sisakkainen[i] = String.valueOf(i + 1); } Object[][] ulkoinen = new String[71][71]; for (int i = 0; i < ulkoinen.length; i++) { ulkoinen[i] = sisakkainen; } oletusmalli.setColumnIdentifiers(sarakenimet); for (int count = 0; count < 70; count++){ oletusmalli.insertRow(count, sisakkainen); } table.getSelectionModel().addListSelectionListener(new RowListener()); table.getColumnModel().getSelectionModel(). addListSelectionListener(new ColumnListener()); add(new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.getModel().addTableModelListener(this); add(new JLabel("Selection Mode")); buttonGroup = new ButtonGroup(); addRadio("Multiple Interval Selection").setSelected(true); addRadio("Single Selection"); addRadio("Single Interval Selection"); add(new JLabel("Selection Options")); rowCheck = addCheckBox("Row Selection"); rowCheck.setSelected(true); columnCheck = addCheckBox("Column Selection"); cellCheck = addCheckBox("Cell Selection"); cellCheck.setEnabled(false); output = new JTextArea(5, 40); output.setEditable(false); output.setFont(new Font("Segoe UI", Font.PLAIN, 20)); add(new JScrollPane(output)); } private JCheckBox addCheckBox(String text) { JCheckBox checkBox = new JCheckBox(text); checkBox.addActionListener(this); add(checkBox); return checkBox; } private JRadioButton addRadio(String text) { JRadioButton b = new JRadioButton(text); b.addActionListener(this); buttonGroup.add(b); add(b); return b; } public void actionPerformed(ActionEvent e) { JFileChooser tiedostovalitsin = new JFileChooser(); JMenuItem source = (JMenuItem)(e.getSource()); if (source.getText() == "Save") { int palautusArvo = tiedostovalitsin.showSaveDialog(Neliojuuri.this); if (palautusArvo == JFileChooser.APPROVE_OPTION) { File tiedosto = tiedostovalitsin.getSelectedFile(); // Tallenna tiedosto oikeasti for (int i = 0; i < oletusmalli.getRowCount(); i++) { System.out.println(oletusmalli.getValueAt(1, i).toString()); } System.out.println(tiedosto.getName()); } } String command = e.getActionCommand(); //Cell selection is disabled in Multiple Interval Selection //mode. The enabled state of cellCheck is a convenient flag //for this status. if ("Row Selection" == command) { table.setRowSelectionAllowed(rowCheck.isSelected()); //In MIS mode, column selection allowed must be the //opposite of row selection allowed. if (!cellCheck.isEnabled()) { table.setColumnSelectionAllowed(!rowCheck.isSelected()); } } else if ("Column Selection" == command) { table.setColumnSelectionAllowed(columnCheck.isSelected()); //In MIS mode, row selection allowed must be the //opposite of column selection allowed. if (!cellCheck.isEnabled()) { table.setRowSelectionAllowed(!columnCheck.isSelected()); } } else if ("Cell Selection" == command) { table.setCellSelectionEnabled(cellCheck.isSelected()); } else if ("Multiple Interval Selection" == command) { table.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); //If cell selection is on, turn it off. if (cellCheck.isSelected()) { cellCheck.setSelected(false); table.setCellSelectionEnabled(false); } //And don't let it be turned back on. cellCheck.setEnabled(false); } else if ("Single Interval Selection" == command) { table.setSelectionMode( ListSelectionModel.SINGLE_INTERVAL_SELECTION); //Cell selection is ok in this mode. cellCheck.setEnabled(true); } else if ("Single Selection" == command) { table.setSelectionMode( ListSelectionModel.SINGLE_SELECTION); //Cell selection is ok in this mode. cellCheck.setEnabled(true); } //Update checkboxes to reflect selection mode side effects. rowCheck.setSelected(table.getRowSelectionAllowed()); columnCheck.setSelected(table.getColumnSelectionAllowed()); if (cellCheck.isEnabled()) { cellCheck.setSelected(table.getCellSelectionEnabled()); } } private void outputSelection() { output.append(String.format("Lead: %d, %d. ", table.getSelectionModel().getLeadSelectionIndex(), table.getColumnModel().getSelectionModel(). getLeadSelectionIndex())); output.append("Rows:"); for (int c : table.getSelectedRows()) { output.append(String.format(" %d", c)); } output.append(". Columns:"); for (int c : table.getSelectedColumns()) { output.append(String.format(" %d", c)); } output.append(".\n"); } @Override public void itemStateChanged(ItemEvent e) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void tableChanged(TableModelEvent e) { int rivi = e.getFirstRow(); int sarake = e.getColumn(); TableModel malli = (TableModel)e.getSource(); String sarakeNimi = malli.getColumnName(sarake); Object data = malli.getValueAt(rivi, sarake); MyTableModel taulumalli = new MyTableModel(); taulumalli.setValueAt(data, rivi, sarake); System.out.println("rivi: " + rivi + " sarake: " + sarake + " data: " + data); } private void setValueAt(Object data, int rivi, int sarake) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } private class RowListener implements ListSelectionListener { public void valueChanged(ListSelectionEvent event) { if (event.getValueIsAdjusting()) { return; } output.append("ROW SELECTION EVENT. "); outputSelection(); } } private class ColumnListener implements ListSelectionListener { public void valueChanged(ListSelectionEvent event) { if (event.getValueIsAdjusting()) { return; } output.append("COLUMN SELECTION EVENT. "); outputSelection(); } } class MyTableModel extends AbstractTableModel { private String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"}; private Object[][] data = { {"Kathy", "Smith", "Snowboarding", new Integer(5), new Boolean(false)}, {"John", "Doe", "Rowing", new Integer(3), new Boolean(true)}, {"Sue", "Black", "Knitting", new Integer(2), new Boolean(false)}, {"Jane", "White", "Speed reading", new Integer(20), new Boolean(true)}, {"Joe", "Brown", "Pool", new Integer(10), new Boolean(false)} }; public int getColumnCount() { return columnNames.length; } public int getRowCount() { return data.length; } public String getColumnName(int col) { return columnNames[col]; } public Object getValueAt(int row, int col) { return data[row][col]; } /* * JTable uses this method to determine the default renderer/ * editor for each cell. If we didn't implement this method, * then the last column would contain text ("true"/"false"), * rather than a check box. */ public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } /* * Don't need to implement this method unless your table's * editable. */ public boolean isCellEditable(int row, int col) { //Note that the data/cell address is constant, //no matter where the cell appears onscreen. if (col < 2) { return false; } else { return true; } } /* * Don't need to implement this method unless your table's * data can change. */ public void setValueAt(Object value, int row, int col) { data[row][col] = value; fireTableCellUpdated(row, col); } } public JMenuBar luoValikkoPalkki() { JMenuBar valikkopalkki = new JMenuBar(); JMenu valikko = new JMenu("File"); valikko.setMnemonic(KeyEvent.VK_F); valikko.getAccessibleContext().setAccessibleDescription( "File saving menu"); valikkopalkki.add(valikko); JMenuItem valikkoitem = new JMenuItem("Save", KeyEvent.VK_S); valikkoitem.setAccelerator(KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_S, ActionEvent.CTRL_MASK)); valikkoitem.addActionListener(this); valikko.add(valikkoitem); return valikkopalkki; } /** * Create the GUI and show it. For thread safety, this method should be * invoked from the event-dispatching thread. */ private static void createAndShowGUI() { //Disable boldface controls. UIManager.put("swing.boldMetal", Boolean.FALSE); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } //Create and set up the window. JFrame frame = new JFrame("Neliöjuuri"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Neliojuuri neliojuuri = new Neliojuuri(); frame.setJMenuBar(neliojuuri.luoValikkoPalkki()); //Create and set up the content pane. Neliojuuri newContentPane = new Neliojuuri(); newContentPane.setOpaque(true); //content panes must be opaque frame.setContentPane(newContentPane); //Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } } ``` Stacktrace: ``` Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 5 at fi.allu.neliojuuri.Neliojuuri$MyTableModel.setValueAt(Neliojuuri.java:356) at fi.allu.neliojuuri.Neliojuuri.tableChanged(Neliojuuri.java:261) at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableModel.java:296) at javax.swing.table.AbstractTableModel.fireTableCellUpdated(AbstractTableModel.java:275) at javax.swing.table.DefaultTableModel.setValueAt(DefaultTableModel.java:666) at javax.swing.JTable.setValueAt(JTable.java:2744) at javax.swing.JTable.editingStopped(JTable.java:4729) at javax.swing.AbstractCellEditor.fireEditingStopped(AbstractCellEditor.java:141) at javax.swing.DefaultCellEditor$EditorDelegate.stopCellEditing(DefaultCellEditor.java:368) at javax.swing.DefaultCellEditor.stopCellEditing(DefaultCellEditor.java:233) at javax.swing.JTable$GenericEditor.stopCellEditing(JTable.java:5473) at javax.swing.DefaultCellEditor$EditorDelegate.actionPerformed(DefaultCellEditor.java:385) at javax.swing.JTextField.fireActionPerformed(JTextField.java:508) at javax.swing.JTextField.postActionEvent(JTextField.java:721) at javax.swing.JTextField$NotifyAction.actionPerformed(JTextField.java:836) at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1668) at javax.swing.JComponent.processKeyBinding(JComponent.java:2882) at javax.swing.JComponent.processKeyBindings(JComponent.java:2929) at javax.swing.JComponent.processKeyEvent(JComponent.java:2845) at java.awt.Component.processEvent(Component.java:6316) at java.awt.Container.processEvent(Container.java:2239) at java.awt.Component.dispatchEventImpl(Component.java:4889) at java.awt.Container.dispatchEventImpl(Container.java:2297) at java.awt.Component.dispatchEvent(Component.java:4711) at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1954) at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:835) at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:1103) at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:974) at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:800) at java.awt.Component.dispatchEventImpl(Component.java:4760) at java.awt.Container.dispatchEventImpl(Container.java:2297) at java.awt.Window.dispatchEventImpl(Window.java:2746) at java.awt.Component.dispatchEvent(Component.java:4711) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760) at java.awt.EventQueue.access$500(EventQueue.java:97) at java.awt.EventQueue$3.run(EventQueue.java:709) at java.awt.EventQueue$3.run(EventQueue.java:703) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84) at java.awt.EventQueue$4.run(EventQueue.java:733) at java.awt.EventQueue$4.run(EventQueue.java:731) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74) at java.awt.EventQueue.dispatchEvent(EventQueue.java:730) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93) at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) ``` I expect to be able to change all the cell values in the table, but I can only do so to a few of them. Cells with index greater than or equal to 5 return ArrayIndexOutOfBounds error.
2019/01/09
[ "https://Stackoverflow.com/questions/54116784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5964318/" ]
With ES6, by calling the entries() method on the array you can do it => ``` const array = [1, 2, 3]; for (const [i, v] of array.entries()) { //Handled last iteration if( i === array.length-1) { continue; } console.log(i, v)// it will print index and value } ```
``` pre> const chain = ['ABC', 'BCA', 'CBA']; let findOut; for (const lastIter of chain) { findOut = lastIter; //Last iteration value stored in each iteration. } ``` console.log(findOut); ``` enter code here CBA ```
1,232
Les différentes catégories de pronoms personnels — sujet, complément direct, complément indirect — sont en général décrites comme des survivances en français du système de cas du latin. Pour mémoire ``` Je | Pronom personnel sujet | Nominatif Me | Pronom personnel complément direct | Accusatif Moi | Pronom personnel complément indirect | Datif ``` Y a-t-il d'autres ? Pourquoi celles-ci ont-elles survécu ?
2011/09/19
[ "https://french.stackexchange.com/questions/1232", "https://french.stackexchange.com", "https://french.stackexchange.com/users/82/" ]
En ancien français, le système casuel s'était déjà partiellement effondré, et les noms ne présentaient plus que deux cas : le *cas sujet* et le *cas régime*. Dans la plupart des cas, le mot n'a eu de descendance que sous sa forme au cas régime, mais il y a des exceptions. [Albert Wikipédia](http://fr.wikipedia.org/wiki/R%C3%A9gime_%28cas%29) en cite quatre : gars / garçon, pâtre / pasteur, nonne / nonnain et pute / putain. (Je dois avouer que je ne connaissais que le premier et le dernier de cette liste). On peut donc voir ces doublets comme des traces du système casuel latin, même si les différentes formes s'opposent maintenant par leur sens plutôt que par leur fonction.
Je dirais les pronoms relatifs: qui, que, dont
28,566,616
I need to remove a line containing "not a dynamic executable" and a previous line from a stream using grep, awk, sed or something other. My current working solution would be to tr the entire stream to strip off newlines then replace the newline preceding my match with something else using sed then use tr to add the newlines back in and then use grep -v. I'm somewhat weary of artifacts with this approach, but I don't see how else I can to it at the moment: ``` tr '\n' '|' | sed 's/|\tnot a dynamic executable/__MY_REMOVE/g' | tr '|' '\n' ``` EDIT: Input is a list of mixed files piped to xargs ldd, basically I want to ignore all output about non library files since that has nothing to do with what I'm doing next. I didn't want to use lib\*.so mask since that could concievably be different
2015/02/17
[ "https://Stackoverflow.com/questions/28566616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1933452/" ]
Most simply with `pcregrep` in multi-line mode: ``` pcregrep -vM '\n\tnot a dynamic executable' filename ``` If `pcregrep` is not available to you, then `awk` or `sed` can also do this by reading one line ahead and skipping the printing of previous lines when a marker line appears. You could be boring (and sensible) with awk: ``` awk '/^\tnot a dynamic executable/ { flag = 1; next } !flag && NR > 1 { print lastline; } { flag = 0; lastline = $0 } END { if(!flag) print }' filename ``` That is: ``` /^\tnot a dynamic executable/ { # in lines that start with the marker flag = 1 # set a flag next # and do nothing (do not print the last line) } !flag && NR > 1 { # if the last line was not flagged and # is not the first line print lastline # print it } { # and if you got this far, flag = 0 # unset the flag lastline = $0 # and remember the line to be possibly # printed. } END { # in the end if(!flag) print # print the last line if it was not flagged } ``` But sed is fun: ``` sed ':a; $! { N; /\n\tnot a dynamic executable/ d; P; s/.*\n//; ba }' filename ``` Explanation: ``` :a # jump label $! { # unless we reached the end of the input: N # fetch the next line, append it /\n\tnot a dynamic executable/ d # if the result contains a newline followed # by "\tnot a dynamic executable", discard # the pattern space and start at the top # with the next line. This effectively # removes the matching line and the one # before it from the output. # Otherwise: P # print the pattern space up to the newline s/.*\n// # remove the stuff we just printed from # the pattern space, so that only the # second line is in it ba # and go to a } # and at the end, drop off here to print # the last line (unless it was discarded). ``` Or, if the file is small enough to be completely stored in memory: ``` sed ':a $!{N;ba}; s/[^\n]*\n\tnot a dynamic executable[^\n]*\n//g' filename ``` Where ``` :a $!{ N; ba } # read the whole file into # the pattern space s/[^\n]*\n\tnot a dynamic executable[^\n]*\n//g # and cut out the offending bit. ```
Always keep in mind that while grep and sed are line-oriented awk is record-oriented and so can easily handle problems that span multiple lines. It's a guess given you didn't post any sample input and expected output but it sounds like all you need is (using GNU awk for multi-char RS): ``` awk -v RS='^$' -v ORS= '{gsub(/[^\n]+\n\tnot a dynamic executable/,"")}1' file ```
41,505,085
I have below code i need to call function on click of button. but it is not atall calling those function. What is wrong in below code. ``` <!DOCTYPE html> <html> <body> <input type="button" value="Copy Parent Text" id="CopyParent" onclick="getRate("SEK", "USD")"> <input type="button" value="Copy Child Text" id="CopyChild" onclick="getRate("USD", "SEK")"> <script type="text/javascript"> function getRate(from, to) { alert("1"); var script = document.createElement('script'); script.setAttribute('src', "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D"+from+to+"%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json&callback=parseExchangeRate"); document.body.appendChild(script); } function parseExchangeRate(data) { var name = data.query.results.row.name; var rate = parseFloat(data.query.results.row.rate, 10); alert("Exchange rate " + name + " is " + rate); } </script> </body> </html> ``` Please help me on this.
2017/01/06
[ "https://Stackoverflow.com/questions/41505085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6611071/" ]
You have a syntax error because you're enclosing double quotes within double quotes. If you look in the browser's console when you click the button it will show you the error. You can change the HTML like this to resolve it: ``` <input type="button" value="Copy Parent Text" id="CopyParent" onclick="getRate('SEK', 'USD')"> <input type="button" value="Copy Child Text" id="CopyChild" onclick="getRate('USD', 'SEK')"> ```
You have add double `quot` inside double `quote` `"getRate("USD", "SEK")"`. Just change you html like below: ``` <input type="button" value="Copy Parent Text" id="CopyParent" onclick='getRate("SEK", "USD")'> <input type="button" value="Copy Child Text" id="CopyChild" onclick='getRate("USD", "SEK")'> ```
13,452,522
Im using the [MBProgressHUD](https://github.com/jdg/MBProgressHUD) to make an overview loading screen while logging out in my ipad app. That progress takes some time because I have to encrypt some bigger files. Because Im doing it in a background thread and the [MBProgressHUD](https://github.com/jdg/MBProgressHUD) is animating on the main thread, I had to do something to know when my background thread is finished. As a test, I did it like that: ``` MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; hud.mode = MBProgressHUDAnimationFade; hud.labelText = @"Do something..."; [self performSelectorInBackground:@selector(doSomethingElse) withObject:nil]; ``` And method doSomethingElse: ``` -(void)doSomethingElse { [self encrypt]; [self performSelectorOnMainThread:@selector(doSomethingElseDone) withObject:nil waitUntilDone:YES]; } ``` And method doSomethingElseDone: ``` -(void)logoutInBackgroundDone { [MBProgressHUD hideHUDForView:self.view animated:YES]; } ``` The solution works but I think there must be a better way? How can I do that on a better way? Any help is really appreciated.
2012/11/19
[ "https://Stackoverflow.com/questions/13452522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/753628/" ]
You can directly dismiss the `MBProgressHUD` from `doSomethingElse` method using `dispatch_async` ``` -(void)doSomethingElse { [self encrypt]; dispatch_async(dispatch_get_main_queue(), ^{ [MBProgressHUD hideHUDForView:self.view animated:YES]; }); } ```
Create an atomic property you can get to ``` @property BOOL spinning; ``` and ``` - (void)myTask { while ( self.spinning ) { usleep(1000*250); // 1/4 second } } ``` then use something in your view controller like ``` HUD = [[MBProgressHUD alloc] initWithView:self.view]; [self.view addSubview:HUD]; [HUD showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES]; ``` This way the HUD will remove itself when spinning becomes false. The spinner has to be atomic since it will be referenced in a background thread. Whatever you are waiting on can simply set the spinner property to false from any thread to indicate it's done. This is under ARC.
23,088,558
Is there a way to detect on WP8 that web browser control is automatically opening media files using media player which then activate OnNavigateFrom event, and how to differ that event from OnNavigateFrom event that is activated when backBtn,Start or search button pressed. This is important because different code need to be activated in those cases. Is there a way to detect when web browser control is selecting URL that is some kind of media URL, and to prevent URL to be open in external application, but to open URL in web browser control or some media element that is existing in application?
2014/04/15
[ "https://Stackoverflow.com/questions/23088558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3536623/" ]
Derp, looks like the variable g appeared out of nowhere. When I changed it to i, it started working. Why didn't I get an error in the console, though? Do promises suppress errors in some way?
You've run into swallowed exception issue. Proposed `catch` in accepted answer is actually same as doing `then(null, fn)`, it's also transformation function that will swallow eventual exceptions (so not real solution for your problem). If you just want to process the value, cleanest way is via `done` (with no error swallowing implied) ``` q.done(function (result) { // Process the result }); ``` However mind that native promises do not provide `done`, and as there's no solution for error swallowing proposed, it's best to not use native promises (until that's solved) and use one of the popular JS libraries instead (most of them provide `done`). See also: * <https://stackoverflow.com/questions/22294425/promises-ecmascript-6-vs-3rd-party-libraries/22296765#22296765> * [promise.then error swallowing](http://www.medikoo.com/asynchronous-javascript-interfaces/promises-then-error-swallowing/?notes) (it's presentation slides, use cursors to move around).
351,086
I want to create a style that makes the selected text have something similar to margin/padding in CSS, but in the horizontal axis only. Example: > > Normal text normal text       New Style       normal text > > >
2011/10/27
[ "https://superuser.com/questions/351086", "https://superuser.com", "https://superuser.com/users/95744/" ]
I tried this and it works. 1. Select the document you wish to include additional spaces between text 2. Use the Search button shortcut ( CTRL + H ). 3. In the find section type " " (i.e. one space character) 4. In the replace section type the number of spaces you wish to include 5. Click on the Replace All button You shall have you document with the extended number of spaces you desire between words. Thanks.
Highlight the space you want to enlarge. Access the font style and try various fonts. Typically "CONSOLAS" and "chi-boot" have particularly wide spaces between words, the alphabet of your text will remain unchanged. Once you have done one space to your satisfaction, others can be done by simply copy and paste of the first. - Since it is a single space, albeit by an alternative font, this method even fools the spell checker. I've used this method in Headings, never in a whole document, but it MAY even work with the "Search & Replace" function, in lieu Copy & Paste.
32,668,984
I'm inputting a program that I'm to assess into visual studio to see where things are taking place, but it's closing immediately. Here's the code: ``` #include <iostream> int dowork(int a, int b); int main() { using namespace std; int x = 4, y = 6; cout << "Welcome to SIT153..." << endl; x = dowork(x, y); for (int i = 0; i < x; i++) { int y = i + 3; if (y > 6) cout << i << " + 3 = " << y << endl; else cout << "Not yet" << endl; } cout << "y = " << y << endl; return 0; } int dowork(int a, int b) { return a + b; } ``` And here's the debug output > > 'ConsoleApplication4.exe' (Win32): Loaded > 'C:\Users\barne\_000\Documents\Visual Studio > 2013\Projects\ConsoleApplication4\Debug\ConsoleApplication4.exe'. > Symbols loaded. > > > 'ConsoleApplication4.exe' (Win32): Loaded > 'C:\Windows\SysWOW64\ntdll.dll'. Cannot find or open the PDB file. > > > 'ConsoleApplication4.exe' (Win32): Loaded > 'C:\Windows\SysWOW64\kernel32.dll'. Cannot find or open the PDB file. > > > 'ConsoleApplication4.exe' (Win32): Loaded > 'C:\Windows\SysWOW64\KernelBase.dll'. Cannot find or open the PDB > file. > > > 'ConsoleApplication4.exe' (Win32): Loaded > 'C:\Windows\SysWOW64\msvcp120d.dll'. Cannot find or open the PDB file. > > > 'ConsoleApplication4.exe' (Win32): Loaded > 'C:\Windows\SysWOW64\msvcr120d.dll'. Cannot find or open the PDB file. > > > The thread 0x18dc has exited with code 0 (0x0). > > > The thread 0x2194 has exited with code 0 (0x0). > > > The thread 0x1608 has exited with code 0 (0x0). > > > The program '[9788] ConsoleApplication4.exe' has exited with code 0 > (0x0). > > > Help?
2015/09/19
[ "https://Stackoverflow.com/questions/32668984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5353702/" ]
A floating point literal without a suffix is of type `double`. Suffixing it with an `f` makes a literal of type `float`. When assigning to a variable, the right operand to `=` is converted to the type of the left operand, thus you observe truncation. When comparing, the operands to `==` are converted to the larger of the two operands, so `x == 0.1` is like `(double)x == 0.1`, which is false since `(double)(float)0.1` is not equal to `0.1` due to rounding issues. In `x == 0.1f`, both operands have type `float`, which results in equality on your machine. Floating point math is tricky, read the standard for more details.
`0.1` is a double value whereas `0.1f` is a float value. The reason we can write `float x=0.1` as well as `double x=0.1` is due to implicit conversions . But by using suffix `f` you make it a float type . In this - ``` if(x == 0.1) ``` is flase because `0.1` is not exactly `0.1` at some places after decimal .There is also conversion in this to higher type i.e `double`. Converting to `float` and then to `double` , there is loss of information as also `double` as higher precession than `float` so it differs .
49,781,097
I want to use Google architecture components in my app, but after updating android studio to version 3.1.1 when I add `android.arch.lifecycle:extensions:1.1.1` dependency into app.gradle file, it will show `Failed to resolve: support-fragment` My gradle version is 4.4 [![enter image description here](https://i.stack.imgur.com/Pxz23.png)](https://i.stack.imgur.com/Pxz23.png) This is app gardle: ``` apply plugin: 'com.android.application' android { compileSdkVersion 27 defaultConfig { applicationId "ir.apptori.myapplication" minSdkVersion 17 targetSdkVersion 27 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:27.1.1' implementation 'com.android.support.constraint:constraint-layout:1.0.2' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.1' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' implementation "android.arch.lifecycle:extensions:1.1.1" } ``` Please guid me how to fix it, Thanks
2018/04/11
[ "https://Stackoverflow.com/questions/49781097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3610737/" ]
I had a similar error and changing the `repositories` order so that `google()` comes before `jcenter()` fixed it. I had to change the order for the `repositories` within `buildscript` **and** `allprojects` in the top level `build.gradle` file. Please see this commit: <https://github.com/kunadawa/ud851-Exercises/commit/9f6720ef4d52c71b206ddaa8477f2cf6e77a66f4>
i add this line in build.gradle and fixed bug : `implementation 'androidx.fragment:fragment:1.2.5'`
697,098
I have the following code in accessing a database via nhibernate: ``` ISessionFactory factory = new NHibernate.Cfg.Configuration().Configure().BuildSessionFactory(); using (ISession session = factory.OpenSession()) { ICriteria sc = session.CreateCriteria(typeof(Site)); siteList = sc.List(); session.Close(); } factory.Close(); ``` I wonder whether it is possible to wrap it in this way: ``` using (var factory= new NHibernate.Cfg.Configuration().Configure().BuildSessionFactory()) { var session = factory.OpenSession(); ICriteria sc = session.CreateCriteria(typeof(Site)); siteList = sc.List(); } ``` As far as I understand, all the connection inside the using() block will be automatically closed. So I guess that the second statement is fully equivalent to the first. Am I right?
2009/03/30
[ "https://Stackoverflow.com/questions/697098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
This is what you usually do: ``` using (ISession session = factory.OpenSession()) { ICriteria sc = session.CreateCriteria(typeof(Site)); siteList = sc.List(); } ``` However you open build your factory just once - at the start of application. You should not really bother by closing it (unless some specific cases) since it's the application end that cleans it up. Your factory usually resides in one well defined place - as a singleton. And to help you understand - using is just c# construct which equals to following: ``` try { ISession session = sf.OpenSession(); ..... } finally { session.Dispose(); } ```
Your 2nd code example has at least one bad practice: you're building your SessionFactory, and afterwards you destroy it. So, I assume that you build your SessionFactory each time you need to have a session ?
6,866,464
I'm currently running into an issue of needing to pass a SAFEARRAY(GUID) as a return value from C++ to C#. Currently the C# side is using an Interop dll generated from Tlbimp.exe (Type Library Importer). The IDL is: ``` HRESULT GetGuids( [out]SAFEARRAY(GUID)* guids); ``` I've also tried [out, retval] The function signature is: ``` HRESULT WINAPI MyClass::GetGuids(SAFEARRAY** guids) ``` If I use `SafeArrayCreate()` or `SafeArrayCreateVector()`: ``` SAFEARRAY* psa psa = SafeArrayCreate(VT_CLSID, 1, rgsabound); ``` I get a NULL `SAFEARRAY` pointer, which is supposed to indicate `E_OUTOFMEMORY` which is incorrect. What I did find was that `VT_CLSID` is only for Ole property sets and not SAFEARRAY's: <http://poi.apache.org/apidocs/org/apache/poi/hpsf/Variant.html> Its indicated that CLSID is I've also tried the alternate means of constructing the safe array with: `SafeArrayAllocDescriptor()` and `SafeArrayAllocData()`. ``` hResult = SafeArrayAllocDescriptor(1, guids) hResult = SafeArrayAllocData(*guids); ``` This lets me create the array, but when populating it with `SafeArrayPutElement()` I get an HRESULT of 0x80070057 (The parameter is incorrect). This is probably due to the fact it takes the `VT_CLSID` parameter as well I can populate it manually with `SafeArrayAccessData()` ``` GUID* pData = NULL; hResult = SafeArrayAccessData(*guids, (void**)&pData); ``` but I get an error from the C# side: "The value does not fall within the expected Range" I'm not sure how to accomplish the desired functionality of returning a SAFEARRAY(GUID) to C# either by a retval or out parameter. It seems it should be simple - there are many areas in the IDL where I'm already passing GUID's without any UDT's or marshalling. Everything works fine until I need to pass them in a SAFEARRAY. Any help is appreciated, Thanks in advance
2011/07/28
[ "https://Stackoverflow.com/questions/6866464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/488267/" ]
You're absolutely right - the problem is that VT\_CLSID isn't allowed in either VARIANT or SAFEARRAY. It boils down to GUID not being an Automation-compatible type. I often need to do the same thing that you're trying. The easiest way around the problem is to convert the GUID to a string and then pass SAFEARRAY(VT\_BSTR). It goes against the grain somewhat to do this conversion, but I suppose you could take the view that there's marshaling going on anyway and this conversion is a type of marshaling.
The way to do it involves passing GUIDs as a UDT (user defined type). For that, we use a SAFEARRAY of VT\_RECORD elements which will be initialized with SafeArrayCreateEx. But first, we have to get a pointer to IRecordInfo that can describe the type. Since GUID is defined in the windows/COM headers and has no uuid attached to it, we have to use something else to get an IRecordInfo interface. Basically, the two options are to create a struct that has the same memory layout as GUID in your own TypeLib, or use mscorlib::Guid defined in mscorlib.tlb ``` #import <mscorlib.tlb> no_namespace named_guids IRecordInfo* pRecordInfo = NULL; GetRecordInfoFromGuids( LIBID_mscorlib, 1, 0, 0, __uuidof(Guid), &pRecordInfo ); SafeArrayCreateEx( VT_RECORD, 1, &sab, pRecordInfo ); ```
576,228
Why are the methods of the Math class static ?
2009/02/23
[ "https://Stackoverflow.com/questions/576228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
They are static because the methods do not rely on [instance variables](http://en.wikipedia.org/wiki/Instance_variable) of the Math class.
They can be invoked as if they are a mathematical code library.
36,379,956
How can I link to a user's profile view without getting a `no implicit conversion of Fixnum into String` error? What I currently have: ``` - @questions.each do |question| = link_to question.user.username, "/users/"+question.user.id ``` Basically what I am trying to achieve is: When the user clicks on a link, he will get redirected to the original poster's profile page. ex: **localhost:3000/users/1** Home controller: ``` def profile if !user_signed_in? redirect_to new_user_session_path end if User.find_by_id(params[:id]) @user = User.find(params[:id]) else redirect_to root_path end end ``` Routes: ``` Rails.application.routes.draw do root 'home#home' devise_for :users get "/users/:id" => "home#profile" get "home" => "home#feed" get "questions" => "home#questions" resources :questions end ```
2016/04/02
[ "https://Stackoverflow.com/questions/36379956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5841629/" ]
You need to cast the id manually to a string: ``` = link_to question.user.username, "/users/"+question.user.id.to_s ``` I hope that helps.
Also this one should work. ``` = link_to question.user.username, "/users/#{question.user.id}" ```
192,723
I took up a somewhat interesting challenge when I answered [this question](https://softwareengineering.stackexchange.com/questions/369599/short-circuiting-an-infinite-java-8-stream/369749#369749). The task is to collect the first occurrences of different types of animals from an infinite stream until you've caught them all. The requirements given: 1. POJO `Animal` 2. enum `AnimalType` 3. method to get `AnimalType` from `Animal` 4. infinite stream of animals: `Stream<Animal>` 5. collect first of each occurrence of each animal type 6. solve this without using state outside of the stream Every requirement has been satisfied except the "outside stream state" one which I believe to be impossible. Despite that, I've shown how you can still solve the problem using a purely functional method (`firstFrom()`) that is both deterministic and referentially transparent. The requested `getAnimalType()` method exists but is completely unnecessary. Normally wouldn't put a `type` field in an object at all. This is what happens when implementation details bleed into requirements. I'm looking for a thorough review of the code. How well it communicates the point, technical soundness, readability, cleanliness, and style. The following code works as one file (for convenience of pasting). ``` package infinitestream; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; public class InfiniteStreamTest { @Test public void testFirstFrom() { // .-== Use method being tested ==-. // Set<Animal> setOfAnimals = InfiniteStream .firstFrom( infiniteStreamOfAnimals(), predictedSize() ) ; // '-== Use method being tested ==-' // // .-== Test results ==-. // Assert.assertTrue( setOfAnimals.size() == predictedSize() ); System.out.println( setOfAnimals ); String actual = setOfAnimals.toString(); String expected = "[first HUMAN animal, first DOG animal, first CAT animal]"; String message = System.lineSeparator() + expected + " <- expected" + System.lineSeparator() + actual + " <- actual" + System.lineSeparator() ; Assert.assertEquals(message, expected, actual); // '-== Test results ==-' // } // Displays // [first HUMAN animal, first DOG animal, first CAT animal] // .-== Construct dependencies ==-. // private int predictedSize() { return AnimalType.values().length; } private Stream<Animal> infiniteStreamOfAnimals() { List<Animal> animals = Arrays .asList( new Animal( "first", AnimalType.HUMAN ), new Animal( "first", AnimalType.DOG ), new Animal( "second", AnimalType.HUMAN ), new Animal( "first", AnimalType.CAT ) ) ; Stream<Integer> infiniteStreamOfInts = Stream.iterate( 0, i -> i+1 ); Stream<Animal> infiniteStreamOfAnimals = infiniteStreamOfInts .map( i->animals.get( i % animals.size() ) ) ; return infiniteStreamOfAnimals; } // '-== Construct dependencies ==-' // } // .-== System being tested ==-. // class InfiniteStream { public static <T> Set<T> firstFrom( Stream<T> infiniteStream, int size ) { Set<T> set = new LinkedHashSet<>(); infiniteStream .takeWhile( x->set.size() < size ) .collect( Collectors.toCollection( ()->set ) ) ; return set; } } // '-== System being tested ==-' // // .-== Required constructs ==-. // enum AnimalType{ HUMAN, DOG, CAT } class Animal { public Animal( String tag, AnimalType type ) { this.tag = tag; this.type = type; } public AnimalType getAnimalType() { return type; } //TODO: remove unused method public String toString() { return tag + " " + type + " animal"; } @Override public int hashCode() { return Objects.hashCode( type ); } @Override public boolean equals( Object that ) { return that != null && that.getClass() == this.getClass() && ( (Animal) that ).type == this.type ; } private String tag; private AnimalType type; } // '-== Required constructs ==-' // ```
2018/04/23
[ "https://codereview.stackexchange.com/questions/192723", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/40367/" ]
Unit tests ---------- Let's talk about your test assertions first. Your test claims: > > > ``` > String actual = setOfAnimals.toString(); > String expected = "[first HUMAN animal, first DOG animal, first CAT animal]"; > > ``` > > This is broken... ;-) **EDIT:** I encountered this problem *after* I changed the code to return a `Collectors.toSet()` - your code has a LinkedHashSet so it **is** deterministic *Still, in general, the issue is that Sets are unordered, and there's no expectation that `setOfAnimals` will return a `toString()` in a deterministic order. Depending on the Set implementation, or even some other random factor, the order of the toString may be different. You need to have a deterministic test. Perhaps returning a List instead of a Set? I actually prefer that option as the List can be in stream order. Note that when I ran your tests in Eclipse with the regular run mechanism, it worked, but when I did code-coverage, the order was different, and the tests failed. This is not just an idle suggestion!* hashCode and equals hacks. -------------------------- Your code requires that the `equals`, and `hashCode` implementation of the stream object conforms to the required contract. I see this as being a "hack". You should have a better mechanism, a more functional mechanism to accomplish this task. More generic and functional --------------------------- I recommend an extractor function that identifies a key value from the stream members, and then a Set of possible key values as inputs. This should be turned in to a generic method. For example, your `firstFrom` method should take three parameters, the stream, a function that extracts the "key", and the possible keys to expect: ``` public static <S, T> Set<S> firstFrom( final Stream<S> stream, final Function<S, T> keyExtractor, final Set<T> keys) { ..... } ``` Note that I have renamed the first parameter to be `stream` instead of `infiniteStream` ... the code works for either, so why imply it does not? Also, I have taken in a set of keys, this parameter contains the "universe" of keys to expect/extract from the stream. In order for the generics to be improved, they should also take in to account the super and sub types that are possible to support. I settled on the generic signatures: ``` public static <S, T> List<S> firstFrom( final Stream<? extends S> stream, final Function<? super S, T> keyExtractor, final Set<? extends T> keys) { ``` Note that the stream can now consist of any Animal or sub-type of animal, and the extractor function can extract from any super-type of Animal too. Further, the keys can be specific subtypes of the extracted keys as well. The full method I propose is: ``` public static <S, T> List<S> firstFrom( final Stream<? extends S> stream, final Function<? super S, T> keyExtractor, final Set<? extends T> keys) { // take a copy to avoid mutating the input parameter final Set<T> remaining = new HashSet<>(keys); return stream.takeWhile(s -> !remaining.isEmpty()) .filter(s -> remaining.remove(keyExtractor.apply(s))) .collect(Collectors.toList()); } ``` There are a few tricks in here. Firstly, the `isEmpty()` is generally a much better test than `size()`. By removing values from the `remaining` keys set we can stop the stream with `isEmpty()`. Secondly, we filter the stream to get rid of any subsequent encounters of the key. This is a nice way to prepare the data for the collector in the List. Finally, I use a trick of the `Set.remove()` function. It returns `true` if the set is mutated. So, only the first time the key is encountered will it return true. Thus, only the first stream instance is collected. Use Case -------- The use-case for the `firstFrom()` function now looks like: ``` Set<AnimalType> possibles = new HashSet<>(); possibles.addAll(Arrays.asList(AnimalType.values())); // .-== Use method being tested ==-. // List<Animal> setOfAnimals = InfiniteStream.firstFrom( infiniteStreamOfAnimals(), Animal::getAnimalType, possibles); ``` See how the `Animal::getAnimalType` is used to extract the type for the stream members? This beats overriding the `hashCode` and `equals`! Also, the `possibles` contains the different values in the `AnimalType` enumeration. Full code. ---------- I moved the instances of the animals to the top in to static final values (this was because I messed around with how to get the test assertions right before I settled on the deterministic List output....). I think it is neater now too. There are other formatting issues, but I've neatened the code with Eclipse's Ctrl-A and Ctrl-F, and then pasted the code here: ``` import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Assert; import org.junit.Test; public class InfiniteStreamTest { private static final Animal fHuman = new Animal("first", AnimalType.HUMAN); private static final Animal fDog = new Animal("first", AnimalType.DOG); private static final Animal sHuman = new Animal("second", AnimalType.HUMAN); private static final Animal fCat = new Animal("first", AnimalType.CAT); private static final List<Animal> animals = Arrays.asList( fHuman, fDog, sHuman, fCat); @Test public void testFirstFrom() { Set<AnimalType> possibles = new HashSet<>(); possibles.addAll(Arrays.asList(AnimalType.values())); // .-== Use method being tested ==-. // List<Animal> setOfAnimals = InfiniteStream.firstFrom( infiniteStreamOfAnimals(), Animal::getAnimalType, possibles); // '-== Use method being tested ==-' // // .-== Test results ==-. // Assert.assertTrue(setOfAnimals.size() == predictedSize()); System.out.println(setOfAnimals); String actual = setOfAnimals.toString(); String expected = "[first HUMAN animal, first DOG animal, first CAT animal]"; String message = System.lineSeparator() + expected + " <- expected" + System.lineSeparator() + actual + " <- actual" + System.lineSeparator() ; Assert.assertEquals(message, expected, actual); // '-== Test results ==-' // } // Displays // [first HUMAN animal, first DOG animal, first CAT animal] // .-== Construct dependencies ==-. // private int predictedSize() { return AnimalType.values().length; } private Stream<Animal> infiniteStreamOfAnimals() { Stream<Integer> infiniteStreamOfInts = Stream.iterate(0, i -> i + 1); Stream<Animal> infiniteStreamOfAnimals = infiniteStreamOfInts.map( i -> animals.get(i % animals.size())); return infiniteStreamOfAnimals; } // '-== Construct dependencies ==-' // } // .-== System being tested ==-. // class InfiniteStream { public static <S, T> List<S> firstFrom( final Stream<? extends S> stream, final Function<? super S, T> keyExtractor, final Set<? extends T> keys) { // take a copy to avoid mutating the input parameter final Set<T> remaining = new HashSet<>(keys); return stream.takeWhile(s -> !remaining.isEmpty()) .filter(s -> remaining.remove(keyExtractor.apply(s))) .collect(Collectors.toList()); } } // '-== System being tested ==-' // // .-== Required constructs ==-. // enum AnimalType { HUMAN, DOG, CAT } class Animal { public Animal(String tag, AnimalType type) { this.tag = tag; this.type = type; } public AnimalType getAnimalType() { return type; } public String toString() { return tag + " " + type + " animal"; } private String tag; private AnimalType type; } // '-== Required constructs ==-' // ```
I find your solution a bit convoluted and rather confusing, for several reasons: * You are relying on the collector returned by `Collectors.toSet()` to have the characteristic [`IDENTITY_FINISH`](https://docs.oracle.com/javase/10/docs/api/java/util/stream/Collector.Characteristics.html#IDENTITY_FINISH), which, while likely, is only an implementation detail and not guaranteed by the specification of the method. To explain: The interface `Collector` defines three type parameters, `T`, `A` and `R`. `T` is the type of the elements that are collected – in your case, this would be `Animal`. `R` is the result type of the collection – a `Set<Animal>` in your case. `A` is the accumulation type, i.e. the type of the container that accumulates the elements while they are collected. However, the accumulation type of the collector returned by `Collectors.toCollection(Supplier<C>)` is `?`, meaning that it could be anything. For example, the collector could first collect the animals into a `List`, and only when all the animals from the stream have been collected into the `List`, it will create a `Set` from this `List` and return the `Set`. Even if the accumulation type is `Set<Integer>`, the accumulation container does not necessarily have to be the `Set` that will be returned. Now, if a collector has the characteristic `IDENTITY_FINISH`, then it means that the accumulation container is identical to the result container. Your code only works if the accumulation container is also the result container, because it depends on the size of the result container to grow as the elements from the stream are collected. * The operation you perform on the stream depends on state that might change during the execution of the operation, which can be [dangerous](https://docs.oracle.com/javase/10/docs/api/java/util/stream/package-summary.html#Statelessness) and produces headaches. For all your method `firstFrom(Stream<T>, int)` knows, the `Stream<Animal>` might be parallel (even if it is ordered), so the collection operation might be executed in several threads. If this is the case, then every thread will first collect the elements it operates on to its own `Set`, and only when the threads are done will the results of the parallel collections be merged into the final result container. Oops, the threads will never be done collecting elements, because the size of the final result container never changes. Interestingly, when I tried a similar approach for collecting the first \$n\$ integers (distinct or not) from an infinite integer stream to a `List`, the program did terminate, but the list was much larger than the specified maximum when the stream was parallel. Of course, it is possible to check whether the collector has the characteristic `IDENTITY_FINISH` and to manually ascertain that the stream is sequential, but then I would ask the question: Why bother with such a complicated design, when you can just call `iterator()` on the stream and iterate over the elements in an old-fashioned, but simple and straightforward way? This would be much more to the point, and the risk of headaches would be minimal.
2,148,997
I would like to create a Javascript class that I can use like so: ``` var f = new myFunction(arg1, arg2); f.arg1; // -> whatever was passed as arg1 in the constructor f(); f instanceof myFunction // -> true typeof f // -> function ``` I can treat it like a normal object, even adding the native `Function` object to the prototype chain, but I can't call it like a function: ``` function myFunction(arg1, arg2) { this.arg1 = arg1; this.arg2 = arg2; } myFunction.prototype = Function var f = new myFunction(arg1, arg2); // ok f.arg1; // ok f(); // TypeError: f is not a function, it is object. f instanceof myFunction // -> true typeof f // -> object ``` I can have the constructor return a function, but then it's not an instance of `myFunction`: ``` function myFunction(arg1, arg2) { var anonFunction = function() { }; anonFunction.arg1 = arg1; anonFunction.arg2 = arg2; return anonFunction; } var f = new myFunction(arg1, arg2); // ok f.arg1; // ok f(); // ok f instanceof myFunction // -> false typeof f // -> function ``` Any suggestions? I should add that I *really* want to avoid using `new Function()` since I hate string code blocks.
2010/01/27
[ "https://Stackoverflow.com/questions/2148997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46768/" ]
First and foremost, you should probably be considering some other way of doing this, because it is unlikely to be portable. I'm just going to assume Rhino for my answer. Second, I'm not aware of any way in Javascript of assigning a function's body after construction. The body is always specified as the object is constructed: ``` // Normal function definitions function doSomething() { return 3 }; var doSomethingElse = function() { return 6; }; // Creates an anonymous function with an empty body var doSomethingWeird = new Function; ``` Now, there's a non-standard Mozilla extension in the form of a `__proto__` property on every object. This allows you the change the inheritance chain of any object. You can apply this to your function object to give it a different prototype after construction: ``` // Let's define a simple prototype for our special set of functions: var OddFunction = { foobar: 3 }; // Now we want a real function with this prototype as it's parent. // Create a regular function first: var doSomething = function() { return: 9; }; // And then, change it's prototype doSomething.__proto__ = OddFunction; // It now has the 'foobar' attribute! doSomething.foobar; // => 3 // And is still callable too! doSomething(); // => 9 // And some of the output from your example: doSomething instanceof OddFunction; // => true typeof doSomething; // => function ```
`function Foo() { var o = function() {return "FOO"}; o.__proto__ = Foo.prototype; return o; }` `(new Foo()) instanceof Foo`: true `(new Foo())()`: FOO
41,319,720
Im using google charts in a project but im having a hard time to make them responsive. Iǘe seen other examples on responsive charts but I cant seem to get it to work in my case. All my charts gets rendered and after that their sizes do not change. If someone can make this chart responsive id appreciate it. Thank you: ``` function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('string', 'Year'); data.addColumn('number', 'Revenue'); data.addColumn('number', 'Average Revenue'); data.addRows([ ['2004', 1000, 630], ['2005', 1170, 630], ['2006', 660, 630], ['2007', 1030, 630] ]); var options = { title: 'Revenue by Year', seriesType: "bars", series: {1: {type: "line"}}, vAxis: {title: 'Year', titleTextStyle:{color: 'red'}}, colors:['red','black'] }; var chart = new google.visualization.ComboChart(document.getElementById('chart')); chart.draw(data, options); } google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(drawChart); ``` Fiddle for the chart: [Fiddle](http://jsfiddle.net/wtwy0cfv/) If it could take up a percentage width of a parent it would be great
2016/12/25
[ "https://Stackoverflow.com/questions/41319720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7339280/" ]
The solution was already given online elsewhere. You need to call your drawChart() function whenever the window is resized to get the desired behaviour. The website [flopreynat.com](https://flopreynat.com/blog/2015-09-08-make-google-charts-responsive) exactly describes this problem and solution ([codepen](https://codepen.io/flopreynat/pen/BfLkA)). It describes how this can be done using JQuery: ``` $(window).resize(function(){ drawChart(); }); ``` Using just Javascript, [this answer on Stack Exchange by Sohnee](https://stackoverflow.com/questions/1818474/how-to-trigger-the-window-resize-event-in-javascript) describes how to trigger functions upon a resize event: ``` window.onresize = doALoadOfStuff; function doALoadOfStuff() { //do a load of stuff } ``` All credit to both authors of the links above.
I created a class chart, and used the window resize event like the accepted answer. css: ``` .chart { width: 100%; min-height: 500px; } ``` js: ``` $(window).resize(function(){ drawChart(); }); ``` html: ``` <div id="barchart" class="chart"></div> ```
18,384,609
My problem is likely all about date formatting in a `SELECT`. In an asp file I open an ADO Recordset wanting to retrieve rows of a MS SQL table that fall between `date1 (08/15/2013)` and `date2 (08/22/2013)` (i.e., the previous 7 days from today's date.) The `SELECT` does retrieve the appropriate 2013 rows but also retrieves rows going back to 08/15/2012. Here is the SELECT: ``` oRS.Source = "SELECT * FROM aTable WHERE entry_Date BETWEEN '" & resultLowerDate & "' AND '" & resultCurrentDate & "' AND entry_Status <> 'INACTIVE'" ``` resultLowerDate = 08/15/2013 and resultCurrentDate = 08/22/2013. The table is set up as follows with resultCurrentDate = "08/22/2013": ``` entry_Status entry_Date (varchar) LastName FirstName SELECT Result INITIAL 08/15/2012 Smith Jim YES INACTIVE 08/21/2012 Green Tom no INITIAL 08/22/2013 Jones Mary yes FOLLOWUP 08/22/2013 Jones Mary yes FOLLOWUP 08/22/2013 Brown Sally yes FOLLOWUP 08/22/2013 Smith Jim yes ``` Any thoughts as to why the `INITIAL 08/15/2012` row gets selected along with the other rows that meet the `SELECT` query?
2013/08/22
[ "https://Stackoverflow.com/questions/18384609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2033850/" ]
STOP STORING DATES IN VARCHAR COLUMNS! And STOP CONCATENATING STRINGS, USE PROPER PARAMETERS. Sorry to yell, but we are getting multiple questions a day where people use the wrong data type for some unknown and probably silly reason, and these are the problems it leads to. The problem here is that you are comparing ***strings***. Try: ``` "... WHERE CONVERT(DATETIME, entry_date, 101)" & _ " >= CONVERT(DATETIME, '" & resultLowerDate & "', 101)" & _ " AND CONVERT(DATETIME, entry_date, 101)" & _ " < DATEADD(DAY, 1, CONVERT(DATETIME, '" & resultCurrentDate & "', 101))" ``` Or better yet, set resultLowerDate and resultUpperDate to YYYYMMDD format, then you can say: ``` "... WHERE CONVERT(DATETIME, entry_date, 101) >= '" & resultLowerDate & "'" & _ " AND CONVERT(DATETIME, entry_date, 101) < DATEADD(DAY, 1, '" & resultCurrentDate & "'" ``` Note that I use an open-ended range (>= and <) instead of BETWEEN, just in case some time slips into your VARCHAR column. Also note that this query could fail because garbage got into your column. Which it can, because you chose the wrong data type. My real suggestion is to fix the table and use a `DATE` or `DATETIME` column.
The fact that your entry\_Date column is a varchar field and not an actual date is the problem. If you cast it to a datetime during the select, you'll get the results you expect. ``` select * from aTable where cast(entry_Date as datetime) between '08/15/2013' and '08/22/2013' ``` [Sql Fiddle link](http://sqlfiddle.com/#!3/4d36c/3)
12,507
My invention is a better solution to existing problem. There are a few other patents and publication that tried to solve the same problem, but as far as I know none was implemented. Only known to me documentation describing the solution actually used by the industry is available online in the form of web pages. Can I use the url when referring to the prior art in my application?
2015/03/24
[ "https://patents.stackexchange.com/questions/12507", "https://patents.stackexchange.com", "https://patents.stackexchange.com/users/11947/" ]
You can cite a URL that refers to prior art on an information disclosure statement [IDS] using form PTO-892. URLs in the specification are 'impermissible.' You should not put a URL in your specification. MPEP 608.01(VII) states: > > If hyperlinks and/or other forms of browser-executable code are embedded in the text of the patent application, examiners should object to the specification and indicate to applicants that the embedded hyperlinks and/or other forms of browser-executable code are impermissible and that references to web sites should be limited to the top-level domain name without any prefix such as http:// or other browser-executable code. This requirement does not apply to electronic documents listed on forms PTO-892 and PTO/SB/08 where the electronic document is identified by reference to a URL. > > > The attempt to incorporate subject matter into the patent application > by reference to a hyperlink and/or other forms of browser-executable > code is considered to be an improper incorporation by reference. See > 37 CFR 1.57(d) and MPEP § 608.01(p), paragraph I regarding > incorporation by reference. Where the hyperlinks and/or other forms of > browser-executable codes themselves rather than the contents of the > site to which the hyperlinks are directed are part of applicant’s > invention and it is necessary to have them included in the patent > application in order to comply with the requirements of 35 U.S.C. > 112(a) or pre-AIA 35 U.S.C. 112, first paragraph, *and applicant does > not intend to have these hyperlinks be active links, examiners should > not object to these hyperlinks. The Office will disable these > hyperlinks when preparing the text to be loaded onto the USPTO Web > database.* > > > <http://www.bitlaw.com/source/mpep/608_01.html>
I have used a reference to a website (also as prior art) in my 1st patent application and the patent was issued without any changes. I also have read mpep 608.01(p) and my understanding is that active hyperlinks are not allowed. Apparently my text reference to a hyperlink and not an embedded hyperlink itself wasn't triggering any alarms with the patent examiner.
26,498,644
I found this example at `wiki.bash-hackers.org`, however it is not explained in detail, so I was hoping maybe someone here, could put some light on this, and explain what is happening. I understand the first line of `isSubset` function, as it is taking passed args, and using indirect referencing, stores keys into internal arrays `xkeys` and `ykeys`. 2nd line is setting parameters, but I don't understand what `${@/%/[key]}` is doing? Looks like substitution, changing `%` to `[key]`, I have no clue what happens here. Then in next line it compares arrays on number of elements, but shouldn't it be reverse, returning 1 if first array has more elements, because then it can't be subset of the second one? Finally `[[ ${!2+_} && ${!1} == ${!2} ]] || return 1`, is pretty confusing. ``` isSubset() { local -a 'xkeys=("${!'"$1"'[@]}")' 'ykeys=("${!'"$2"'[@]}")' set -- "${@/%/[key]}" (( ${#xkeys[@]} <= ${#ykeys[@]} )) || return 1 local key for key in "${xkeys[@]}"; do [[ ${!2+_} && ${!1} == ${!2} ]] || return 1 done } main() { # "a" is a subset of "b" local -a 'a=({0..5})' 'b=({0..10})' isSubset a b echo $? # true # "a" contains a key not in "b" local -a 'a=([5]=5 {6..11})' 'b=({0..10})' isSubset a b echo $? # false # "a" contains an element whose value != the corresponding member of "b" local -a 'a=([5]=5 6 8 9 10)' 'b=({0..10})' isSubset a b echo $? # false } main ```
2014/10/22
[ "https://Stackoverflow.com/questions/26498644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2434479/" ]
2nd line: ``` ${@/%/[key]} ``` `%` as first character of the pattern indicates that pattern has to match at the end. There is nothing else in the pattern so the meaning is "replace empty string at the end, with '[key]'". After that positional parameters look like this: ``` 1 = a[key] 2 = b[key] ``` Next line: > > but shouldn't it be reverse, returning 1 if first array has more elements, > > > But it does that. Notice that `||` operator is used, so it will return `1` if the condition is *not* met. The condition is: "x.size <= y.size", so it will return `1` if "x.size > y.size". Finally: ``` [[ ${!2+_} && ${!1} == ${!2} ]] || return 1 ``` To be honest, I don't know what `+_` is for. As for the rest, notice that we are in a loop with a `key` variable. We also have `key` in our positional variables, so: ``` ${!1} ``` becomes ``` ${a[key]) ``` and `key` variable takes values of keys from array `a`. So the whole test verifies that value with given key exists in the second array: ``` [[ ${!2+_} && ... ``` and that value with that key in the first array is the same as the value with that key in the second array: ``` ... && ${!1} == ${!2} ]] ``` The first condition is necessary to detect the case when you pass array `a` which at index `i` has empty string and array `b` which doesn't have index `i`: ``` local -a 'a=([1]="" 2 3)' 'b=([2]=2 {3..10})' isSubset a b echo $? # false ```
The explanation for `${@/%/[key]}` is this section of the bash man page: > > ${parameter/pattern/string} > > > The pattern is expanded to produce a pattern just as in pathname > expansion. Parameter is expanded and the longest match of pat- > tern against its value is replaced with string. If Ipattern > begins with /, all matches of pattern are replaced with string. > Normally only the first match is replaced. If pattern begins > with #, it must match at the beginning of the expanded value of > parameter. If pattern begins with %, it must match at the end > of the expanded value of parameter. If string is null, matches > of pattern are deleted and the / following pattern may be omit- > ted. If parameter is @ or \*, the substitution operation is > applied to each positional parameter in turn, and the expansion > is the resultant list. If parameter is an array variable sub- > scripted with @ or \*, the substitution operation is applied to > each member of the array in turn, and the expansion is the > resultant list. > > > Specifically the bit about `%` there in the middle. So `${@/%/[key]}` is matching the end of the string for each value in the array and appending `[key]` to it. Assuming a call to `isSubset` of `isSubset a b` where `a='([0]="0" [1]="1" [2]="2" [3]="3" [4]="4" [5]="5")'` and `b='([0]="0" [1]="1" [2]="2" [3]="3" [4]="4" [5]="5" [6]="6" [7]="7" [8]="8" [9]="9" [10]="10")'`. What happens in `isSubset` goes like this: ``` isSubset() { local -a 'xkeys=("${!'"$1"'[@]}")' 'ykeys=("${!'"$2"'[@]}")' ``` Interpolate `$1` and `$2` into the above line and we get ``` local -a 'xkeys=("${!a[@]}")' 'ykeys=("${!b[@]}")' ``` Which expands to (via `${!arr[@]}` array index expansion) ``` local -a 'xkeys=(0 1 2 3 4 5)' 'ykeys=(0 1 2 3 4 5 6 7 8 9 10)' ``` At this point we now have `xkeys` and `ykeys` arrays of the keys of the arrays passed in. ``` set -- "${@/%/[key]}" ``` Recall that `$@` is `@=(a b)` and from the man page snippet above we know that this becomes ``` set -- 'a[key]' 'b[key]' ``` `set --` then sets the functions positional parameters for us so we have `@=('a[key]' 'b[key]')` ``` (( ${#xkeys[@]} <= ${#ykeys[@]} )) || return 1 ``` If `xkeys` is larger than `ykeys` then it can't be a subset so bail out. (This could be done before the `set --` line and that would be slightly more efficient I imagine, though unlikely to matter in any but the hottest of loops.) ``` local key for key in "${xkeys[@]}"; do ``` Loop over every key in `xkeys` (with the value assigned to `key`). (Note the variable name here, it is crucial.)[1] ``` [[ ${!2+_} && ${!1} == ${!2} ]] || return 1 ``` More indirection, this time on the positional parameters. The above expands to ``` [[ ${b[key]+_} && ${a[key]} == ${b[key]} ]] || return 1 ``` `${b[key]+_}` expands to \_ if `b[key]` has a value and an empty string if it does not. (I'm not sure why this bothers with the alternate value expansion instead of just using `${!2}` but there is probably a reason. It could be safety in the face of `set -u` or it could be safety against `[[` interpreting the resulting string, though I don't think it does that but `[` would have.) This test therefore passes when `b[key]` has a value and fails when it does not. `${a[key]} == ${b[key]}` tests that the value in that index is the same in both arrays and the whole expression returns failure from the function when either part fails. @danadam correctly explains, and it makes sense to include here as well, that the key detail here is that the `[]` indexing in array lookups does variable expansion so `a[key]` in positional parameter one is not looking for the "key" index in array `a` but is rather `a[$key]`. ``` done } ``` I hope that all made sense. (And I hope I got it all right. =) 1. I *really* wanted to write "Note the variable name here, it is ... key." but the ensuing confusion wasn't worth the joke.
121,659
First of all I'm using `Centos 6` server, putty and wordpress.org I followed the instructions from [this link](http://www.servermom.org/how-to-install-and-setting-up-vsftpd-on-centos-server/535/#comment-1343) to set up `vsftpd` and ftp in `centos` server. For the `vsftpd.conf` file, these were the changes I made: ``` anonymous_enable=NO local_enable=YES chroot_local_user=YES ``` All of them are uncommented. I then restarted the `vsftpd` service. For `iptables` I enabled input and output for port 21. After entering the user account name and password for <ftp://domain.com>, it seems like the server is not recognizing my username and password. They are the same credentials I have been using to log in to `CentOS` server. Then I found something on Google about `getsebool`. It mentioned that ftp\_home\_directory is turned off and I needed to turn it on with `setsebool -P` OK, now I am able to connect using ftp in putty, but not in the web browser or `filezilla`.
2014/03/26
[ "https://unix.stackexchange.com/questions/121659", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/62691/" ]
I am sure there are many ways to accomplish this. Here is one method: ``` echo a{b,c,d} | sed 's/ /,/g' ```
Here's a bash-only solution. ``` (IN=$(echo a{b,c,d}); echo ${IN// /,}) # ab,ac,ad ``` The part before the semicolon assigns `ab ac ad` to the variable `IN` and the second part uses search and replace to change all spaces to commas. The `//` means all matches, not just the first. Do it all in a subshell (the enclosing parentheses) to not pollute your namespace.
20,996,796
I wrote a simple OpenCV program that recovers my webcam video stream and display it on a simple window. I wante to resize this window to the resolution 256x256 but it changed it to 320x240. Here's my source code : ``` #include <iostream> #include <opencv/cv.h> #include <opencv/highgui.h> using namespace std; int main(int argc, char** argv) { char key; cvNamedWindow("Camera_Output", cv::WINDOW_NORMAL); CvCapture *capture = cvCaptureFromCAM(CV_CAP_ANY); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 256); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 256); while(1){ IplImage *frame = cvQueryFrame(capture); cvShowImage("Camera_Output", frame); key = cvWaitKey(10); if (key == 27){ break; } } cvReleaseCapture(&capture); cvDestroyWindow("Camera_Output"); return 0; } ``` The output resolution is 320x240 and I want a 256x256 resolution. I think it's not possible because the camera manages its output video stream buffer and it has to keep the same ratio (width/height). What do you think about this idea ? Is there a function which can force the resolution as a square resolution using OpenCV ? Thanks a lot in advance for your help.
2014/01/08
[ "https://Stackoverflow.com/questions/20996796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1364743/" ]
The answers before explained why you are getting a "**weird toast**" so to fix that, in your `tweetAdapter` class you are using `tweet.title` as a `string`. So try this: ``` adapter.getItem(position).title; ``` Because the `adapter` will get the item that is sent through your `TweetAdapter`, using the `tweet.title` here will work too.
Try this ``` String itemValue = ((TextView)view).getText().toString(); ``` Hope this helps.
32,121,686
This may seem like an odd question, but I'm trying to practice writing reusable code, or least trying to practice thinking about it in the right way, if you know what I mean? I have an assignment that involves writing a text interface with a couple of different menus. So there are two approaches to this: (1) a class for each menu (sloppy) or (2) a class which contains the information for all the menus (not as sloppy). Now that I am writing this, it feels like it might be bad practice, BUT is it possible to have one class which contains the basic components of a menu (a title, a list of MenuOptions etc), but the methods can be added at another time? Alternatively, if this is not possible/advisable, which would be the generally preferred way of doing something like this, (a) separate classes for separate menus, or (b) one big class which contains all the code for the different menus?
2015/08/20
[ "https://Stackoverflow.com/questions/32121686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3593486/" ]
I think I understand what you mean, but I also think that when you say `but the methods can be added at another time?` you mean that *what the methods do is added at another time*. Menus, in your case, usually need to take care of some basic things, such as * Showing the actual menu text (let's call it title); * Showing a tool tip; * Doing something when clicked. * Child sub menu items. To achieve this, you could use either or a mix of two things: 1. The [strategy](https://sourcemaking.com/design_patterns/strategy) design pattern. 2. Abstract classes. The strategy design pattern allow you to specify a behaviour, and then pass it along to some class which knows what to do with that behaviour. In short, your behaviour could be what happens when the menu item is clicked. So basically, your menu class will *not* know what to do when it is clicked, but it *will* know to whom the call will be delegated. This approach would allow you to have one `Menu` class and several behaviours it can access. Using abstract classes is similar to using the design pattern, however, you would end up creating a new concrete class for each different menu you want to have. Thus, I think that the best result would be somewhere in between. For instance you could create your `Menu` parent class as `abstract`, with properties such as `Title`, `Tooltip`, etc. You could then add a method called `onActionPerformed` which takes in some object which handles what happens when the menu item has been clicked. Lastly, you could create abstract methods such as `onBeforeActionPerformed` and `onAfterActionPerformed`, this would essentially be interceptors which would allow you to do logic just before and after the event handling. You could then extend the `Menu` class with things such as `NonInterceptibleMenu` and the likes to handle the different scenarios.
You could have a general class for a menu-item and for a menu itself (as a collection of menu-items). These classes would not contain any logic regarding on click behaviour, but they would just cover general parts, like UI, layout, title placeholder - general configurations. You can have 'methods added later'. This can be achieved either with delegates, or with lambda functions. In Java you might have met similar configuration in Swing, when you have buttons and click listeners (or even menus. You can have a look at the usage of JMenuBar, JMenu, JMenuItem classes and their interface might be interesting for you). You might come across many examples when 'methods are added' as anonymous classes, this was before lambda functions arrived in Java 8
11,183,065
I've been learning about divs over the past few months, and am now able to align divs side by side. However, today I was working on my website, and my divs suddenly stopped lining up. The divs in question are: `#dorsey_left`, `#dorsey_middle` and `#dorsey_right`. When I remove `#dorsey_left` from the `HTML` document, `#dorsey_middle` and `#dorsey_right` align properly. I'm guessing that the problem is related to `#dorsey_left`, but I can't find anything in the code. This is the [JsFiddle](http://jsfiddle.net/juaZg/).
2012/06/25
[ "https://Stackoverflow.com/questions/11183065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1377319/" ]
I think you'll find the solution by cleaning up your code. There are numerous syntax errors (unclosed quotes, children of `<ul>` that aren't `<li>`, etc). If your code passes [validation](http://validator.w3.org/) and the problem still exists try to simplify it so you get to the root of the problem by removing things that clearly aren't the problem.
This tutorial will solve your problem which also has code in it for aligning 3 divs horizontally <http://codejigz.com/forget-tables-use-divscss-for-page-layouts/>
38,928,764
This is my first attempt on using ionic 2. But already I'm having difficulties. But I'm trying. So after i start a new project, I went on to see how click event is used. I search and read throught the net. But still got no proper answer. So I used this code on button click event. ``` <button myitem (click)='openFilters()'>CLICK</button> ``` And my .ts file look like as below. ``` import {Component} from '@angular/core'; import {NavController} from 'ionic-angular'; @Component({ templateUrl: 'build/pages/home/home.html' }) export class HomePage { constructor(private navCtrl: NavController) { openFilters() { console.log('crap'); } } } ``` I event tried adding `selector: 'myitem',` to the @component part.
2016/08/13
[ "https://Stackoverflow.com/questions/38928764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6711310/" ]
To work with click function your code should look like this **.html** ``` <button myitem (click)='openFilters();'>CLICK</button> ``` **.ts** ``` import {Component} from '@angular/core'; import {NavController} from 'ionic-angular'; @Component({ templateUrl: 'build/pages/home/home.html' }) export class HomePage { constructor(private navCtrl: NavController) { } openFilters() { console.log('crap'); } } ```
The code in the `button` element is perfect. The issue is that you have declared the `openfilters()` method *inside the constructor of the class*, so the click event handler could not find it. Put it outside the constructor, as another method of the class, and it will work as expected. ``` export class HomePage { constructor(private navCtrl: NavController) { // ... } openFilters() { console.log('crap'); } } ```
7,094
I have this snippet of code that gets the most recently added products: ``` $_productCollection = Mage::getResourceModel('catalog/product_collection') ->addAttributeToSelect('*') ->addAttributeToFilter($preorderAttribute, array( 'eq' => Mage::getResourceModel('catalog/product') ->getAttribute($preorderAttribute) ->getSource() ->getOptionId($preorderValue) )) ->setVisibility(array(2,3,4)) ->setOrder('created_at', 'desc') ->setPage(1, 12); ``` I want to further filter this by category, for example, categories with id 3 and 4. Only products from 3 and 4 categories are selected in the collection. How can I achieve this? I tried to use `addAttributeToFilter` to filter by category IDs but there seems to be a variety of different ways to do it, and it's neither not working or simply gives a Fatal error: > > Call to a non-member function getBackend() > > > ....now I'm at a loss. Any help would be appreciated.
2013/08/24
[ "https://magento.stackexchange.com/questions/7094", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/3029/" ]
I managed to resolve this (after much trial and error) with the following code: ``` $collection = Mage::getModel('catalog/product')->getCollection(); $collection->addAttributeToFilter('status', 1); $collection->addAttributeToSelect(array('name','sku','price','small_image')); // Filter by multiple categories $collection->joinField('category_id','catalog/category_product','category_id','product_id=entity_id',null,'left'); $data_cats = $this->getRequest()->getParam('categories'); // Or $data_cats = array(85,86,87,88); $filter_cats = array(); foreach ($data_cats as $value_cats) { $filter_cats[] = array( 'attribute' => 'category_id', 'finset' => $value_cats ); } $collection->addAttributeToFilter($filter_cats); ``` Hope this helps someone ;)
for error: 'invalid attribut entity\_id' don't make space between product\_id = entity\_id !! the good syntax is: ``` ->joinField( 'category_id', 'catalog/category_product', 'category_id', 'product_id=entity_id', null, 'left' ) ```
46,609,082
I'm currently teaching myself HTML/Javascript, with a few challenges set by a colleague. I'm trying to create loops which will display 3 random numbers between 1-99. Each displaying a random colour. Have done some searching and unable to find anything that incorporates these four aspects of my loop. Below is where I've got to so far. Any ideas how to convert this into loops? Many thanks Chris ``` <!DOCTYPE html> <html> <body> <center> <h1>Hello World!</h1> <h2>10 Random Coloured Numbers</h2> <p id="no1"></p> <p id="no2"></p> <p id="no3"></p> <script> document.getElementById("no1","no2","no3").innerHTML = Math.floor(Math.random() * 101) document.getElementById("no1","no2","no3").style.color = '#' + (Math.random() * 0xFFFFFF << 0).toString(16); </script> ```
2017/10/06
[ "https://Stackoverflow.com/questions/46609082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8665947/" ]
As @Lamak mentioned in a comment, you cannot avoid sorting all rows in the table, but not for the reason stated. A sort is required to determine distinct categories by which the result set should be partitioned, and, in the absence of explicit ordering within each partition, row numbers are easily determined as a side effect of the category sort. How the query runs "behind the scenes", or, if using the correct term, its execution plan is determined by the presence (or absence) of an index that might help avoid that category sort. If you had a covering index on `(category, value)`, and whatever other columns you need in the result, your query would run much more efficiently. In that latter case the simplified algorithm might look more like this: 1. Read the pre-sorted records containing all necessary columns, including row numbers, from the index. 2. Discard records with row number greater than `n`. Your "ideal" query > > > ``` > SELECT category, value, row_number() OVER (PARTITION by category) as > category_id FROM myTable WHERE category_id < N > > ``` > > probably wouldn't run in any SQL database, because the `SELECT` list is processed *after* the `WHERE` clause predicates, so `category_id` is unknown when the predicates are evaluated.
Other method of rownumber, but i have doubts of performance too. I agree @mustaccio. My example take 5 rows... ``` select distinct f1.category, f3.* from yourtable f1 inner join lateral ( select f2.value from yourtable f2 where f2.category=f1.category fetch first 5 rows only ) f3 on 1=1 ```
5,990,020
I want to remove the message Nothing Found to Display in Struts 1.3 Display Tag , When no record fetch from database. Its possible to do this...?
2011/05/13
[ "https://Stackoverflow.com/questions/5990020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/627789/" ]
From my point of view the default behavior should be that no message must be displayed in case of empty data source. The **empty\_list** didn't work in my case. I tried this and it works: ``` <display:table ... <display:setProperty name="basic.msg.empty_list" value="" /> <display:column ... ... </display:table> ``` You can also customize you message in html format: ``` <display:setProperty name="basic.msg.empty_list" value="<span style=\"font-size:12px\">No data</span>" /> ``` I hope it will help...
remove "pagesize" attribute, it fixes the issue for struts2 & Displaytag 1.2 (that annoying message is called PageBanner"
15,289,627
I want to create two arrays b and c at the same time. I know two methods which can be able to achieve it. The first method is ``` b = ([i, i * 2] for i in [0..10]) c = ([i, i * 3] for i in [0..10]) alert "b=#{b}" alert "c=#{c}" ``` This method is very handy for creating only one array. I can not be the better way to get the better performance for computation. The second method is ``` b = [] c = [] for i in [0..10] b.push [i, i*2] c.push [i, i*3] alert "b=#{b}" alert "c=#{c}" ``` This method seems good for computation efficiency but two lines b = [] c = [] have to be written first. I don't want to write this 2 lines but I have not find a good idea to have the answer. Without the initialization for the arrays of b and c, we can not use push method. There exists the existential operator ? in Coffeescript but I don't know hot to use it in this problem. Do you have a better method for creating the arrays of b and c without the explicit initialization? Thank you!
2013/03/08
[ "https://Stackoverflow.com/questions/15289627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1494999/" ]
You can use a little help from `underscore` (or any other lib that provides `zip`-like functionality): ``` [b, c] = _.zip ([[i, i * 2], [i, i * 3]] for i in [0..10])... ``` After executing it we have: ``` coffee> b [ [ 0, 0 ], [ 1, 2 ], [ 2, 4 ], [ 3, 6 ], [ 4, 8 ], [ 5, 10 ], [ 6, 12 ], [ 7, 14 ], [ 8, 16 ], [ 9, 18 ], [ 10, 20 ] ] coffee> c [ [ 0, 0 ], [ 1, 3 ], [ 2, 6 ], [ 3, 9 ], [ 4, 12 ], [ 5, 15 ], [ 6, 18 ], [ 7, 21 ], [ 8, 24 ], [ 9, 27 ], [ 10, 30 ] ] ``` See the [section about splats](http://coffeescript.org/#splats) in CoffeeScript docs for more details and examples.
How about this using the existential operator: ``` for i in [0..10] b = [] if not b?.push [i, i*2] c = [] if not c?.push [i, i*3] console.log "b=#{b}" console.log "c=#{c}" ``` Or to be a bit more understandable: ``` for i in [0..10] (if b? then b else b = []).push [i, i*2] (if c? then c else c = []).push [i, i*3] console.log "b=#{b}" console.log "c=#{c}" ``` **EDIT: from comments:** > > OK but you you have to write so many tedious codes. The same reason is > also for ` (b = b or []).push [i, i\*2] > > > It is tedious, so we can wrap it in a function (but beware the variables will be global now): ``` # for node.js array = (name) -> global[name] = global[name] or [] # for the browser array = (name) -> window[name] = window[name] or [] for i in [0..10] array('b').push [i, i*2] array('c').push [i, i*3] console.log "b=#{b}" console.log "c=#{c}" ```
4,320,476
Consider equations in polar coordinates of the form $$r = f(\theta) = 1 - \alpha \sin{\theta}$$ When I plot a few of these polar functions, I always get a graph that is symmetric relative to the $y$ axis, indicating that $f(\theta)$ is in fact odd. Is $f(\theta)$ an odd function? $$f(-\theta)=1-\alpha\sin{(-\theta)}$$ Since $\sin{(-\theta)}=-\sin{(\theta)}$ $$f(-\theta)=1+\alpha\sin{(\theta)}$$ $$-f(-\theta)=-1-\alpha\sin{(\theta)}=-(1+\alpha\sin{(\theta)}) \neq 1-\alpha\sin{(\theta)}=f(\theta)$$ Is $f(\theta)$ odd, in which case how do I show this? Or is there some edge case where it's not odd?
2021/11/30
[ "https://math.stackexchange.com/questions/4320476", "https://math.stackexchange.com", "https://math.stackexchange.com/users/333842/" ]
Odd functions: $f(-x)=-f(x)$ Let's try this odd function statement with yours: Assuming function $f$ is odd, $$f(-x)=-f(x)\\ f(-\theta)=-[1+\alpha \sin(\theta)]\\ [1+\alpha \sin(-\theta)]=-[1+\alpha \sin(\theta)]\\ 1-\alpha \sin(\theta) =-1-\alpha \sin(\theta) $$ Adding $\alpha \sin(\theta)$ to either side, we get: $1 =-1$. Now we know that $1 \neq -1$, therefore $f(\theta)=1+\alpha \sin(\theta)$ is not an odd function.
Consider the function $f(x) = 1 - \alpha \sin{(x)}$ in Cartesian coordinates. Though $\alpha\sin{(x)}$ is an odd function, $1-\alpha\sin{(x)}$ is not, as shown by Mateus Figueiredo's answer. Note also that shifting $\alpha\sin{(x)}$ to the left by $\frac{\pi}{2}$ makes it equal to $\cos{(x)}$, which is an even function. Now let's consider the same function, but representing a polar coordinate $$r=f(\theta)=1-\alpha\sin{(\theta)}$$ In Cartesian coordinates, the condition for symmetry about the y-axis was $f(x)=-f(-x)$. In polar coordinates I am not quite sure what the general condition is, but here are two ways that a polar function $f(\theta)$ implies a graph that is symmetric relative to the y-axis: 1. $f(\frac{\pi}{2}+\theta)$ is even, as noted by Arturo Magidin. 2. $f$ is odd Note the following * Given a point in polar coordinates $(r,\theta)=(f(\theta),\theta)$ what can we say about $(-r,\theta)$? $$(-r,\theta)=(r,\theta+\pi)=(f(\theta),\theta+\pi)\tag{1}$$ **Proof of $1$** Let $\theta\_1>0$ be a constant. The lines $\theta = \frac{\pi}{2} + \theta\_1$ and $\theta=\frac{\pi}{2}-\theta\_1$ are symmetric relative to the y-axis. A given $r$ polar coordinate specifies the same $y$ coordinate on both lines. The corresponding pair of points, one on each line, with this $y$ coordinate are symmetric relative to the y axis. $$y = r \sin{\left(\frac{\pi}{2} \pm \theta\_1\right )}=r\sin{\left(\frac{\pi}{2} + \theta\_1\right )}$$ $$x=r \cos{\left(\frac{\pi}{2} \pm \theta\_1\right )}=\pm r \cos{\left(\frac{\pi}{2} + \theta\_1\right )} $$ By assumption, $f(\frac{\pi}{2}+\theta)$ is even so $$r=f(\frac{\pi}{2}+\theta)=f(\frac{\pi}{2}-\theta)$$ And the points $$(f(\frac{\pi}{2}+\theta),\frac{\pi}{2}+\theta)=(r, \frac{\pi}{2}+\theta)$$ $$(f(\frac{\pi}{2}-\theta),\frac{\pi}{2}-\theta)=(r, \frac{\pi}{2}-\theta)$$ are symmetric because they are each on one of the lines $\theta=\frac{\pi}{2}\pm \theta\_1$, and have the same $r$ (and also $y$) coordinate. **Proof of** $f$ odd $\implies$ for every polar point $\left ( f(\frac{\pi}{2}+\theta), \frac{\pi}{2} +\theta \right )$ on the graph of $f$ there is another point on the graph of $f$, $\left ( f(\frac{\pi}{2}+\theta), \frac{\pi}{2} -\theta \right )$, symmetric to the first point relative to the $y$ axis. Consider polar point $$\left (f(-\frac{\pi}{2}-\theta), -\frac{\pi}{2} -\theta \right )$$ use $f$ odd $$=\left (-f(\frac{\pi}{2}+\theta), -\frac{\pi}{2} -\theta \right )$$ use $(1)$ $$=\left (f(\frac{\pi}{2}+\theta), \frac{\pi}{2} -\theta \right )$$ $\implies$ $\left (f(\frac{\pi}{2}+\theta), \frac{\pi}{2} -\theta \right )$ is on the graph of $r=f(\theta)$. But so is $\left (f(\frac{\pi}{2}+\theta), \frac{\pi}{2} +\theta \right )$ These two points are symmetric relative to the $y$ axis. Now, considering the original question, the function $f(\theta)=1-\alpha\sin{(\theta)}$ is not odd, but condition $1$ above is satisfied: $$f(\frac{\pi}{2} + \theta)=1-\alpha\sin{(\frac{\pi}{2}+\theta)}=1-\alpha\sin{(\frac{\pi}{2}-\theta)}=f(\frac{\pi}{2} - \theta)$$ Therefore, the graphs of $f(\theta)=1-\alpha\sin{(\theta)}$ are symmetric relative to the $y$ axis.
38,893,452
i can't add Jquery library to my codes and i have to use js code can somebody help me with converting following code to js thanks .. ``` <script type="text/javascript"> $(function(){ $("#gorightslide").click(function(){ if(!$(this).is('.diactiveisbtn')){ $(this).addClass('diactiveisbtn'); $("#goleftslide").removeClass('diactiveisbtn'); $("#oneblockshowblog").css({display:'none'}); $("#twoblockshowblog").fadeIn(500); } }); $("#goleftslide").click(function(){ if(!$(this).is('.diactiveisbtn')){ $(this).addClass('diactiveisbtn'); $("#gorightslide").removeClass('diactiveisbtn'); $("#twoblockshowblog").css({display:'none'}); $("#oneblockshowblog").fadeIn(500); } }); }); </script> ```
2016/08/11
[ "https://Stackoverflow.com/questions/38893452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5869303/" ]
You can try this : ``` $(function(){ document.getElementById("gorightslide").click(function(){ if(!hasClass(this, 'diactiveisbtn')){ this.className += " diactiveisbtn"; document.getElementById("goleftslide").className = document.getElementById("goleftslide").className.replace(/\diactiveisbtn\b/,''); document.getElementById("oneblockshowblog").style.display = "none"; fadeIn(document.getElementById("twoblockshowblog")); } }); document.getElementById("goleftslide").click(function(){ if(!hasClass(this, 'diactiveisbtn')){ this.className += " diactiveisbtn"; document.getElementById("gorightslide").className = document.getElementById("gorightslide").className.replace(/\diactiveisbtn\b/,''); document.getElementById("twoblockshowblog").style.display = "none"; fadeIn(document.getElementById("oneblockshowblog")); } }); }); function hasClass(element, cls) { return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1; } function fadeIn(el) { el.style.opacity = 0; var last = +new Date(); var tick = function() { el.style.opacity = +el.style.opacity + (new Date() - last) / 400; last = +new Date(); if (+el.style.opacity < 1) { (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16); } }; tick(); } ```
Try this ``` function yourfunction() { document.getElementById("gorightslide").onclick = function(event) { if(event.target.className != "diactiveisbtn"){ event.target.classList = "diactiveisbtn"; document.getElementById("goleftslide").classList = ""; document.getElementById("oneblockshowblog").style.display = "none"; document.getElementById("twoblockshowblog").style.display = "block"; // you can add here css animation (@keyframe) } } document.getElementById("goleftslide").onclick = function(event) { if(event.target.className != "diactiveisbtn"){ event.target.classList = "diactiveisbtn"; document.getElementById("gorightslide").classList = ""; document.getElementById("twoblockshowblog").style.display = "none"; document.getElementById("oneblockshowblog").style.display = "block"; // you can add here css animation (@keyframe) } } } ```
25,729,901
Is there any expert out there that can help me with the following? I have the following system calls in C: ``` access() unlink() setsockopt() fcntl() setsid() socket() bind() listen() ``` I want to know if they may fail with error code -1 and errno EINTR/EAGAIN. Should I have to handle EINTR/EAGAIN for these? The documentation do not refer anything related to EINTR/EAGAIN but many people I see handle it. Which is the correct? Here is how I register signal handlers : <https://gitorious.org/zepto-web-server/zepto-web-server/source/b1b03b9ecccfe9646e34caf3eb04689e2bbc54dd:src/signal-dispatcher-utility.c> With this configuration: <https://gitorious.org/zepto-web-server/zepto-web-server/source/b1b03b9ecccfe9646e34caf3eb04689e2bbc54dd:src/server-signals-support-utility.c> Also here is a commit that I added some EINTR/EAGAIN handling in some system calls that I know that return EINTR or EAGAIN : <https://gitorious.org/zepto-web-server/zepto-web-server/commit/b1b03b9ecccfe9646e34caf3eb04689e2bbc54dd>
2014/09/08
[ "https://Stackoverflow.com/questions/25729901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3763715/" ]
See <http://man7.org/linux/man-pages/man7/signal.7.html> -- start reading near the bottom where it talks about "Interruption of system calls and library functions..." This is a Linux man page, but the info is pretty generally applicable to any Unix/Posix/Linux-flavored system.
[signal(7)](http://man7.org/linux/man-pages/man7/signal.7.html) for Linux lists ``` accept connect fcntl flock futex ioctl open read readv recv recvfrom recvmsg send sendmsg sendto wait wait3 wait4 waitid waitpid write writev ``` as possibly interruptible (EINTR) by no-SA\_RESTART handlers and ``` setsockopt accept recv recvfrom recvmsg connect send sendto sendmsg pause sigsuspend sigtimedwait sigwaitinfo epoll_wait epoll_pwait poll ppoll select lect msgrcv msgsnd semop semtimedop clock_nanosleep nanosleep read io_getevents sleep ``` as EINTR-interruptible, even by SA\_RESTART handlers. Furthermore, it lists: ``` setsockopt accept recv recvfrom recvmsg connect send sendto sendmsg epoll_wait epoll_pwait semop semtimedop sigtimedwait sigwaitinfo read futex msgrcv msgsnd nanosleep ``` as EINTR-interruptible by a stopping signal + `SIGCONT`, and says this particular behavior is Linux-specific and not sanctioned by `POSIX.1`. Apart from these, especially if the function's specification doesn't list `EINTR`, you shouldn't get `EINTR`. If you don't trust the system to honor it, you can try bombarding a loop with your suspected system function by `SIGSTOP`/`SIGCONT`+a signal with a `no-SA_RESTART` no-op handler and see if you can elicit an EINTR. I tried that with: ``` #include <assert.h> #include <errno.h> #include <fcntl.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> static void chld(int Sig) { int status; if(0>wait(&status)) _exit(1); if(!WIFEXITED(status)){ //this can only interrupt an AS-safe block assert(WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM); puts("OK"); exit(0); } else { switch(WEXITSTATUS(status)){ case 1: puts("FAIL"); break; case 2: puts("EINTR"); break; } } exit(0); } static void nop(int Sig) { } int main() { sigset_t full; sigfillset(&full); sigaction(SIGCHLD, &(struct sigaction){ .sa_handler=chld, .sa_mask=full, .sa_flags=0 } , 0); sigaction(SIGUSR1, &(struct sigaction){ .sa_handler=nop, .sa_mask=full, .sa_flags=0 } , 0); pid_t p; if(0>(p=fork())) { perror(0); return 1; } if(p!=0){ //bombard it with SIGSTOP/SIGCONT/SIGUSR1 for(;;){ usleep(1); kill(p, SIGSTOP); kill(p, SIGCONT); kill(p, SIGUSR1); } }else{ sigaction(SIGCHLD, &(struct sigaction){ .sa_handler=SIG_DFL }, 0); if(0>alarm(1)) return 1; for(;;){ #if 1 /*not interruptible*/ if(0>access("/dev/null", R_OK)){ if(errno==EINTR) return 2; perror(0); return 1; } #else int fd; unlink("fifo"); if(0>mkfifo("fifo",0600)) return 1; /*interruptible*/ if(0>(fd=open("fifo", O_RDONLY|O_CREAT, 0600))){ if(errno==EINTR) return 2; perror(0); return 1; } close(fd); #endif } } return 0; } ``` and `unlink` and `access` definitely appear to be EINTR-uninterruptible (in compliance with their spec), which means an `EINTR`-retry loop around them would be unnecessary.
179,255
My partner and I have worked as software engineers in academia for several years in multiple very different schools & departments. However every job has been very independent. I have a boss and coworkers but I end up working mostly independently and on very different projects than my coworkers. My partner recently left academia and took a job as a software engineer at a startup. Instantly he has found himself in an extremely collaborative environment. He is regularly programming with another person and in close daily contact with several colleagues. I've heard things are similar from other people I know who work at startups. Why is the culture at startups so collaborative and the culture in academia so independent? Is there a way I could influence the culture in my academia-based workplace to be more collaborative? For context: I am currently a staff data scientist at a large university medical school. In the past I've been a research programmer for a psychology lab and a web developer at a business school. I've been at the same university for 11 years.
2021/10/14
[ "https://workplace.stackexchange.com/questions/179255", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/130010/" ]
Collaboration is driven by a need for collaboration, bottom line. In academia, collaboration often manifests itself in mentor-mentee relationships or in co-writing papers. In software, collaboration manifests in terms of large projects and separation of responsibilities, but also in mentor-mentee relationships. If you, as an academic, want to have more collaboration, try taking on some students and mentoring them, or try finding a research project that you can collaborate on with a colleague. Not having an academic background myself, I can't suggest what something like that might look like, but there are some ideas for you. Another thing to be aware of is that academia often focuses on personal worth; how many papers one authors, how many journals one publishes, how many conferences one attends or contributes to or speaks at. Therefore, there is added pressure to be competitive; if someone else authors a paper, that's a paper that you didn't author, so therefore you have to be the one to write that paper. If someone else publishes in a journal, that's a journal article slot that you didn't get, so that means you have to be competitive for that journal slot. And so on. Companies don't really work like that: it's rare for individuals to be unduly given credit for the work of their team; usually, when a project is delivered, the whole team gets credit, and only truly outstanding efforts are mentioned individually. Of course, promotions and raises happen on a by-person basis, but when one person shows advanced skill to get a promotion, that's (usually) not taking the promotion away from someone else (not in software, at least; it happens in other fields more). Therefore, there's really no competition in software in the same way as academia and people are more open to collaboration.
In the real world, companies fight each other. If a company does not deliver, its employee will soon need to find themselves a new working place. So, usually, in companies, the main goal is the success of the company. So people will, usually, cooperate in order to deliver faster and better products for the overall good of the company, that will result in better working place for themselves
15,424,910
I'm trying to see if there's a simple way to access the internal scope of a controller through an external javascript function (completely irrelevant to the target controller) I've seen on a couple of other questions here that `angular.element("#scope").scope();` would retrieve the scope from a DOM element, but my attempts are currently yielding no proper results. Here's the jsfiddle: <http://jsfiddle.net/sXkjc/5/> I'm currently going through a transition from plain JS to Angular. The main reason I'm trying to achieve this is to keep my original library code intact as much as possible; saving the need for me to add each function to the controller. Any ideas on how I could go about achieving this? Comments on the above fiddle are also welcome.
2013/03/15
[ "https://Stackoverflow.com/questions/15424910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1709725/" ]
Here's a reusable solution: <http://jsfiddle.net/flobar/r28b0gmq/> ``` function accessScope(node, func) { var scope = angular.element(document.querySelector(node)).scope(); scope.$apply(func); } window.onload = function () { accessScope('#outer', function (scope) { // change any property inside the scope scope.name = 'John'; scope.sname = 'Doe'; scope.msg = 'Superhero'; }); }; ```
The accepted answer is great. I wanted to look at what happens to the Angular scope in the context of `ng-repeat`. The thing is, Angular will create a sub-scope for each repeated item. When calling into a method defined on the original `$scope`, that retains its original value (due to javascript closure). However, the `this` refers the calling scope/object. This works out well, so long as you're clear on when `$scope` and `this` are the same and when they are different. hth Here is a fiddle that illustrates the difference: <https://jsfiddle.net/creitzel/oxsxjcyc/>
43,120,912
It's probably really obvious once you know the answer, but I can't find it anywhere. I'm not talking about *making* an installer, I'm talking about running the installer that lets me modify which features of Visual Studio 2017 are installed. The main screen looks like this: [![enter image description here](https://i.stack.imgur.com/e9LVG.png)](https://i.stack.imgur.com/e9LVG.png) the screen I need is this one: [![enter image description here](https://i.stack.imgur.com/lVM6z.png)](https://i.stack.imgur.com/lVM6z.png) In Visual Studio 2017, there is a menu entry for "Extensions and Updates" under the Tool menu that doesn't take me to this application. There is also a "NuGet Package Manager" which isn't even close. In my Windows 10 start menu, I see Visual Studio 2017 itself, and a folder named "Visual Studio 2017" that contains a couple of command prompts and a "Debuggable Package Manager". In the Control Panel - Programs and Features, I see Microsoft Visual Studio 2017 but right-click only gives me "Uninstall".
2017/03/30
[ "https://Stackoverflow.com/questions/43120912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1997735/" ]
I also found it a bit strange that you cannot modify the installation from *Control Panel - Programs and Features*. You can however launch the Visual Studio 2017 installer from the following location: ``` %ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vs_installer.exe ```
Under Projects/New in VS there is a link to go to the Installer. That is the easiest way to start the Installer and get to the positions (panels) you want.
22,761,101
I have a navigation called #nav ul li a. In this list, I want to add the class active to the element on which has been clicked. This is my jquery ``` $(document).ready(function() { $('#nav ul li a').click(function() { $('#nav ul li a').removeClass('active"'); $(this).addClass('active'); return false; }); }); ``` and this is my html ``` <header id="header"> <h1 id="logo"><a href="#intro">DerW&auml;schestuhl</a></h1> <nav id="nav"> <ul> <li><a href="#one" class="active" id="uebersicht-btn">&Uuml;bersicht</a></li> <li><a href="#two" class="" id="aussehen-btn">Aussehen</a></li> <li><a href="#work" class="" id="funktionen-btn">Funktionen</a></li> <li><a href="#produktion" class=""id="produktionen-btn">Produktion</a></li> <li><a href="#contact" class="" id="kaufen-btn">Kaufen</a></li> </ul> </nav> </header> ``` and here is my jsfiddle to show the stylesheets: <http://jsfiddle.net/Usgk3/> Do you guys have any idea why it isnt working? I cant find the mistake
2014/03/31
[ "https://Stackoverflow.com/questions/22761101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3320275/" ]
Try ``` $(document).ready(function() { $('#nav ul li a').click(function(e) { $('.active').removeClass('active'); $(this).addClass('active'); return false; }); }); ``` [**Demo**](http://jsfiddle.net/Usgk3/4/)
You're missing jQuery in your fiddle demo. You also need yo use: ``` $('#nav ul li a').removeClass('active'); ``` instead of: ``` $('#nav ul li a').removeClass('active"'); // -- ^ Remove this ``` **[Updated Fiddle](http://jsfiddle.net/Usgk3/11/)**
917,566
Working on a little Ruby script that goes out to the web and crawls various services. I've got a module with several classes inside: ``` module Crawler class Runner class Options class Engine end ``` I want to share one logger among all those of those classes. Normally I'd just put this in a constant in the module and reference it like so: ``` Crawler::LOGGER.info("Hello, world") ``` The problem is that I can't create my logger instance until I know where the output is going. You start the crawler via command line and at that point you can tell it you want to run in development (log output goes to STDOUT) or production (log output goes to a file, crawler.log): ``` crawler --environment=production ``` I have a class `Options` that parses the options passed in through the command line. Only at that point do I know how to instantiate the logger with the correct output location. So, my question is: how/where to I put my logger object so that all my classes have access to it? I could pass my logger instance to each `new()` call for every class instance I create, but I know there has to be a better, Rubyish way to do it. I'm imagining some weird class variable on the module that shared with `class << self` or some other magic. :) A little more detail: `Runner` starts everything by passing the command line options to the `Options` class and gets back an object with a couple of instance variables: ``` module Crawler class Runner def initialize(argv) @options = Options.new(argv) # feels like logger initialization should go here # @options.log_output => STDOUT or string (log file name) # @options.log_level => Logger::DEBUG or Logger::INFO @engine = Engine.new() end def run @engine.go end end end runner = Runner.new(ARGV) runner.run ``` I need the code in `Engine` to be able to access the logger object (along with a couple more classes that are initialized inside `Engine`). Help! All of this could be avoided if you could just dynamically change the output location of an already-instantiated Logger (similar to how you change the log level). I'd instantiate it to STDOUT and then change over to a file if I'm in production. I did see a suggestion somewhere about changing Ruby's $stdout global variable, which would redirect output somewhere other than STDOUT, but this seems pretty hacky. Thanks!
2009/05/27
[ "https://Stackoverflow.com/questions/917566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/113347/" ]
With the design you've laid out, it looks like the easiest solution is to give Crawler a module method that returns a module ivar. ``` module Crawler def self.logger @logger end def self.logger=(logger) @logger = logger end end ``` Or you could use "`class <<self` magic" if you wanted: ``` module Crawler class <<self attr_accessor :logger end end ``` It does the exact same thing.
A little chunk of code to demonstrate how this works. I'm simply creating a new basic Object so that I can observe that the object\_id remains the same throughout the calls: ``` module M class << self attr_accessor :logger end @logger = nil class C def initialize puts "C.initialize, before setting M.logger: #{M.logger.object_id}" M.logger = Object.new puts "C.initialize, after setting M.logger: #{M.logger.object_id}" @base = D.new end end class D def initialize puts "D.initialize M.logger: #{M.logger.object_id}" end end end puts "M.logger (before C.new): #{M.logger.object_id}" engine = M::C.new puts "M.logger (after C.new): #{M.logger.object_id}" ``` The output of this code looks like (an `object_id` of 4 means `nil`): ``` M.logger (before C.new): 4 C.initialize, before setting M.logger: 4 C.initialize, after setting M.logger: 59360 D.initialize M.logger: 59360 M.logger (after C.new): 59360 ``` Thanks for the help guys!
11,382,975
How can I make `QGraphicsView` look flat? It looks like this: ![enter image description here](https://i.stack.imgur.com/ZYxbY.png) I don't want the outline to be shown. Thanks!
2012/07/08
[ "https://Stackoverflow.com/questions/11382975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/288280/" ]
`QGraphicsView` inherits from `QFrame`. Use the [`setFrameStyle`](http://qt-project.org/doc/qt-4.8/qframe.html#setFrameStyle) method and the [`lineWidth`](http://qt-project.org/doc/qt-4.8/qframe.html#lineWidth-prop) property to change the frame [appearance](http://qt-project.org/doc/qt-4.8/qframe.html#details).
You can also use the stylesheet to customize the look (including the borders) of a QFrame, see the [stylesheet doc](http://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qframe). To make your widget look flat just add this CSS : `border: 0px`
9,080
In Luke 24:16, in the use of the passive voice true to the Greek? > > "Their eyes were kept from recognizing him." (NRSV) > > > Only one English translation (NLV) has it that God kept them from recognizing Jesus on the road to Emmaus. I'm wondering if the Greek really implies that it was God, or if it may have been their own limitations that kept their eyes from recognizing him.
2014/05/01
[ "https://hermeneutics.stackexchange.com/questions/9080", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/4056/" ]
It is Passive ------------- The verb is ἐκρατοῦντο (ekratounto), which is the imperfect **passive** indicative 3rd plural of the verb κρατέω (krateō), which in this context has the idea of "restrain."1 However, it is not that they did not "see" Jesus (v.15) in some respect, but that when they saw Him, they did not "know" (ἐπιγνῶναι; epignōnai) it was Him, hence the NRSV notation of a failure in "recognizing" Him. As ἐκρατοῦντο is imperfect tense, it has a continuous idea to it. So "their eyes were being restrained so as to not know him." Nature of the "Blindness" ------------------------- It may well be this restraint was "physical" in that Jesus was cloaked in some way to prevent seeing His face. However, there is strong evidence that their lack of recognition was also present with His voice and teaching (vv.17, 19, 25-27), which points to a "stronger" blindness to His identity than merely visual lack of recognition. Was it in part because of their unbelief (v.25)? Maybe, but it seems there must be more. Not until His acts of taking, blessing, and breaking bread with them is He known to them (v.30-31). And at that point it is ***another passive*** verb when "their eyes were opened" (διηνοίχθησαν; diēnoichthēsan), this one aorist tense, not implying a continuous action, but simply stating the event of the opening occurred. Then they "knew" (ἐπέγνωσαν; epegnōsan) Him. In themselves, they had felt their "hearts burning within" (v.32) as Jesus spoke to them, but this hint of recognition *from within themselves* was not enough to break the restraint. That seems like evidence that the restraint is not because of "their own limitations" as you ask. Conclusion ---------- It is true that God is not explicitly stated as being the active agent in restraining the eyes and then opening them, but it is strongly implied. The context communicates that their inability to know it was Jesus was not just their limitation, but something more. I think it likely that Jesus wanted to convey the message He had for them without "distracting them" (so to speak) by His presence being revealed. God reveals knowledge to others in His time and His way, and here is an example of that. --- **NOTES** 1 William Arndt, Frederick W. Danker, and Walter Bauer, *A Greek-English Lexicon of the New Testament and Other Early Christian Literature* (Chicago: University of Chicago Press, 2000), s.v. κρατέω, entry #5.
The causal agent of the passive voice does not appear to be God, but unbelief. That is, there is compelling biblical evidence that the agent of the blindness in this context (in the passive voice) was "slowness of heart." First we see that when Jesus had earlier spoken of his imminent death and resurrection, the disciples did not understand because at that time they did not believe the Scriptures. > > [**John 2:19-22**](http://www.biblegateway.com/passage/?search=Jn%202:19-22&version=NASB) (NASB) > > 19 Jesus answered them, “Destroy this temple, and in three days I will raise it up.” 20 The Jews then said, “It took forty-six years to build this temple, and will You raise it up in three days?” 21 But He was speaking of the temple of His body. 22 **So when He was raised from the dead, His disciples remembered that He said this; and they believed the Scripture and the word which Jesus had spoken.** > > > It was not until after his resurrection that they believed. That is, unbelief blocked their understanding of the resurrection of Jesus. In the passive voice, the truth therefore became concealed or hidden from them. > > [**Luke 9:43-45**](http://www.biblegateway.com/passage/?search=Luke%209:43-45&version=NASB) (NASB) > > 43 But while everyone was marveling at all that He was doing, He said to His disciples, 44 “Let these words sink into your ears; for the Son of Man is going to be delivered into the hands of men.” 45 But they did not understand this statement, **and it was concealed from them so that they would not perceive it**; and they were afraid to ask Him about this statement. > > > [**Luke 18:31-34**](http://www.biblegateway.com/passage/?search=Luke%2018:31-34&version=NASB) (NASB) > > 31 Then He took the twelve aside and said to them, “Behold, we are going up to Jerusalem, and all things which are written through the prophets about the Son of Man will be accomplished. 32 For He will be handed over to the Gentiles, and will be mocked and mistreated and spit upon, 33 and after they have scourged Him, they will kill Him; and the third day He will rise again.” 34 **But the disciples understood none of these things, and the meaning of this statement was hidden from them, and they did not comprehend the things that were said.** > > > It was not God as the primary cause, but unbelief that blocked their full understanding until Jesus identified himself after the resurrection. Notwithstanding that the resurrected body of Jesus still bore the scars of the crucifixion (compare [John 20:20](http://www.biblegateway.com/passage/?search=John%2020:20&version=NASB) with [Revelation 5:6](http://www.biblegateway.com/passage/?search=Revelation%205:6&version=NASB)) and in this sense his glorified body was **disfigured** (please click [**here**](https://hermeneutics.stackexchange.com/a/8975/921) for more discussion, s.v., *Argument from Disfiguration*), the PRINCIPAL cause of their lack of recognition and discernment was their lack of faith, and so they were not looking for or expecting the resurrection of Jesus. For example, when the risen Jesus was on the road to Emmaus, he chided his disillusioned disciples in this regard with the following words: > > [**Luke 24:25-26**](http://www.biblegateway.com/passage/?search=Luke%2024:25-26&version=NASB) (NASB) > > 25 And He said to them, “**O foolish men and slow of heart to believe in all that the prophets have spoken!** 26 Was it not necessary for the Christ to suffer these things and to enter into His glory?” > > > This statement was not rhetorical flourish, but an encouraging reprimand because of their lack of faith in the Scriptures. Again, the natural body of Jesus had undergone its physical transformation at resurrection ([1 Cor 15:43-51](http://www.biblegateway.com/passage/?search=1%20Cor%2015:43-51&version=NASB)), however it was still their internal bias --based on their lack of faith-- that caused the blindness of these disciples on the road to Emmaus to "see" Jesus. When they finally recognized Jesus, was it because they saw his **"disfigured"** hands with the nail marks as he broke the bread in front of them? Finally, without casting moral aspersions on the weakness of faith among the disciples of Jesus (since we are no better than they), we see that an internal bias occurs when one does not accept the plain and normal reading of Scripture by faith. When we receive the Scriptures like children, the Lord reveals the wisdom of His word. > > [**Luke 10:21**](http://www.biblegateway.com/passage/?search=Luke%2010:21&version=NASB) (NASB) > > 21 At that very time He rejoiced greatly in the Holy Spirit, and said, “I praise You, O Father, Lord of heaven and earth, that You have hidden these things from the wise and intelligent and have revealed them to infants. Yes, Father, for this way was well-pleasing in Your sight. > > > In conclusion, the bias from unbelief will result in "blindness," which filters out anything that contradicts that internal bias (to include the appearance of someone like Jesus who rises from the dead -- see [Luke 16:31](http://www.biblegateway.com/passage/?search=Luke%2016:31&version=NASB)). In this sense, and in the passive voice, is the truth thus "concealed or hidden" from us so that we are "kept from seeing" and understanding the Word of God (who is Jesus). We must trust His word therefore like children.
69,828,503
Within my app the user is prompted to create a zip file using intent ACTION\_CREATE\_DOCUMENT (as in [here](https://stackoverflow.com/questions/8586691/how-to-open-file-save-dialog-in-android)) This returns a content URI to my app, similar to: `content:/com.android.externalstorage.documents/document/primary%3ADocuments%2Fbackup.zip` This is the backup file that my app will write to after the user has picked a location. I need to check if the selected location has enough space for the file, because the file can get very large, up to more than 1GB. The problem is, that I can't find a proper, standardized way to check if the amount of bytes I'm going to write to the file fits within the free space of the user-selected folder. Many of the old approaches don't work, since I can't access the file system directly. I tried [this](https://developer.android.com/training/data-storage/app-specific#query-free-space) solution from the docs, but it only seems to adress files that are within the apps private, scoped storage. `StorageManager` and `StorageStatsManager` also don't seem to work, as they seemingly can't understand content-uris, but only standart Java-`File` objects that I can't use. How do I do a simple check on how much space is available?
2021/11/03
[ "https://Stackoverflow.com/questions/69828503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8260782/" ]
I encoutered this same problem before... When you change the definition of `Future` (in `_userProfile`), you expect the future to update... but nothing happens... The reason is that the Future will NOT update the `snapshot.hasError`, nor `snapshot.hasData` nor the `else`... The only thing that changes is `ConnectionState.done` **Solution:** add a new condition after `if (snapshot.hasError)` that will include `ConnectionState.done`. Then when you setState, it will rebuild properly More information in [this](https://www.greycastle.se/reloading-future-with-flutter-futurebuilder/) excellent explanation Let me know if you still have trouble.
This is how I would do it: ``` return FutureBuilder<UserProfile>( future: _userProfile, builder: (context, snapshot) { if (snapshot.connectionState != ConnectionState.done) { return const Center(child: CircularProgressIndicator()); } if (snapshot.hasError) { print(snapshot.error); return Center(child: ErrorPage(context)); } if (!snapshot.hasData) { print("_userProfile returns null!"); return Center(child: ErrorPage(context)); } final userProfile = snapshot.data as UserProfile; // cast to UserProfile return Padding(...); // use userProfile in here } } ```
17,666,803
My code works as follows: * Text comes to server (from textarea) * Text is ran through trim() then nl2br But what is happening is it is adding a `<br>` but not removing the new line so ``` " something" ``` becomes ``` "<br> something" ``` which adds a double new line. Please help this error is ruining all formatting, I can give more code on request. Creation of post: Shortened creation method (Only showing relevent bits) Creation method: ``` BlogPost::Create(ParseStr($_POST['Content'])); ``` ParseStr runs: ``` return nl2br(trim($Str)); ``` Viewing of post: ``` echo "<span id='Content'>".BlogPosts::ParseBB(trim($StoredPost->Content))."</span>"; ``` ParseBB runs: ``` $AllowedTags = array( // i => Tag, Tag Replacement, Closing tag 0 => array("code","pre class='prettyprint'",true), 1 => array("center","span style='text-align:center;'",true), 2 => array("left","span style='text-align:right;'",true), 3 => array("right","span style='text-align:left;'",true) ); $AllowedTagsStr = "<p><a><br><br/><b><i><u><img><h1><h2><h3><pre><hr><iframe><code><ul><li>"; $ParsedStr = $Str; foreach($AllowedTags as $Tag) { $ParsedStr = str_replace("<".$Tag[0].">","<".$Tag[1].">",$ParsedStr); if($Tag[2]) $ParsedStr = str_replace("</".$Tag[0].">","</".$Tag[1].">",$ParsedStr); } return strip_tags($ParsedStr,$AllowedTagsStr); ``` Example: What I see: ![](https://i.stack.imgur.com/90tUm.png) What is shown: ![](https://i.stack.imgur.com/xVvLg.png)
2013/07/16
[ "https://Stackoverflow.com/questions/17666803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1763295/" ]
It's because [`nl2br()`](http://php.net/nl2br) doesn't remove new lines at all. > > Returns string with `<br />` or `<br>` **inserted before** all newlines (`\r\n`, `\n\r`, `\n` and `\r`). > > > Use `str_replace` instead: ``` $string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string); ```
Aren't you using UTF-8 charset? If you are using multibyte character set (ie UTF-8), trim will not work well. You must use multibyte functions. Try something like this one: <http://www.php.net/manual/en/ref.mbstring.php#102141> Inside `<pre>` you should not need to call nl2br function to display break lines. Check if you really want to call nl2br when you are creating post. You probably need it only on displaying it.
1,355,608
I would like to be able to do something like (psuedo-code): ``` if (classAvailable) { // do a thing } else { // do a different thing } ``` What would be even better is if I could extend a class from ClassA if it's available or ClassB, if it isn't. I suspect this isn't possible though.
2009/08/31
[ "https://Stackoverflow.com/questions/1355608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/76835/" ]
I don't think there's a way to dynamically choose whether to extend one class or another, except if you made a program that can manipulate bytecode directly (simple example: hold the compiled bytecode for both versions of the subclass as strings, and just use a `ClassLoader` to load whichever one corresponds to the superclass you have available). You could do it in Python, though ;-)
In case you are using Spring, try to use org.springframework.util.ClassUtils#isPresent
9,201,816
I am trying to use a DataView.RowFilter in order to filter all entries that do not belong in a specified year. My code is as follows: ``` bigDT.DefaultView.RowFilter = "year(date_posted)=2011"; ``` This however, does not work. I have read that I can specify DateTimes using a format like "#mm/dd/yyyy#". I'd prefer if I could check only the year, as users can specify a year, or no year, or month, or day, etc. Thank you.
2012/02/08
[ "https://Stackoverflow.com/questions/9201816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1178551/" ]
Valid [expressions](http://msdn.microsoft.com/en-us/library/cabd21yw%28vs.71%29.aspx) for DateTime. You can do something like ``` "date_posted > #1/1/2011# AND date_posted < #12/31/2011#" ```
Make sure the document has the column name "year" and the field in that column is a text or datetime. If it is datetime, you need to be specific and probably include the date, time, etc. If it is text it should be defaultview.rowfilter = "year = 2011".
62,454,825
``` const express = require('express'), app = express(), path = require('path'), mongoose = require('mongoose'), userGuess = document.getElementById('userGuess'), lastResult = document.getElementById('lastResult'), numRound = document.getElementById('numRound'), roundDiv = document.getElementById('roundDiv'), correctNum = document.getElementById('correctNumber'), startButton = document.getElementById('startButton'), gameInputs = document.getElementById('gameInputs'), guessSubmit = document.getElementById('submitGuess'), health = document.getElementById('health'), easy = document.getElementById('easy'), normal = document.getElementById('normal'), hard = document.getElementById('hard'), labelDifficulty = document.getElementById('labelNum'), points = document.getElementById('points'), span = document.getElementsByClassName('close')[0], modal = document.getElementById('myModal'), playerNames = document.getElementById('playerNames'), playerName = document.getElementById('playerName'), submitName = document.getElementById('submitName'), cheat = document.getElementById('cheatMod'), resetGame = document.getElementById('resetGame') ``` In my app.js file, I am manipulating a lot of elements, which is coming from an index.html file, connected to the said app.js file as a script. Is there any way I can accomplish what I'm trying to do here, but on the node.js? I just need to add a database so I can save highscores and player names. Thank you.
2020/06/18
[ "https://Stackoverflow.com/questions/62454825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13648276/" ]
I was able to bypass nmy problem by just linking my DOM manipulation from a seprate index.js file, instead of manipulating from my app.js which runs my node. Thank you for your help guys.
Nodejs is server-side. It really isn't supposed to use methods from `windows` or `document`. If you do it will say it's undefined. There is one way and that is to use puppeteer. <https://www.npmjs.com/package/puppeteer> Keep in mind you must run puppeteer commands asynchronously. But for the basics and to just do what you want to do try: ``` const puppeteer = require('puppeteer'); var x = async(){ const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('<url>'); await page.evaluate(() => { //insert code here like you would in the console in your browser's devTools }) await browser.close(); } ``` Check out the puppeteer documentation here: <https://pptr.dev/>
14,852,251
I am programming in VS2010 and Windows 7. I am calling the `WinBioOpenSession` function from `winbio.h` This is my code: ``` WINBIO_SESSION_HANDLE sessionHandle = NULL; hr = WinBioOpenSession( WINBIO_TYPE_FINGERPRINT, WINBIO_POOL_SYSTEM, WINBIO_FLAG_RAW, NULL, 0, WINBIO_DB_DEFAULT, &sessionHandle ); ``` hr returns `E_ACCESSDENIED` return code? How can I resolve this?
2013/02/13
[ "https://Stackoverflow.com/questions/14852251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1360473/" ]
Polymorphism? ``` public class UserController : Controller { [HttpPost] public virtual ActionResult SaveUser(User user) { } } public class UserController : Core.UserController { [HttpPost] public override ActionResult SaveUser(User user) { var customUser = user as Custom.User; if(customUser != null) { //Your code here ... } } } ```
Another possible workaround if the polymorphism solution doesn't work or isn't acceptable, would be to either rename your UserController or its action method to something slightly different: ``` public class CustomUserController : Core.UserController { [HttpPost] public ActionResult SaveUser(Custom.User user) { } } public class UserController : Core.UserController { [HttpPost] public ActionResult SaveCustomUser(Custom.User user) { } } ``` If you wanted to keep the routes consistent with the other project, you would just have to create a custom route for this.
619,155
Considering the scattering of gamma rays on a deuteron, which leads to its break up acording to: $$ \gamma+ d \longrightarrow p +n $$ we can use the conservation of energy and momentum in order to determine the minimum photon energy in order to make this reaction possible, which happens to be very close to the binding energy of the deuteron nuclide. We assume that the speed of the proton and neutron after scattering are highly non-relativistic. So, the conservation of energy: $$ p\_{\gamma}c + m\_dc^2=m\_pc^2+m\_nc^2+ \frac{1}{2}m\_pv\_p^2+\frac{1}{2}m\_nv\_n^2 \tag 1$$ and of momentum: $$ \vec p\_{\gamma} = m\_p \vec v\_{p}+m\_n \vec v\_{n} \tag 2$$ Squaring equation $(2)$ we obtain: $$ p\_{\gamma}^{ \space 2} = m\_p^{ \space 2}v\_{p}^{ \space 2}+m\_n^{ \space 2}v\_{n}^{ \space 2} + 2m\_pm\_n \vec v\_{n}\cdot \vec v\_p \tag 3$$ But if we are looking for the minimum photon energy, then we must find the case where the proton and neutron speeds are also minimum. We assume $m\_p \approx m\_n$ and $v\_n \approx v\_p$. With these approximations and the deuteron mass formula: $m\_d = m\_n + m\_p -\frac{B\_d}{c^2}$ we should be able to get to this equation: $$ p\_{\gamma}^2 = 2 m\_d \left( \frac{1}{2}m\_pv\_p^2 + \frac{1}{2}m\_nv\_n^2 \right) \tag 4$$ but I'm having trouble getting there. Can someone show me how to do it?
2021/03/06
[ "https://physics.stackexchange.com/questions/619155", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/276140/" ]
There are several presentations of [Zeno's paradoxes](https://en.wikipedia.org/wiki/Zeno%27s_paradoxes). One version is as follows (taken from Wikipedia): --- Suppose Atalanta wishes to walk to the end of a path. Before she can get there, she must get halfway there. Before she can get halfway there, she must get a quarter of the way there. Before traveling a quarter, she must travel one-eighth; before an eighth, one-sixteenth; and so on. The resulting sequence can be represented as: $${\displaystyle \left\{\cdots ,{\frac {1}{16}},{\frac {1}{8}},{\frac {1}{4}},{\frac {1}{2}},1\right\}} $$ This description requires one to complete an infinite number of tasks, which Zeno maintains is an impossibility. --- There are a number of resolutions to the paradox. The simplest, perhaps, is just to ask "why is it impossible to complete an infinite number of tasks?" Without this premise, the conclusion of the argument doesn't hold. If you now ask about spacetime being discretized, then it is not even clear what argument there is left to be made. We *wouldn't* need an infinite number of tasks to be completed, so the argument towards the impossibility of motion becomes even less clear. Another version, the arrow version, is (again taken from Wikipedia): --- In the arrow paradox, Zeno states that for motion to occur, an object must change the position which it occupies. He gives an example of an arrow in flight. He states that in any one (duration-less) instant of time, the arrow is neither moving to where it is, nor to where it is not. It cannot move to where it is not, because no time elapses for it to move there; it cannot move to where it is, because it is already there. In other words, at every instant of time there is no motion occurring. If everything is motionless at every instant, and time is entirely composed of instants, then motion is impossible. --- A possible resolution to this paradox is to simply ask, why must it be the case that "at every instant of time there is no motion occurring?" For example, from the point of view of classical physics the velocity of particle can be defined at any instant. The paradox is trading off on a number of ambiguities surrounding the definition of motion without ever defining what motion is. As written, the argument is full of non-sequiturs. Again, it is not clear what discretizing space-time has to do with this.
Zeno's paradox is based on incorrect logical reasoning, as he did not take into account that shorter length steps are associated with shorter time steps as well. And incorrect logical reasoning can not hold the key to *anything*.
26,174
We all know the halacha of [עִבְדוּ אֶת-יְה-ה בְּשִׂמְחָה](http://www.mechon-mamre.org/p/pt/pt26a0.htm#2) (Tehillim 100:2). But the gemara paskens (Pesachim 109a) that since the destruction of the Beis Hamikdash "אין שמחה אלא ביין" ("Joy only comes from wine"). So obviously, one must be drunk whenever serving G-d. Lest one think that there are *some* times one can be sober, the Mishna (Avos 2:19) tells us "לא עליך כל המלאכה לגמור" (that one may never stop serving G-d). Clearly, one is always obligated to be drunk. So how is Purim different? This question is [Purim Torah](http://en.wikipedia.org/wiki/Purim_Torah) and is not intended to be taken completely seriously. See the [Purim Torah policy](https://judaism.meta.stackexchange.com/questions/797/). ===================================================================================================================================================================================================================
2013/02/11
[ "https://judaism.stackexchange.com/questions/26174", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/883/" ]
In the Gemara it says: "לבסומי בפוריא". Which is commonly translated as drink. However it's clear that לבסומי is actually a reference to the word סמים which means drugs. Other translations for לבסומי are "sweet things", and "sing agreeably". [Ref](http://joshyuter.com/wp-content/uploads/2011/03/Drinking-on-Purim.pdf) Clearly the intent of the Gemara is that a person should make brownies laced with drugs, and eat them until they spontaneously sing. This conveniently fulfills all the dictums of Purim at once: Drinking, feasting and making merry.
So it's well known that you must drink on Purim - however it does not specify *what* you must drink. On every day of the year you must drink wine (אלא ביין....) but on Purim you must drink water till you experience [water intoxication](http://en.wikipedia.org/wiki/Water_intoxication). Some of the symptoms of water intoxication are confusion and drowsiness, which fulfills the dictum of עד דלא ידע.
74,174,807
i am trying to use the isEnabled and setIsEnabled useState Hook to update the icon of the play button. When I hit the playbutton, the icon changes appropriately with the useState Hook assumingly triggering a re render, but hitting the restart btn (although i am calling the setIsEnabled) is not triggering a re render of the playbutton icon. Is there a way to force reload it or is there something I'm doing wrong with the useState hook ---- ActionBtn.jsx ------ ``` export const ActionButton = (props: { name: string; themeColor: string; timerReference: any; }) => { // tracker for whether timer is active const [isEnabled, setIsEnabled] = useState(false); // handle button press for each button // settings btn const openSettings = () => { addHapticFeedback("light"); alert("settings"); }; // play & pause btn const toggleTimer = () => { // toggle play or pause button setIsEnabled(!isEnabled); addHapticFeedback("light"); if (isEnabled) { props.timerReference.current.pause(); } else { props.timerReference.current.play(); } }; // restart btn const restartTimer = () => { // deactivate timer setIsEnabled(false); addHapticFeedback("light"); props.timerReference.current.reAnimate(); props.timerReference.current.pause(); }; // define type of action button based on prop passed if (props.name === "settings") { return ( <TouchableOpacity style={[styles.button, { backgroundColor: props.themeColor }]} onPress={openSettings} > <SettingsIcon size={iconSize} fillColor={iconColor} /> </TouchableOpacity> ); } else if (props.name === "play") { return ( <TouchableOpacity style={[styles.button, { backgroundColor: props.themeColor }]} onPress={toggleTimer} > <PlayIcon size={iconSize} fillColor={iconColor} isEnabled={isEnabled} /> </TouchableOpacity> ); } else if (props.name === "restart") { return ( <TouchableOpacity style={[styles.button, { backgroundColor: props.themeColor }]} onPress={restartTimer} > <RestartIcon size={iconSize} fillColor={iconColor} /> </TouchableOpacity> ); } else { return <View />; } }; ----- ICONS.jsx ------ export const PlayIcon = (props: { size: number; fillColor: string; isEnabled: boolean; }) => { return props.isEnabled ? ( <Svg width={props.size} height={props.size} viewBox="0 0 40 40"> <Path d="M25 31.6666C24.0833 31.6666 23.2989 31.3405 22.6467 30.6883C21.9933 30.035 21.6667 29.25 21.6667 28.3333V11.6666C21.6667 10.75 21.9933 9.96553 22.6467 9.31331C23.2989 8.65998 24.0833 8.33331 25 8.33331H28.3333C29.25 8.33331 30.035 8.65998 30.6883 9.31331C31.3406 9.96553 31.6667 10.75 31.6667 11.6666V28.3333C31.6667 29.25 31.3406 30.035 30.6883 30.6883C30.035 31.3405 29.25 31.6666 28.3333 31.6666H25ZM11.6667 31.6666C10.75 31.6666 9.96555 31.3405 9.31333 30.6883C8.65999 30.035 8.33333 29.25 8.33333 28.3333V11.6666C8.33333 10.75 8.65999 9.96553 9.31333 9.31331C9.96555 8.65998 10.75 8.33331 11.6667 8.33331H15C15.9167 8.33331 16.7017 8.65998 17.355 9.31331C18.0072 9.96553 18.3333 10.75 18.3333 11.6666V28.3333C18.3333 29.25 18.0072 30.035 17.355 30.6883C16.7017 31.3405 15.9167 31.6666 15 31.6666H11.6667Z" fill={props.fillColor} /> </Svg> ) : ( <Svg width={props.size} height={props.size} viewBox="0 0 55 55"> <Path d="M21.84 41.277c-.762.495-1.534.523-2.316.084-.78-.437-1.17-1.113-1.17-2.028V15.667c0-.915.39-1.592 1.17-2.03.782-.438 1.554-.41 2.317.086l18.635 11.833c.686.458 1.03 1.106 1.03 1.944 0 .838-.344 1.486-1.03 1.944L21.841 41.277Z" fill={props.fillColor} /> </Svg> ); }; export const RestartIcon = (props: { size: number; fillColor: string }) => { return ( <Svg width={props.size} height={props.size} viewBox="0 0 46 46"> <Path d="M24.875 22.25L29.5625 26.9375C29.9062 27.2812 30.0781 27.7187 30.0781 28.25C30.0781 28.7812 29.9062 29.2187 29.5625 29.5625C29.2188 29.9062 28.7812 30.0781 28.25 30.0781C27.7188 30.0781 27.2812 29.9062 26.9375 29.5625L21.6875 24.3125C21.5 24.125 21.3594 23.9137 21.2656 23.6787C21.1719 23.445 21.125 23.2031 21.125 22.9531V15.5C21.125 14.9687 21.305 14.5231 21.665 14.1631C22.0238 13.8044 22.4688 13.625 23 13.625C23.5312 13.625 23.9769 13.8044 24.3369 14.1631C24.6956 14.5231 24.875 14.9687 24.875 15.5V22.25ZM23 39.875C19.2188 39.875 15.8281 38.7575 12.8281 36.5225C9.82812 34.2887 7.8125 31.375 6.78125 27.7812C6.625 27.2187 6.68 26.6875 6.94625 26.1875C7.21125 25.6875 7.625 25.375 8.1875 25.25C8.71875 25.125 9.19562 25.2419 9.61812 25.6006C10.0394 25.9606 10.3281 26.4062 10.4844 26.9375C11.2969 29.6875 12.8675 31.9062 15.1962 33.5937C17.5237 35.2812 20.125 36.125 23 36.125C26.6562 36.125 29.7575 34.8512 32.3037 32.3037C34.8512 29.7575 36.125 26.6562 36.125 23C36.125 19.3437 34.8512 16.2419 32.3037 13.6944C29.7575 11.1481 26.6562 9.875 23 9.875C20.8438 9.875 18.8281 10.375 16.9531 11.375C15.0781 12.375 13.5 13.75 12.2188 15.5H15.5C16.0312 15.5 16.4769 15.6794 16.8369 16.0381C17.1956 16.3981 17.375 16.8437 17.375 17.375C17.375 17.9062 17.1956 18.3512 16.8369 18.71C16.4769 19.07 16.0312 19.25 15.5 19.25H8C7.46875 19.25 7.02375 19.07 6.665 18.71C6.305 18.3512 6.125 17.9062 6.125 17.375V9.875C6.125 9.34375 6.305 8.89812 6.665 8.53813C7.02375 8.17938 7.46875 8 8 8C8.53125 8 8.97687 8.17938 9.33687 8.53813C9.69562 8.89812 9.875 9.34375 9.875 9.875V12.4062C11.4688 10.4062 13.4144 8.85937 15.7119 7.76562C18.0081 6.67187 20.4375 6.125 23 6.125C25.3438 6.125 27.5394 6.57 29.5869 7.46C31.6331 8.35125 33.4144 9.55437 34.9306 11.0694C36.4456 12.5856 37.6488 14.3669 38.54 16.4131C39.43 18.4606 39.875 20.6562 39.875 23C39.875 25.3437 39.43 27.5387 38.54 29.585C37.6488 31.6325 36.4456 33.4137 34.9306 34.9287C33.4144 36.445 31.6331 37.6487 29.5869 38.54C27.5394 39.43 25.3438 39.875 23 39.875Z" fill={props.fillColor} /> </Svg> ); }; ```
2022/10/23
[ "https://Stackoverflow.com/questions/74174807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11683609/" ]
You forgot a period for nav\_links class. This should work: ``` .nav_links li { display: inline-block; } ```
Because you couldn't focus properly on the class selector. Actually `.nav_links` not `nav_links`. Please run the example below. ```css @import url('https://fonts.googleapis.com/css2?family=Roboto+Slab&display=swap'); *{ box-sizing: border-box; background-color: #EFF7E1; text-decoration: none; } li,a,button{ font-family: 'Roboto Slab', serif; font-weight: 400; font-size: 20px; text-decoration: none; } header{ background-image: -moz-linear-gradient(#0000ff #A2d0c1); display: flex; justify-content: space-between; align-items: center; padding: 20px 12%; } .nav_links li{ display: inline-block; } ``` ```html <html> <head> <link rel="stylesheet" href="menustyle.css"> <meta charset="UTF-8"> </head> <body> <header> <img src="Adidas_Logo.svg.png" alt="logo" style="width: 100px;"> <nav> <ul class="nav_links"> <li><a href="#">Products</a></li> <li><a href="#">Categories</a></li> <li><a href="#">Notifications</a></li> </ul> </nav> <a href="#" class="cta"><button>Card</button></a> </header> </body> </html> ```
80,581
Assume a capacitor's voltage limit be v, and the target voltage limit be V. What is the way of connecting the capacitors to reach the V?
2013/08/29
[ "https://electronics.stackexchange.com/questions/80581", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/28163/" ]
The hypothetical case of ideal capacitors which are perfectly identical in leakage current and voltage ratings, is well described in existing answers. In practice, things get a bit more complicated. If the load in the application has a high duty cycle, **active balancing of capacitors connected in series** is required, to protect the capacitors from an early demise. This can be done with discrete components, but there are also purpose-built, highly integrated capacitor balancing ICs available. While general-purpose electrolytic capacitors are sensitive to voltages over rating, non-electrolytic capacitors such as mica or ceramic ones are less so. Most sensitive are electric double layer capacitors (supercapacitors), which are also typically rated for fairly low voltages, making the problem more relevant in moderate voltage circuit designs. Thus capacitor active balancing ICs are most often used for supercapacitor banks, such as for car audio buffer capacitors. An example is the Texas Instruments [BQ33100 Super Capacitor Manager](http://www.ti.com/lit/ds/symlink/bq33100.pdf), that can manage from 2 to 5 or even 9 supercapacitors or conventional capacitors in series. Of course, for conventional electrolytic capacitors, it is simply more cost effective to use a capacitor with a higher voltage rating, or a bunch of high voltage lower value capacitors in parallel. --- At a simpler level, for low duty cycle / low load applications, a passive balancing approach can be adopted. This [Maxwell Technologies appnote](http://www.maxwell.com/products/ultracapacitors/docs/an-002_cell_balancing.pdf) describes the approach, consisting of a resistor in parallel with each capacitor, in a ladder arrangement. The resistors are sized to "dominate the total cell leakage current" by typically 10 times the maximum leakage current of the target capacitors. From [an answer to another question](https://electronics.stackexchange.com/a/80368/14004), here is such a passive balancing arrangement: ![Schematic](https://i.stack.imgur.com/lO3hU.png)
Capacitors connected in series add their voltage tolerances. (This is true if their capacitance values are identical.) Note that the equivalent capacitance value of capacitors in series is *smaller* than any individual value according to the formula: $$\frac{1}{C\_{eq}} = \frac{1}{C\_1} + \frac{1}{C\_2} + \frac{1}{C\_3} \dotsm$$
16,275,928
According to my understanding in hibernate (please confirm) 1- You have to `session.close()` if you get it by `getSessionFactory().openSession()`. 2- No need to `session.close()` if you get it by `getSessionFactory().getCurrentSession()`. It is automatically closed after **commit()**. 3- *@2* When using `getSessionFactory().getCurrentSession()`, we have to do all DB activities inside an active transaction so that we can commit() at the end. 4- Hibernate en-queues all save, update, and delete operations and submits them to the database server only after a ***flush()*** operation or ***committing*** the transaction or ***closing of the session*** in which these operations occur.(as per javadoc) From the above points if I consider **1** & **4**, then the following code should work: ``` Session session = HibernateUtil.getSessionFactory().openSession(); AccountDetails ac = new AccountDetails(); //perform set operations session.save(ac); session.close(); System.out.println("new account stored."); ``` **BUT** it is not working i.e. it runs smoothly but does not reflect(store) in database.Why this is so ? When I write the code inside a transaction and commit, then it is stored. I think I am missing a basic thing. Please clarify.
2013/04/29
[ "https://Stackoverflow.com/questions/16275928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343275/" ]
session.close() is only responsible to close the session <https://docs.jboss.org/hibernate/orm/3.5/javadocs/org/hibernate/Session.html#close()> how to work with hibernate session: <https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/transactions.html#transactions-basics> ``` // Non-managed environment idiom Session sess = factory.openSession(); Transaction tx = null; try { tx = sess.beginTransaction(); // do some work ... tx.commit(); } catch (RuntimeException e) { if (tx != null) tx.rollback(); throw e; // or display error message } finally { sess.close(); } ``` As it wrote in the documentation: a much more flexible solution is Hibernate's built-in "current session" context management: ``` // Non-managed environment idiom with getCurrentSession() try { factory.getCurrentSession().beginTransaction(); // do some work ... factory.getCurrentSession().getTransaction().commit(); } catch (RuntimeException e) { factory.getCurrentSession().getTransaction().rollback(); throw e; // or display error message } ```
Whenever you carry out any unit of work on the database objects, Transactions have to be used. <http://docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/transactions.html> shows why they are used and how they can be used. But, the key is to use a `transaction` object by calling `session.beginTransaction()` which returns a `Transaction` object. This will represent the unit of work carried out to the database.
137,675
So we have this beautiful Grohe Minta (sort of upside down 7-shaped) kitchen faucet. We want to add a drinking water faucet next to it, but cannot find any filtered water faucet that goes with the Minta's looks. So, I'm thinking of buying another kitchen or prep faucet, connect the cold water hose to the filters and cap the hot water connection. Is this ok to do? Permissible? Any issues we should be aware of? Flow, gpm? Connectors/adapters needed? Here is a pic of the Grohe Minta: [![enter image description here](https://i.stack.imgur.com/hknjV.jpg)](https://i.stack.imgur.com/hknjV.jpg)
2018/04/20
[ "https://diy.stackexchange.com/questions/137675", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/84979/" ]
Good idea. There's really no problem with that approach aside from the stagnant water that will accumulate in the faucet's hot water stub, which could be a health concern (or just gross). Instead, split your filtered water supply and run it to both the hot and cold sides of the faucet. This has the additional benefit of making the faucet flow full in all temperature modes.
I installed a whirlpool filter #WHKF-DWHBB, item #631984 that I purchased from Lowes, on the cold side of the kitchen faucet, about 10 years ago. I change the filter every 6 months. I installed the filter since we do not like the taste of the city water. The replacement filter is the one that is for taste and odor only (charcoal). The water tastes as good as bottled water. My 2 cents
103,064
Recently i have written a test class for Webservice.i got 79% .But the test class failed. And the error is "Methods defined as Test Method do not support Web service callouts ". how to resolve this error and improve code coverage? My apex class : ``` global class Rfleet_Searchaddress { public String StNumber {get;set;} public String Bcity {get;set;} public String BPostalcode {get;set;} public String BCountry {get;set;} public String Snumber {get;set;} public String street {get;set;} public Boolean refreshPage {get;set;} string Id; list < Account > updateAdd = new list < Account > (); //This method is constructor public Rfleet_Searchaddress(ApexPages.StandardController controller) { id = ApexPages.currentPage().getParameters().get('id'); refreshPage = false; } //This method is autosave the addresses public void autosave() { for (Account updatelist: [SELECT id, Rfleet_Main_Address_Number__c, Rfleet_Main_address_Street__c, BillingAddress, BillingCity, BillingCountry, BillingPostalCode, BillingState, BillingStreet FROM Account where id = : id]) { updatelist.BillingStreet = Snumber + ' ' + street; //StNumber; updatelist.BillingCity = Bcity; updatelist.BillingPostalCode = BPostalcode; updatelist.BillingState = ''; updatelist.BillingCountry = BCountry; updatelist.Rfleet_Main_Address_Number__c = Snumber; updatelist.Rfleet_Main_address_Street__c = street; updateAdd.add(updatelist); } try{ update updateAdd; }catch(DmlException e) { system.debug('update--->' + updateAdd); } refreshPage = true; } //This method is remote action @RemoteAction global static list < String > restapi(string accName) { string jsonStr; Http h = new Http(); HttpRequest req = new HttpRequest(); req.setHeader('Accept', 'application/JSON'); req.setEndpoint('http://api-adresse.data.gouv.fr/search/?q=' + EncodingUtil.urlEncode(accName, 'UTF-8')); //+'&'+'limit'+'='+'10');// req.setMethod('GET'); HttpResponse res = h.send(req); system.debug('res1===>' + res.getBody()); List < String > calOut1 = new List < String > (); JSON2Apex parsed = JSON2Apex.parse(res.getBody()); for (JSON2Apex.Features f: parsed.Features) { JSON2Apex.Properties p = f.Properties; calOut1.add(p.label + ' ' + 'FRANCE'); } return calOut1; } } ``` JSON2apex: ``` public class JSON2Apex { public String query; public String version; public String licence; public List<Features> features; public String type; public String attribution; public class Geometry { public List<Double> coordinates; public String type; } public class Features { public Geometry geometry; public String type; public Properties properties; } public class Properties { public String city; public String label; public String id; public String postcode; public String name; public String citycode; public String context; public Double score; public String type; } public static JSON2Apex parse(String json) { return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class); } static testMethod void testParse() { String json = '{\"query\": \"8\", \"version\": \"draft\", \"licence\": \"ODbL 1.0\", \"features\": [{\"geometry\": {\"coordinates\": [5.600741, 43.28252], \"type\": \"Point\"}, \"type\": \"Feature\", \"properties\": {\"city\": \"Aubagne\", \"label\": \"Route Nationale 8 13400 Aubagne\", \"id\": \"13005_XXXX_b0c6c8\", \"postcode\": \"13400\", \"name\": \"Route Nationale 8\", \"citycode\": \"13005\", \"context\": \"13, Bouches-du-Rh\\u00f4ne, Provence-Alpes-C\\u00f4te d\'Azur\", \"score\": 0.6540636363636363, \"type\": \"street\"}}, {\"geometry\": {\"coordinates\": [5.864773, 43.132774], \"type\": \"Point\"}, \"type\": \"Feature\", \"properties\": {\"city\": \"Ollioules\", \"label\": \"Route Nationale 8 83190 Ollioules\", \"id\": \"83090_XXXX_a33650\", \"postcode\": \"83190\", \"name\": \"Route Nationale 8\", \"citycode\": \"83090\", \"context\": \"83, Var, Provence-Alpes-C\\u00f4te d\'Azur\", \"score\": 0.6526818181818181, \"type\": \"street\"}}, {\"geometry\": {\"coordinates\": [45.136426, -12.845884], \"type\": \"Point\"}, \"type\": \"Feature\", \"properties\": {\"city\": \"Ouangani\", \"label\": \"Route D\\u00e9partementale 8 97670 Ouangani\", \"id\": \"97614_XXXX_704587\", \"postcode\": \"97670\", \"name\": \"Route D\\u00e9partementale 8\", \"citycode\": \"97614\", \"context\": \"976, Mayotte\", \"score\": 0.6507545454545454, \"type\": \"street\"}}, {\"geometry\": {\"coordinates\": [5.86687, 43.132284], \"type\": \"Point\"}, \"type\": \"Feature\", \"properties\": {\"city\": \"Ollioules\", \"label\": \"Route Nationale 8 83190 Ollioules\", \"id\": \"83090_XXXX_9346fc\", \"postcode\": \"83190\", \"name\": \"Route Nationale 8\", \"citycode\": \"83090\", \"context\": \"83, Var, Provence-Alpes-C\\u00f4te d\'Azur\", \"score\": 0.6481181818181817, \"type\": \"street\"}}, {\"geometry\": {\"coordinates\": [3.242916, 43.379135], \"type\": \"Point\"}, \"type\": \"Feature\", \"properties\": {\"city\": \"B\\u00e9ziers\", \"label\": \"Chemin Rural 8 34500 B\\u00e9ziers\", \"id\": \"34032_XXXX_ddb1db\", \"postcode\": \"34500\", \"name\": \"Chemin Rural 8\", \"citycode\": \"34032\", \"context\": \"34, H\\u00e9rault, Languedoc-Roussillon\", \"score\": 0.6467545454545454, \"type\": \"locality\"}}], \"type\": \"FeatureCollection\", \"attribution\": \"BAN\"}'; JSON2Apex obj = parse(json); System.assert(obj != null); } } ``` Mockup test class: ``` @isTest global class Rfleet_MockHttpResponseGenerator_Test implements HttpCalloutMock { global HTTPResponse respond(HTTPRequest req) { // Optionally, only send a mock response for a specific endpoint // and method. System.assertEquals('http://api-adresse.data.gouv.fr/search/?q='+'france', req.getEndpoint()); System.assertEquals('GET', req.getMethod()); // Create a fake response HttpResponse res = new HttpResponse(); res.setHeader('Content-Type', 'application/json'); res.setBody('{"foo":"bar"}'); res.setStatusCode(200); return res; } } ``` My test class : ``` @isTest public class Rfleet_Searchaddress_test { @isTest static void Testsearchaddress() { Account testAccount = new Account(Name='chinna',Montant__c=5); insert testAccount; testAccount.BillingStreet='chengalpattu'; update testAccount; Account myTestTrainee = [SELECT id From Account LIMIT 1]; PageReference myVfPage = Page.RFLEET_Searchaddress; system.test.setCurrentPage(myVfPage); ApexPages.currentPage().getParameters().put('id', myTestTrainee.id);//Pass Id to page ApexPAges.StandardController sc = new ApexPages.StandardController(myTestTrainee); Rfleet_Searchaddress apextestclass=new Rfleet_Searchaddress(sc); apextestclass.autosave(); String param ='Base Product'; RestRequest req = new RestRequest(); RestResponse res = new RestResponse(); req.requestURI = 'http://api-adresse.data.gouv.fr/search/?q='; req.httpMethod = 'GET'; RestContext.request = req; RestContext.response = res; Rfleet_Searchaddress.restapi('jso'); Test.startTest(); Test.setMock(HttpCalloutMock.class, new Rfleet_MockHttpResponseGenerator()); Test.stopTest(); } } The uncovered lines are: ``` [![enter image description here](https://i.stack.imgur.com/Qy7di.png)](https://i.stack.imgur.com/Qy7di.png)
2015/12/21
[ "https://salesforce.stackexchange.com/questions/103064", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/25911/" ]
* Apex Code has built in functionality to call external Web services, such as Amazon Web Services, Facebook, Google, or any publicly available web service. You will also need to have the proper test method code coverage for the related Apex code that makes these callouts. * But since the Force.com platform has no control over the external Web service and the impact of making the web service call, test methods can not invoke a 3rd party web service. * With Winter 13, you can now use mock tests with a response that is either hard-coded or reading static resource, > > global class YourHttpCalloutMockImpl implements HttpCalloutMock { > > > > * The class that implements the HttpCalloutMock interface can be either global or public. * You can annotate this class with @isTest since it will be used only in test context. * In this way, you can exclude it from your organization’s code size limit of 3 MB. * Now that you have specified the values of the fake response, instruct the Apex runtime to send this fake response by calling Test.setMock * in your test method. For the first argument, pass HttpCalloutMock.class, and for the second argument, pass a new instance of your interface implementation of HttpCalloutMock, as follows: > > Test.setMock(HttpCalloutMock.class, new YourHttpCalloutMockImpl()); > > > * After this point, if an HTTP callout is invoked in test context, the callout is not made and you receive the mock response you specified in the respond method implementation. * This is a full example that shows how to test an HTTP callout. > > ### /\* Apex class making a callout \*/ > > > public class CalloutClass { > > public static HttpResponse getInfoFromExternalService() { > > HttpRequest req = new HttpRequest(); > > req.setEndpoint('<http://api.salesforce.com/endpoint>'); > > req.setMethod('GET'); > > Http h = new Http(); > > HttpResponse res = h.send(req); > > return res; > > } > > } > > > > ### /\* MockResponse class implementing the HttpCalloutMock interface \*/ > > > @isTest > > global class MockHttpResponseGenerator implements HttpCalloutMock { > > // Implement this interface method > > global HTTPResponse respond(HTTPRequest req) { > > // Optionally, only send a mock response for a specific endpoint > > // and method. > > System.assertEquals('<http://api.salesforce.com/endpoint>', req.getEndpoint()); > > System.assertEquals('GET', req.getMethod()); > > // Create a fake response > > HttpResponse res = new HttpResponse(); > > res.setHeader('Content-Type', 'application/json'); > > res.setBody('{"foo":"bar"}'); > > res.setStatusCode(200); > > return res; > > } > > } > > > > ### /\* Test Class getting fake response from the class MockHttpResponseGenerator that implements HttpCalloutMock \*/ > > > @isTest > > private class CalloutClassTest { > > @isTest static void testCallout() { > > // Set mock callout class > > Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator()); > > // Call method to test. > > // This causes a fake response to be sent from the class that implements HttpCalloutMock. > > HttpResponse res = CalloutClass.getInfoFromExternalService(); > > // Verify response received contains fake values > > String contentType = res.getHeader('Content-Type'); > > System.assert(contentType == 'application/json'); > > String actualResponseBody = res.getBody(); > > String expectedResponseBody = '{"foo":"bar"}'; > > System.assertEquals(actualResponseBody, expectedResponseBody); > > System.assertEquals(200, res.getStatusCode()); > > } > > } > > > >
Remove HttpMockCallout code from test method and check to see if you are in test mode and instantiate the Mock before the actual callout in the method being tested: req.setMethod('GET'); if (Test.isRunningTest()) { Test.setMock(HttpCalloutMock.class, new Rfleet\_MockHttpResponseGenerator()); } HttpResponse res = h.send(req);
5,391,945
I was modifying files renaming them and switching them around (I was testing alternative homepages). Now I get a status message that says 'File has been replaced' and an R. I'm not sure what to do to solve this. I'm using Coda, and it does not solve it. So i guess it's command line time. The version that I care about is my local version, and I want to overwrite the remote version. i'm the only person working on it so a brute force approach is fine.
2011/03/22
[ "https://Stackoverflow.com/questions/5391945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/545822/" ]
1. Copy the file and put it in a temp location 2. Run "svn revert " 3. Now copy it back to the same location 4. Run "svn st " to check status
I used a similar procedure to that explained by Version Control Buddy to correct this issue in RAD with Subversive SVN Connector (Eclipse may be similar): 1. List item 2. Copy the file(s) to a temp location outside of RAD 3. Revert the file(s) in RAD using Right-click > Team > Revert 4. Outside of RAD, copy the saved back to the location 5. Refresh the folder in RAD, and the correct status will show. Note that I find if I just directly check in a file that is showing as Replace, the history of the original file is not easily view-able, so it may be worth these steps to preserve the history, especially on a multi-user project.
567,160
I have VirtualBox on Ubuntu 14.10 and some programs don't work on Wine, so I wanted to use a Windows XP SP3 ISO (for basic programs) and it gives me the error "FATAL: No bootable medium found! System halted." These are my settings for Storage: ![enter image description here](https://i.stack.imgur.com/KRufS.png) And here are my settings for system: ![enter image description here](https://i.stack.imgur.com/83TU6.png) How do I fix this?
2014/12/30
[ "https://askubuntu.com/questions/567160", "https://askubuntu.com", "https://askubuntu.com/users/309517/" ]
Seems like you have not a hard-drive... you can add one on Settings like here on my image (I have it in Catalan language, sorry) ![How to add a hard-drive](https://i.stack.imgur.com/erdBt.png) If you have already one, just add a CD (at the left from add hard-drive button) and run VirtualBox machine again. **Edited:** Well, seeing your images, the only thing what I can think is when you run the virtual machine, press `F2` to enter on boot menu, select the CD, key `C` and start the Windows XP installation, you should be able to install it. PS: Be sure to make on general tab a type of machine Windows XP (32 bit).
I just had the same issue, but for me i needed to re-order my SATA optical drives with the windows iso as port 1, and the physical cd/dvd as port 2. then it worked!
13,137,967
I want to update a field in table1 with another field in table2.I wrote the following query but it is not working. ``` UPDATE tempdata A SET A.new_user_id = (SELECT B.id FROM user B WHERE A.usr_email = B.usr_email) ``` It is giving "#1242 - Subquery returns more than 1 row" error. Anybody please help me.
2012/10/30
[ "https://Stackoverflow.com/questions/13137967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/966881/" ]
``` UPDATE tempdata A, user B SET A.new_user_id = B.id WHERE A.usr_email = B.usr_email ```
This is also one way to handle this scenerio ``` UPDATE A SET A.new_user_id = B.id FROM tempdata A INNER JOIN user B ON A.usr_email = B.usr_email ```
17,931,755
I have the problem of connecting with mysql on my debian server. I run `mysql -u root` and get the error message: ``` ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (111) Check that mysqld is running and that the socket: '/var/run/mysqld/mysqld.sock' exists! ``` So I did and I ran the command `sudo find / -type s` and got ``` /run/proftpd.sock /run/mysqld/mysqld.sock ``` Not `/var/run/mysqld/mysqld.sock`! Im simply trying to set up a database server to test it. What should I do?
2013/07/29
[ "https://Stackoverflow.com/questions/17931755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/931738/" ]
This question would be better asked on [serverfault.com](http://serverfault.com). However, the easiest way to do this (without confusing other Debian apps) would be to create (as root) a symbolic link to the sock file: ``` # ln -s /run/mysqld/mysqld.sock /var/run/mysqld/mysqld.sock ```
Connect with `mysql -u root -S /run/mysqld/mysqld.sock`, this should work.
2,283,937
As I continue to build more and more websites and web applications I am often asked to store user's passwords in a way that they can be retrieved if/when the user has an issue (either to email a forgotten password link, walk them through over the phone, etc.) When I can I fight bitterly against this practice and I do a lot of ‘extra’ programming to make password resets and administrative assistance possible without storing their actual password. When I can’t fight it (or can’t win) then I always encode the password in some way so that it, at least, isn’t stored as plaintext in the database—though I am aware that if my DB gets hacked it wouldn't take much for the culprit to crack the passwords, so that makes me uncomfortable. In a perfect world folks would update passwords frequently and not duplicate them across many different sites—unfortunately I know MANY people that have the same work/home/email/bank password, and have even freely given it to me when they need assistance. I don’t want to be the one responsible for their financial demise if my DB security procedures fail for some reason. Morally and ethically I feel responsible for protecting what can be, for some users, their livelihood even if they are treating it with much less respect. I am certain that there are many avenues to approach and arguments to be made for salting hashes and different encoding options, but is there a single ‘best practice’ when you have to store them? In almost all cases I am using PHP and MySQL if that makes any difference in the way I should handle the specifics. **Additional Information for Bounty** I want to clarify that I know this is not something you want to have to do and that in most cases refusal to do so is best. I am, however, not looking for a lecture on the merits of taking this approach I am looking for the best steps to take if you do take this approach. In a note below I made the point that websites geared largely toward the elderly, mentally challenged, or very young can become confusing for people when they are asked to perform a secure password recovery routine. Though we may find it simple and mundane in those cases some users need the extra assistance of either having a service tech help them into the system or having it emailed/displayed directly to them. In such systems the attrition rate from these demographics could hobble the application if users were not given this level of access assistance, so please answer with such a setup in mind. **Thanks to Everyone** This has been a fun question with lots of debate and I have enjoyed it. In the end I selected an answer that both retains password security (I will not have to keep plain text or recoverable passwords), but also makes it possible for the user base I specified to log into a system without the major drawbacks I have found from normal password recovery. As always there were about 5 answers that I would like to have marked as correct for different reasons, but I had to choose the best one--all the rest got a +1. Thanks everyone! Also, thanks to everyone in the Stack community who voted for this question and/or marked it as a favorite. I take hitting 100 up votes as a compliment and hope that this discussion has helped someone else with the same concern that I had.
2010/02/17
[ "https://Stackoverflow.com/questions/2283937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258497/" ]
Pursuant to the comment I made on the question: One important point has been very glossed over by nearly everyone... My initial reaction was very similar to @Michael Brooks, till I realized, like @stefanw, that the issue here is broken requirements, but these are what they are. But then, it occured to me that that might not even be the case! The missing point here, is the unspoken *value* of the application's assets. Simply speaking, for a low value system, a fully secure authentication mechanism, with all the process involved, would be overkill, and the **wrong** security choice. Obviously, for a bank, the "best practices" are a must, and there is no way to ethically violate CWE-257. But it's easy to think of low value systems where it's just not worth it (but a simple password is still required). **It's important to remember, true security expertise is in finding appropriate tradeoffs, NOT in dogmatically spouting the "Best Practices" that anyone can read online.** As such, I suggest another solution: Depending on the value of the system, and **ONLY IF** the system is appropriately low-value with no "expensive" asset (the identity itself, included), **AND** there are valid business requirements that make proper process impossible (or sufficiently difficult/expensive), **AND** the client is made aware of all the caveats... Then it could be appropriate to simply allow reversible encryption, with no special hoops to jump through. I am stopping just short of saying not to bother with encryption at all, because it is very simple/cheap to implement (even considering passible key management), and it DOES provide SOME protection (more than the cost of implementing it). Also, its worth looking at how to provide the user with the original password, whether via email, displaying on the screen, etc. Since the assumption here is that the value of the stolen password (even in aggregate) is quite low, any of these solutions can be valid. --- Since there is a lively discussion going on, actually SEVERAL lively discussions, in the different posts and seperate comment threads, I will add some clarifications, and respond to some of the very good points that have been raised elsewhere here. To start, I think it's clear to everyone here that allowing the user's original password to be retrieved, is Bad Practice, and generally Not A Good Idea. That is not at all under dispute... Further, I will emphasize that in many, nay MOST, situations - it's really wrong, even [foul, nasty, AND ugly](http://www.fthe.net/blog/?p=28). However, the crux of the question is around *the principle*, **IS there any situation where it might not be necessary** to forbid this, and if so, how to do so in the **most correct manner appropriate to the situation**. Now, as @Thomas, @sfussenegger and few others mentioned, the only proper way to answer that question, is to do a thorough *risk analysis* of any given (or hypothetical) situation, to understand what's at stake, how much it's worth to protect, and what other mitigations are in play to afford that protection. No, it is NOT a buzzword, this is one of the basic, most important tools for a real-live security professional. Best practices are good up to a point (usually as guidelines for the inexperienced and the hacks), after that point thoughtful risk analysis takes over. Y'know, it's funny - I always considered myself one of the security fanatics, and somehow I'm on the opposite side of those so-called "Security Experts"... Well, truth is - because I'm a fanatic, and an actual real-life security expert - I do not believe in spouting "Best Practice" dogma (or CWEs) WITHOUT that all-important *risk analysis*. "Beware the security zealot who is quick to apply everything in their tool belt without knowing what the actual issue is they are defending against. More security doesn’t necessarily equate to good security." Risk analysis, and true security fanatics, would point to a smarter, value/risk -based tradeoff, based on risk, potential loss, possible threats, complementary mitigations, etc. Any "Security Expert" that cannot point to sound risk analysis as the basis for their recommendations, or support logical tradeoffs, but would instead prefer to spout dogma and CWEs without even understanding how to perform a risk analysis, are naught but Security Hacks, and their Expertise is not worth the toilet paper they printed it on. Indeed, that is how we get the ridiculousness that is Airport Security. But before we talk about the appropriate tradeoffs to make in THIS SITUATION, let's take a look at the apparent risks (apparent, because we don't have all the background information on this situation, we are all hypothesizing - since the question is what hypothetical situation might there be...) Let's assume a LOW-VALUE system, yet not so trival that it's public access - the system owner wants to prevent casual impersonation, yet "high" security is not as paramount as ease of use. (Yes, it is a legitimate tradeoff to ACCEPT the risk that any proficient script-kiddie can hack the site... Wait, isn't APT in vogue now...?) Just for example, let's say I'm arranging a simple site for a large family gathering, allowing everyone to brainstorm on where we want to go on our camping trip this year. I'm less worried about some anonymous hacker, or even Cousin Fred squeezing in repeated suggestions to go back to Lake Wantanamanabikiliki, as I am about Aunt Erma not being able to logon when she needs to. Now, Aunt Erma, being a nuclear physicist, isn't very good at remembering passwords, or even with using computers at all... So I want to remove all friction possible for her. Again, I'm NOT worried about hacks, I just dont want silly mistakes of wrong login - I want to know who is coming, and what they want. Anyway. So what are our main risks here, if we symmetrically encrypt passwords, instead of using a one-way hash? * Impersonating users? No, I've already accepted that risk, not interesting. * Evil administrator? Well, maybe... But again, I dont care if someone can impersonate another user, INTERNAL or no... and anyway a malicious admin is gonna get your password **no matter what** - if your admin's gone bad, its game over anyway. * Another issue that's been raised, is the identity is actually shared between several systems. Ah! This is a very interesting risk, that requires a closer look. Let me start by asserting that it's not the actual *identity* thats shared, rather the *proof*, or the authentication credential. Okay, since a shared password will effectively allow me entrance to another system (say, my bank account, or gmail), this is effectively the same identity, so it's just semantics... Except that *it's not*. Identity is managed seperately by each system, in this scenario (though there might be third party id systems, such as OAuth - still, its seperate from the identity in this system - more on this later). As such, the core point of risk here, is that the user will willingly input his (same) password into several different systems - and now, I (the admin) or any other hacker of my site will have access to Aunt Erma's passwords for the nuclear missile site. Hmmm. Does anything here seem off to you? It should. Let's start with the fact that protecting the nuclear missiles system is **not my responsibility**, I'm just building a frakkin family outing site (for MY family). So whose responsibility IS it? Umm... How about the nuclear missiles system? Duh. Second, If I wanted to steal someone's password (someone who is known to repeatedly use the same password between secure sites, and not-so-secure ones) - why would I bother hacking your site? Or struggling with your symmetric encryption? Goshdarnitall, I can just put up [my own simple website](http://xkcd.com/792/), have users sign up to receive VERY IMPORTANT NEWS about whatever they want... Puffo Presto, I "stole" their passwords. Yes, user education always does come back to bite us in the hienie, doesn't it? And there's nothing you can do about that... Even if you WERE to hash their passwords on your site, and do everything else the TSA can think of, you added protection to their password *NOT ONE WHIT*, if they're going to keep promiscuously sticking their passwords into every site they bump into. Don't EVEN bother trying. Put another way, ***You don't own their passwords***, so stop trying to act like you do. So, my Dear Security Experts, as an old lady used to ask for Wendy's, "WHERE's the risk?" Another few points, in answer to some issues raised above: * CWE is not a law, or regulation, or even a standard. It is a collection of *common weaknesses*, i.e. the inverse of "Best Practices". * The issue of shared identity is an actual problem, but misunderstood (or misrepresented) by the naysayers here. It is an issue of sharing the identity in and of itself(!), NOT about cracking the passwords on low-value systems. If you're sharing a password between a low-value and a high-value system, the problem is already there! * By the by, the previous point would actually point **AGAINST** using OAuth and the like for both these low-value systems, and the high-value banking systems. * I know it was just an example, but (sadly) the FBI systems are not really the most secured around. Not quite like your cat's blog's servers, but nor do they surpass some of the more secure banks. * Split knowledge, or dual control, of encryption keys do NOT happen just in the military, in fact PCI-DSS now **requires** this from basically all merchants, so its not really so far out there anymore (IF the value justifies it). * To all those who are complaining that questions like these are what makes the developer profession look so bad: it is answers like those, that make the security profession look even worse. Again, business-focused risk analysis is what is required, otherwise you make yourself useless. In addition to being wrong. * I guess this is why it's not a good idea to just take a regular developer and drop more security responsibilities on him, without training to think differently, and to look for the correct tradeoffs. No offense, to those of you here, I'm all for it - but more training is in order. Whew. What a long post... But to answer your original question, @Shane: * Explain to the customer the proper way to do things. * If he still insists, explain some more, insist, argue. Throw a tantrum, if needed. * Explain the BUSINESS RISK to him. Details are good, figures are better, a live demo is usually best. * IF HE STILL insists, AND presents valid business reasons - it's time for you to do a judgement call: Is this site low-to-no-value? Is it really a valid business case? Is it good enough for you? Are there no other risks you can consider, that would outweigh valid business reasons? (And of course, is the client NOT a malicious site, but thats duh). If so, just go right ahead. It's not worth the effort, friction, and lost usage (in this hypothetical situation) to put the necessary process in place. Any other decision (again, in this situation) is a bad tradeoff. So, bottom line, and an actual answer - encrypt it with a simple symmetrical algorithm, protect the encryption key with strong ACLs and preferably DPAPI or the like, document it and have the client (someone senior enough to make that decision) sign off on it.
Securing credentials is not a binary operation: secure/not secure. Security is all about risk assessment and is measured on a continuum. Security fanatics hate to think this way, but the ugly truth is that nothing is perfectly secure. Hashed passwords with stringent password requirements, DNA samples, and retina scans are more secure but at a cost of development and user experience. Plaintext passwords are far less secure but are cheaper to implement (but should be avoided). At end of the day, it comes down to a cost/benefit analysis of a breach. You implement security based on the value of the data being secured and its time-value. What is the cost of someone's password getting out into the wild? What is the cost of impersonation in the given system? To the FBI computers, the cost could be enormous. To Bob's one-off five-page website, the cost could be negligible. A professional provides options to their customers and, when it comes to security, lays out the advantages and risks of any implementation. This is doubly so if the client requests something that could put them at risk because of failing to heed industry standards. If a client specifically requests two-way encryption, I would ensure you document your objections but that should not stop you from implementing in the best way you know. At the end of the day, it is the client's money. Yes, you should push for using one-way hashes but to say that is absolutely the only choice and anything else is unethical is utter nonsense. If you are storing passwords with two-way encryption, security all comes down to key management. Windows provides mechanisms to restrict access to certificates private keys to administrative accounts and with passwords. If you are hosting on other platform's, you would need to see what options you have available on those. As others have suggested, you can use asymmetric encryption. There is no law (neither the Data Protection Act in the UK) of which I'm aware that states specifically that passwords must be stored using one-way hashes. The only requirement in any of these laws is simply that ***reasonable*** steps are taken for security. If access to the database is restricted, even plaintext passwords can qualify legally under such a restriction. However, this does bring to light one more aspect: legal precedence. If legal precedence suggests that you must use one-way hashes given the industry in which your system is being built, then that is entirely different. That is the ammunition you use to convince your customer. Barring that, the best suggestion to provide a reasonable risk assessment, document your objections and implement the system in the most secure way you can given customer's requirements.
3,898,301
When I boot up Linux Mint from a Live CD, I am able to save files to the "File System". But where are these files being saved to? Can't be the disc, since it's a CDR. I don't think it's stored in the RAM, because it can only hold so much data and isn't really intended to be used as a "hard drive". The only other option is the hard drive... but it's certainly not saving to any partition on the hard drive I know about, since none of them are mounted. Then where are my files being saved to??
2010/10/09
[ "https://Stackoverflow.com/questions/3898301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/403736/" ]
RAM. In Linux, and indeed most unix systems, any kind of device is seen as a file system. For example, to get memory info on linux you use `cat /proc/meminfo`, where `cat` is used to read files. Then, there's all sorts of strange stuff like `/dev/random` (to read random crap) and `/dev/null` (to throw away crap). ;-)
To make it persistent - use a USB device - properly formatted and with a special name. See here: <https://help.ubuntu.com/community/LiveCD/Persistence>
47,354,226
I am using Boost::Spirit to build simple "data-filter" language in my C++ GUI application for non-technical users. Language is very similiar to plain English and parse-able into AST. I am requested to make the process as user-friendly as possible, so I wish to provide CLang-like error messages ("Unrecognized 'tokken', did you meant 'token'?") and autocompletion. The question in place is how to use Boost::Spirit grammar to generate possible token list for both goals (I will use simple string distance algorithm to satisfy first requirement)? My ideas so far: * Add position and length in source stream to token definition obtained from parser. * Add special invalid token to grammar, which will match anything... well... not valid :-) * If user presses ctrl + space, build AST (with invalid token the tree will be always buildable), then look for token inside current cursor position * Use simple matcher on all possible tokens (I have token list after all) and prepare a list of suggestions The problem with this solution is the suggestion will also suggest tokens that are invalid for given place. And if I add (and I will) definable identifiers, I have much bigger problem in hand... One more constraint: I want to have grammar for this language defined in only one place; If the grammar changes, I want to autocompleter be aware of this changes after recompilation
2017/11/17
[ "https://Stackoverflow.com/questions/47354226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151150/" ]
Out of curiosity, I decided to try the concept. Here's my attempt. Plan ---- Let's parse arithmetic expressions with function calls. Now, we want to parse (partial) expression with possible unknown identifiers. In case of incomplete expressions, we want to "imply" the minimal token to complete it (and potentially continue parsing). In case of unknown identifiers, we want to fuzzy-match the known identifiers in the domain (either variables or functions) and rank them in order of decreasing probability. --- Base Definitions ---------------- Let's start out by deciding we want our input to be in memory, so we can refer to locations/substrings by using `string_view`s: ``` #include <boost/utility/string_view.hpp> using Source = boost::string_view; using Location = Source::const_iterator; ``` Completion Hints ---------------- Besides the AST, we want our parser to generate completion hints (the implicit completion tokens and suggestions) ``` namespace Completion { using Candidates = std::vector<std::string>; class Hints { struct ByLocation { template <typename T, typename U> bool operator()(T const& a, U const& b) const { return loc(a) < loc(b); } private: static Location loc(Source const& s) { return s.begin(); } static Location loc(Location const& l) { return l; } }; public: std::map<Location, std::string, ByLocation> incomplete; std::map<Source, Candidates, ByLocation> suggestions; /*explicit*/ operator bool() const { return incomplete.size() || suggestions.size(); } }; ``` In addition, let's code up a quick & dirty fuzzy identifier match scoring function. I opted for a simple synchronizing compare that * scores corresponding runs of characters progressively, and * favours skipping characters from candidates over skipping characters from the input (meaning that `adj_diff` is a good fuzzy match for `adjacent_difference` even though characters have been skipped from the candidate, but `adj_qqq_diff` is worse because the `qqq` from the input could not be matched) * the algorithm is done recursively and without allocations * first characters get a boost if matched (`rate=1` at first invocation) ``` static int fuzzy_match(Source input, boost::string_view candidate, int rate = 1) { // start with first-letter boost int score = 0; while (!(input.empty() || candidate.empty())) { if (input.front() != candidate.front()) { return score + std::max( fuzzy_match(input.substr(1), candidate, std::max(rate-2,0)), //penalty for ignoring an input char fuzzy_match(input, candidate.substr(1), std::max(rate-1,0))); } input.remove_prefix(1); candidate.remove_prefix(1); score += ++rate; } return score; } } // namespace Completion ``` We'll see how this is used in the grammar. AST --- A run-of-the-mill AST that can do binary expressions, string/numeric literals, variables and (nested) function calls: ``` #include <boost/variant.hpp> namespace Ast { using NumLiteral = double; using StringLiteral = std::string; // de-escaped, not source view struct Identifier : std::string { using std::string::string; using std::string::operator=; }; struct BinaryExpression; struct CallExpression; using Expression = boost::variant< NumLiteral, StringLiteral, Identifier, boost::recursive_wrapper<BinaryExpression>, boost::recursive_wrapper<CallExpression> >; struct BinaryExpression { Expression lhs; char op; Expression rhs; }; using ArgList = std::vector<Expression>; struct CallExpression { Identifier function; ArgList args; }; } ``` Grammar ------- --- ### Basics The grammar starts off pretty "basic" as well: ``` namespace Parsing { namespace qi = boost::spirit::qi; namespace phx = boost::phoenix; template <typename It> struct Expression : qi::grammar<It, Ast::Expression()> { Expression(Completion::Hints& hints) : Expression::base_type(start), _hints(hints) { using namespace qi; start = skip(space) [expression]; expression = term [_val = _1] >> *(char_("-+") >> expression) [_val = make_binary(_val, _1, _2)]; term = factor [_val = _1] >> *(char_("*/") >> term) [_val = make_binary(_val, _1, _2)]; factor = simple [_val = _1] >> *(char_("^") >> factor) [_val = make_binary(_val, _1, _2)]; simple = call | variable | compound | number | string; ``` So far so good: The constructor stores a reference to the `Completion::Hints&` to be recorded. All these rules have been declared as `qi::rule<It, Expression(), qi::space_type>`. ### Implied Tokens Now it gets slightly more interesting, some rules here are lexemes¹ ``` number = double_; identifier = raw[(alpha|'_') >> *(alnum|'_')]; ``` And some productions are tolerant of missing closing tokens: ``` // imply the closing quotes string %= '"' >> *('\\' >> char_ | ~char_('"')) >> implied('"'); compound %= '(' >> expression >> implied(')'); ``` The `implied` magic makes it so that if the expected closing token is missing, it will be recorded as a hint, and parsing continues: ``` auto implied = [=](char ch) { return copy(omit[lit(ch) | raw[eps][imply(_1, ch)]]); }; ``` Of course, this begs the question what `imply(_1, ch)` really does, and we'll see later. > > For now, observe that we do `raw[eps]` to get an (empty) source `iterator_range` to construct a `Location` from in the semantic action. > > > ### Identifier Lookup We store "symbol tables" in `Domain` members `_variables` and `_functions`: ``` using Domain = qi::symbols<char>; Domain _variables, _functions; ``` Then we declare some rules that can do lookups on either of them: ``` // domain identifier lookups qi::_r1_type _domain; qi::rule<It, Ast::Identifier(Domain const&)> maybe_known, known, unknown; ``` The corresponding declarations will be shown shortly. Variables are pretty simple: ``` variable = maybe_known(phx::ref(_variables)); ``` Calls are trickier. If a name is unknown we don't want to assume it implies a *function* unless it's followed by a `'('` character. However, if an identifier is a known function name, we want even to imply the `(` (this gives the UX the appearance of autocompletion where when the user types `sqrt`, it suggests the next character to be `(` magically). ``` // The heuristics: // - an unknown identifier followed by ( // - an unclosed argument list implies ) call %= ( known(phx::ref(_functions)) // known -> imply the parens | &(identifier >> '(') >> unknown(phx::ref(_functions)) ) >> implied('(') >> -(expression % ',') >> implied(')'); ``` It all builds on `known`, `unknown` and `maybe_known`: ``` /////////////////////////////// // identifier loopkup, suggesting { maybe_known = known(_domain) | unknown(_domain); // distinct to avoid partially-matching identifiers using boost::spirit::repository::qi::distinct; auto kw = distinct(copy(alnum | '_')); known = raw[kw[lazy(_domain)]]; unknown = raw[identifier[_val=_1]] [suggest_for(_1, _domain)]; } ``` ### Debug, Predefined Variables/Functions Remaining is a bit of red tape: ``` BOOST_SPIRIT_DEBUG_NODES( (start) (expression)(term)(factor)(simple)(compound) (call)(variable) (identifier)(number)(string) //(maybe_known)(known)(unknown) // qi::symbols<> non-streamable ) _variables += "foo", "bar", "qux"; _functions += "print", "sin", "tan", "sqrt", "frobnicate"; } private: Completion::Hints& _hints; using Domain = qi::symbols<char>; Domain _variables, _functions; qi::rule<It, Ast::Expression()> start; qi::rule<It, Ast::Expression(), qi::space_type> expression, term, factor, simple; // completables qi::rule<It, Ast::Expression(), qi::space_type> compound; qi::rule<It, Ast::CallExpression(), qi::space_type> call; // implicit lexemes qi::rule<It, Ast::Identifier()> variable, identifier; qi::rule<It, Ast::NumLiteral()> number; qi::rule<It, Ast::StringLiteral()> string; // domain identifier lookups qi::_r1_type _domain; qi::rule<It, Ast::Identifier(Domain const&)> maybe_known, known, unknown; ``` ### Phoenix Helpers Let's start with the usual helper to construct binary AST nodes: ``` /////////////////////////////// // binary expression factory struct make_binary_f { Ast::BinaryExpression operator()(Ast::Expression const& lhs, char op, Ast::Expression const& rhs) const { return {lhs, op, rhs}; } }; boost::phoenix::function<make_binary_f> make_binary; ``` Similarly, we can have a Phoenix function object to register implied chars: ``` /////////////////////////////// // auto-completing incomplete expressions struct imply_f { Completion::Hints& _hints; void operator()(boost::iterator_range<It> where, char implied_char) const { auto inserted = _hints.incomplete.emplace(&*where.begin(), std::string(1, implied_char)); // add the implied char to existing completion if (!inserted.second) inserted.first->second += implied_char; } }; boost::phoenix::function<imply_f> imply { imply_f { _hints } }; ``` Note that it orders by location (which makes UX easier) and detects when a previous implied token lived at the same location, in which case we simply append to it. By now it won't be much of a surprise that generating relevant suggestions for unknown identifiers is also a phoenix actor: ``` /////////////////////////////// // suggest_for struct suggester { Completion::Hints& _hints; void operator()(boost::iterator_range<It> where, Domain const& symbols) const { using namespace Completion; Source id(&*where.begin(), where.size()); Candidates c; symbols.for_each([&](std::string const& k, ...) { c.push_back(k); }); auto score = [id](Source v) { return fuzzy_match(id, v); }; auto byscore = [=](Source a, Source b) { return score(a) > score(b); }; sort(c.begin(), c.end(), byscore); c.erase( remove_if(c.begin(), c.end(), [=](Source s) { return score(s) < 3; }), c.end()); _hints.suggestions.emplace(id, c); } }; boost::phoenix::function<suggester> suggest_for {suggester{_hints}}; ``` That's all. If it looks more complicated, that's because it does a lot more: it scores all candidates fuzzily, orders them by descending score and removes any candidates with score < 3. ``` }; } ``` BONUS ----- Let's alter things a little more and allow `','` to be implied inside argument lists: ``` call %= ( known(phx::ref(_functions)) // known -> imply the parens | &(identifier >> '(') >> unknown(phx::ref(_functions)) ) >> implied('(') >> -(expression % ',') >> implied(')') ; ``` Let's replace `','` there: ``` >> -(expression % (',' | !(')'|eoi) >> implied(','))) ``` > > **NOTE**: It might seem to make more sense to detect `&expression` to assert that an expression follows, instead asserting that the end of the input/argument list has not been reached. > > > Doing that goes bad, though, because any contained expressions could trigger more implied tokens as a side effect, leading to duplicated implied tokens. > > > This (side-effectful semantic actions) is one of the chief reasons why I usually avoid semantic actions, or use them to store effect only in the rule's (exposed) attribute(s). See [Boost Spirit: "Semantic actions are evil"?](https://stackoverflow.com/questions/8259440/boost-spirit-semantic-actions-are-evil) > > > TEST DRIVER =========== This post would be nothing without some nice test cases. So here goes: ``` int main() { for (Source const input : { "", // invalid "(3", // incomplete, imply ')' "3*(6+sqrt(9))^7 - 1e8", // completely valid "(3*(((6+sqrt(9))^7 - 1e8", // incomplete, imply ")))" "print(\"hello \\\"world!", // completes the string literal and the parameter list "foo", // okay, known variable "baz", // (suggest bar) "baz(", // incomplete, imply ')', unknown function "taz(", // incomplete, imply ')', unknown function "san(", // 2 suggestions (sin/tan) "print(1, 2, \"three\", complicated(san(78", "(print sqrt sin 9) -0) \"bye", }) { std::cout << "-------------- '" << input << "'\n"; Location f = input.begin(), l = input.end(); Ast::Expression expr; Completion::Hints hints; bool ok = parse(f, l, Parsing::Expression<Location>{hints}, expr); if (hints) { std::cout << "Input: '" << input << "'\n"; } for (auto& c : hints.incomplete) { std::cout << "Missing " << std::setw(c.first - input.begin()) << "" << "^ implied: '" << c.second << "'\n"; } for (auto& id : hints.suggestions) { std::cout << "Unknown " << std::setw(id.first.begin() - input.begin()) << "" << std::string(id.first.size(), '^'); if (id.second.empty()) std::cout << " (no suggestions)\n"; else { std::cout << " (did you mean "; once_t first; for (auto& s : id.second) std::cout << (first?"":" or ") << "'" << s << "'"; std::cout << "?)\n"; } } if (ok) { std::cout << "AST: " << expr << "\n"; } else { std::cout << "Parse failed\n"; } if (f!=l) std::cout << "Remaining input: '" << std::string(f,l) << "'\n"; } } ``` Note that, besides the first input (`""`) everything is heuristically parsed as *some* kind of expression! The last one is designed to show off how all the parameter lists are implied because `print`, `sqrt` and `sin` are known functions. Then some `','` are implied, before finally the unclosed string literal and remaining parentheses are closed. Here's the (non-debug) output: ``` -------------- '' Parse failed -------------- '(3' Input: '(3' Missing ^ implied: ')' AST: 3 -------------- '3*(6+sqrt(9))^7 - 1e8' AST: ((3 * ((6 + (sqrt (9))) ^ 7)) - 1e+08) -------------- '(3*(((6+sqrt(9))^7 - 1e8' Input: '(3*(((6+sqrt(9))^7 - 1e8' Missing ^ implied: ')))' AST: (3 * (((6 + (sqrt (9))) ^ 7) - 1e+08)) -------------- 'print("hello \"world!' Input: 'print("hello \"world!' Missing ^ implied: '")' AST: (print (hello "world!)) -------------- 'foo' AST: foo -------------- 'baz' Input: 'baz' Unknown ^^^ (did you mean 'bar'?) AST: baz -------------- 'baz(' Input: 'baz(' Missing ^ implied: ')' Unknown ^^^ (no suggestions) AST: (baz ()) -------------- 'taz(' Input: 'taz(' Missing ^ implied: ')' Unknown ^^^ (did you mean 'tan'?) AST: (taz ()) -------------- 'san(' Input: 'san(' Missing ^ implied: ')' Unknown ^^^ (did you mean 'sin' or 'tan'?) AST: (san ()) -------------- 'print(1, 2, "three", complicated(san(78' Input: 'print(1, 2, "three", complicated(san(78' Missing ^ implied: ')))' Unknown ^^^^^^^^^^^ (did you mean 'frobnicate' or 'print'?) Unknown ^^^ (did you mean 'sin' or 'tan'?) AST: (print (1, 2, three, (complicated ((san (78)))))) -------------- '(print sqrt sin 9) -0) "bye' Input: '(print sqrt sin 9) -0) "bye' Missing ^ implied: '(' Missing ^ implied: '(' Missing ^ implied: '(' Missing ^ implied: ',' Missing ^ implied: '"))' AST: (print ((sqrt (((sin (9)) - 0))), bye)) ``` Full Listing / Live Demo ======================== **`[Live On Coliru](http://coliru.stacked-crooked.com/a/c1b0c5c573e9ec78)`** ``` //#define BOOST_SPIRIT_DEBUG #include <boost/utility/string_view.hpp> using Source = boost::string_view; using Location = Source::const_iterator; #include <map> #include <vector> namespace Completion { static int fuzzy_match(Source input, boost::string_view candidate, int rate = 1) { // start with first-letter boost int score = 0; while (!(input.empty() || candidate.empty())) { if (input.front() != candidate.front()) { return score + std::max( fuzzy_match(input.substr(1), candidate, std::max(rate-2,0)), //penalty for ignoring an input char fuzzy_match(input, candidate.substr(1), std::max(rate-1,0))); } input.remove_prefix(1); candidate.remove_prefix(1); score += ++rate; } return score; } using Candidates = std::vector<std::string>; class Hints { struct ByLocation { template <typename T, typename U> bool operator()(T const& a, U const& b) const { return loc(a) < loc(b); } private: static Location loc(Source const& s) { return s.begin(); } static Location loc(Location const& l) { return l; } }; public: std::map<Location, std::string, ByLocation> incomplete; std::map<Source, Candidates, ByLocation> suggestions; /*explicit*/ operator bool() const { return incomplete.size() || suggestions.size(); } }; } #include <boost/variant.hpp> namespace Ast { using NumLiteral = double; using StringLiteral = std::string; // de-escaped, not source view struct Identifier : std::string { using std::string::string; using std::string::operator=; }; struct BinaryExpression; struct CallExpression; using Expression = boost::variant< NumLiteral, StringLiteral, Identifier, boost::recursive_wrapper<BinaryExpression>, boost::recursive_wrapper<CallExpression> >; struct BinaryExpression { Expression lhs; char op; Expression rhs; }; using ArgList = std::vector<Expression>; struct CallExpression { Identifier function; ArgList args; }; } #include <boost/fusion/adapted/struct.hpp> BOOST_FUSION_ADAPT_STRUCT(Ast::BinaryExpression, lhs, op, rhs) BOOST_FUSION_ADAPT_STRUCT(Ast::CallExpression, function, args) #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix.hpp> #include <boost/spirit/repository/include/qi_distinct.hpp> // for debug printing: namespace { struct once_t { // an auto-reset flag operator bool() { bool v = flag; flag = false; return v; } bool flag = true; }; } // for debug printing: namespace Ast { static inline std::ostream& operator<<(std::ostream& os, std::vector<Expression> const& args) { os << "("; once_t first; for (auto& a : args) os << (first?"":", ") << a; return os << ")"; } static inline std::ostream& operator<<(std::ostream& os, BinaryExpression const& e) { return os << boost::fusion::as_vector(e); } static inline std::ostream& operator<<(std::ostream& os, CallExpression const& e) { return os << boost::fusion::as_vector(e); } } namespace Parsing { namespace qi = boost::spirit::qi; namespace phx = boost::phoenix; template <typename It> struct Expression : qi::grammar<It, Ast::Expression()> { Expression(Completion::Hints& hints) : Expression::base_type(start), _hints(hints) { using namespace qi; start = skip(space) [expression]; expression = term [_val = _1] >> *(char_("-+") >> expression) [_val = make_binary(_val, _1, _2)]; term = factor [_val = _1] >> *(char_("*/") >> term) [_val = make_binary(_val, _1, _2)]; factor = simple [_val = _1] >> *(char_("^") >> factor) [_val = make_binary(_val, _1, _2)]; simple = call | variable | compound | number | string; auto implied = [=](char ch) { return copy(omit[lit(ch) | raw[eps][imply(_1, ch)]]); }; variable = maybe_known(phx::ref(_variables)); compound %= '(' >> expression >> implied(')'); // The heuristics: // - an unknown identifier followed by ( // - an unclosed argument list implies ) call %= ( known(phx::ref(_functions)) // known -> imply the parens | &(identifier >> '(') >> unknown(phx::ref(_functions)) ) >> implied('(') >> -(expression % (',' | !(')'|eoi) >> implied(','))) >> implied(')') ; // lexemes, primitive rules identifier = raw[(alpha|'_') >> *(alnum|'_')]; // imply the closing quotes string %= '"' >> *('\\' >> char_ | ~char_('"')) >> implied('"'); // TODO more escapes number = double_; // TODO integral arguments /////////////////////////////// // identifier loopkup, suggesting { maybe_known = known(_domain) | unknown(_domain); // distinct to avoid partially-matching identifiers using boost::spirit::repository::qi::distinct; auto kw = distinct(copy(alnum | '_')); known = raw[kw[lazy(_domain)]]; unknown = raw[identifier[_val=_1]] [suggest_for(_1, _domain)]; } BOOST_SPIRIT_DEBUG_NODES( (start) (expression)(term)(factor)(simple)(compound) (call)(variable) (identifier)(number)(string) //(maybe_known)(known)(unknown) // qi::symbols<> non-streamable ) _variables += "foo", "bar", "qux"; _functions += "print", "sin", "tan", "sqrt", "frobnicate"; } private: Completion::Hints& _hints; using Domain = qi::symbols<char>; Domain _variables, _functions; qi::rule<It, Ast::Expression()> start; qi::rule<It, Ast::Expression(), qi::space_type> expression, term, factor, simple; // completables qi::rule<It, Ast::Expression(), qi::space_type> compound; qi::rule<It, Ast::CallExpression(), qi::space_type> call; // implicit lexemes qi::rule<It, Ast::Identifier()> variable, identifier; qi::rule<It, Ast::NumLiteral()> number; qi::rule<It, Ast::StringLiteral()> string; // domain identifier lookups qi::_r1_type _domain; qi::rule<It, Ast::Identifier(Domain const&)> maybe_known, known, unknown; /////////////////////////////// // binary expression factory struct make_binary_f { Ast::BinaryExpression operator()(Ast::Expression const& lhs, char op, Ast::Expression const& rhs) const { return {lhs, op, rhs}; } }; boost::phoenix::function<make_binary_f> make_binary; /////////////////////////////// // auto-completing incomplete expressions struct imply_f { Completion::Hints& _hints; void operator()(boost::iterator_range<It> where, char implied_char) const { auto inserted = _hints.incomplete.emplace(&*where.begin(), std::string(1, implied_char)); // add the implied char to existing completion if (!inserted.second) inserted.first->second += implied_char; } }; boost::phoenix::function<imply_f> imply { imply_f { _hints } }; /////////////////////////////// // suggest_for struct suggester { Completion::Hints& _hints; void operator()(boost::iterator_range<It> where, Domain const& symbols) const { using namespace Completion; Source id(&*where.begin(), where.size()); Candidates c; symbols.for_each([&](std::string const& k, ...) { c.push_back(k); }); auto score = [id](Source v) { return fuzzy_match(id, v); }; auto byscore = [=](Source a, Source b) { return score(a) > score(b); }; sort(c.begin(), c.end(), byscore); c.erase( remove_if(c.begin(), c.end(), [=](Source s) { return score(s) < 3; }), c.end()); _hints.suggestions.emplace(id, c); } }; boost::phoenix::function<suggester> suggest_for {suggester{_hints}}; }; } #include <iostream> #include <iomanip> int main() { for (Source const input : { "", // invalid "(3", // incomplete, imply ')' "3*(6+sqrt(9))^7 - 1e8", // completely valid "(3*(((6+sqrt(9))^7 - 1e8", // incomplete, imply ")))" "print(\"hello \\\"world!", // completes the string literal and the parameter list "foo", // okay, known variable "baz", // (suggest bar) "baz(", // incomplete, imply ')', unknown function "taz(", // incomplete, imply ')', unknown function "san(", // 2 suggestions (sin/tan) "print(1, 2, \"three\", complicated(san(78", "(print sqrt sin 9) -0) \"bye", }) { std::cout << "-------------- '" << input << "'\n"; Location f = input.begin(), l = input.end(); Ast::Expression expr; Completion::Hints hints; bool ok = parse(f, l, Parsing::Expression<Location>{hints}, expr); if (hints) { std::cout << "Input: '" << input << "'\n"; } for (auto& c : hints.incomplete) { std::cout << "Missing " << std::setw(c.first - input.begin()) << "" << "^ implied: '" << c.second << "'\n"; } for (auto& id : hints.suggestions) { std::cout << "Unknown " << std::setw(id.first.begin() - input.begin()) << "" << std::string(id.first.size(), '^'); if (id.second.empty()) std::cout << " (no suggestions)\n"; else { std::cout << " (did you mean "; once_t first; for (auto& s : id.second) std::cout << (first?"":" or ") << "'" << s << "'"; std::cout << "?)\n"; } } if (ok) { std::cout << "AST: " << expr << "\n"; } else { std::cout << "Parse failed\n"; } if (f!=l) std::cout << "Remaining input: '" << std::string(f,l) << "'\n"; } } ``` --- ¹ [Boost spirit skipper issues](https://stackoverflow.com/questions/17072987/boost-spirit-skipper-issues/17073965#17073965)
Spirit doesn't have that feature. You could generate it yourself but it would be considerable effort to do it generically (if not straight up impossible, due NP-completeness). Perhaps just detect parse error (`on_error`) and have a limited number of stock "options" - the 80% rule should go a long way. Also, I think the "sketch" with parsing 'invalid placeholder tokens' will not work because you'll have to build in assumptions about the type of the placeholder token and it may therefore not result in a valid expression. I sense that you treat expression parsing as little more than tokenizing - which isn't accurate in most cases.
29,836,610
Firefox version: 37 Chrome version: 40 I am calling from chrome-firefox in a WebRTC application and it is not showing a remote stream. firefox-firefox and chrome-chrome are both fine. I add my local stream to the peer connection, create my answer and send it via my signalling method, and then start sending my ice candidates. One possible issue is that I may be receiving (and setting on the peerConnection) ice candidates before I create my answer on the receiver side, although, I did try putting timeouts on candidate adding to ensure that doesn't happen and the problem was the same. Here is information from the Firefox side, where I ultimately get "ICE failed, see about:webrtc for more details" SDP settings (IP addresses censored): ``` Local SDP v=0 o=mozilla...THIS_IS_SDPARTA-37.0.2 6210678986336338968 0 IN IP4 0.0.0.0 s=- t=0 0 a=sendrecv a=fingerprint:sha-256 7D:6F:E7:3F:5A:65:27:3A:EB:41:5E:E3:B0:91:02:59:81:5F:48:8C:DE:96:FC:89:ED:9D:C4:BF:E0:0A:1D:DF a=group:BUNDLE audio video a=ice-options:trickle m=audio 18943 RTP/SAVPF 111 c=IN IP4 <ip2> a=candidate:0 1 UDP 2122252543 <ip1> 36102 typ host a=candidate:1 1 UDP 1686110207 <ip5> 39509 typ srflx raddr <ip1> rport 36102 a=candidate:3 1 UDP 92274687 <ip2> 18943 typ relay raddr <ip2> rport 18943 a=sendrecv a=end-of-candidates a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level a=ice-pwd:679dfdec38e1d2899d3614d64081186a a=ice-ufrag:d064eacb a=mid:audio a=rtcp-mux a=rtpmap:111 opus/48000/2 a=setup:active a=ssrc:2905377298 cname:{506042e1-9b66-42b4-8238-dad7d0edecf2} m=video 18207 RTP/SAVPF 100 c=IN IP4 <ip2> a=candidate:0 1 UDP 2122252543 <ip1> 40785 typ host a=candidate:0 2 UDP 2122252542 <ip1> 38373 typ host a=candidate:1 1 UDP 1686110207 <ip5> 51040 typ srflx raddr <ip1> rport 40785 a=candidate:1 2 UDP 1686110206 <ip5> 20057 typ srflx raddr <ip1> rport 38373 a=candidate:3 1 UDP 92274687 <ip2> 18207 typ relay raddr <ip2> rport 18207 a=candidate:3 2 UDP 92274686 <ip2> 18115 typ relay raddr <ip2> rport 18115 a=sendrecv a=end-of-candidates a=fmtp:100 max-fs=12288;max-fr=60 a=ice-pwd:679dfdec38e1d2899d3614d64081186a a=ice-ufrag:d064eacb a=mid:video a=rtcp-fb:100 nack a=rtcp-fb:100 nack pli a=rtcp-fb:100 ccm fir a=rtcp-mux a=rtpmap:100 VP8/90000 a=setup:active a=ssrc:488270549 cname:{506042e1-9b66-42b4-8238-dad7d0edecf2} Remote SDP v=0 o=- 7318013814084266610 2 IN IP4 127.0.0.1 s=- t=0 0 a=sendrecv a=group:BUNDLE audio video a=msid-semantic:WMS m=audio 9 RTP/SAVPF 111 103 104 9 0 8 106 105 13 126 c=IN IP4 0.0.0.0 a=candidate:2193902281 1 udp 2122260223 <ip4> 48993 typ host generation 0 a=candidate:1313437018 1 udp 1686052607 <ip3> 49740 typ srflx raddr <ip4> rport 48993 generation 0 a=candidate:2193902281 2 udp 2122260223 <ip4> 48993 typ host generation 0 a=candidate:3427251769 2 tcp 1518280447 <ip4> 0 typ host tcptype active generation 0 a=candidate:1313437018 2 udp 1686052607 <ip3> 49740 typ srflx raddr <ip4> rport 48993 generation 0 a=candidate:3427251769 1 tcp 1518280447 <ip4> 0 typ host tcptype active generation 0 a=candidate:3785383356 1 udp 41885439 <ip6> 15958 typ relay raddr <ip3> rport 49740 generation 0 a=sendrecv a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level a=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time a=fingerprint:sha-256 C1:CB:BF:44:C5:A0:AD:C2:72:DA:6B:1D:3B:8B:6D:EA:48:56:21:A9:70:7B:F0:A1:AA:9B:BC:38:81:CF:5E:FA a=ice-options:google-ice a=ice-pwd:y/RCxcbHnWBQ11TkkIgguND7 a=ice-ufrag:zwx79P612mklrN8V a=maxptime:60 a=mid:audio a=rtcp-mux a=rtpmap:111 opus/48000/2 a=rtpmap:103 ISAC/16000/1 a=rtpmap:104 ISAC/32000/1 a=rtpmap:9 G722/8000/1 a=rtpmap:0 PCMU/8000 a=rtpmap:8 PCMA/8000 a=rtpmap:106 CN/32000/1 a=rtpmap:105 CN/16000/1 a=rtpmap:13 CN/8000/1 a=rtpmap:126 telephone-event/8000/1 a=setup:actpass a=ssrc:3947573917 cname:sH2LQZ+VcJ2oyRhi a=ssrc:3947573917 msid:f11srXWZnw7HYBbEfqK65NOcnuxjyX1nHCaz 3b60d586-c63b-4ab8-962a-9f49cb304480 a=ssrc:3947573917 mslabel:f11srXWZnw7HYBbEfqK65NOcnuxjyX1nHCaz a=ssrc:3947573917 label:3b60d586-c63b-4ab8-962a-9f49cb304480 m=video 9 RTP/SAVPF 100 116 117 96 c=IN IP4 0.0.0.0 a=candidate:2193902281 1 udp 2122260223 <ip4> 48993 typ host generation 0 a=candidate:2193902281 2 udp 2122260223 <ip4> 48993 typ host generation 0 a=candidate:3427251769 1 tcp 1518280447 <ip4> 0 typ host tcptype active generation 0 a=candidate:1313437018 1 udp 1686052607 <ip3> 49740 typ srflx raddr <ip4> rport 48993 generation 0 a=candidate:1313437018 2 udp 1686052607 <ip3> 49740 typ srflx raddr <ip4> rport 48993 generation 0 a=candidate:3427251769 2 tcp 1518280447 <ip4> 0 typ host tcptype active generation 0 a=candidate:3785383356 1 udp 41885439 <ip5> 15958 typ relay raddr <ip3> rport 49740 generation 0 a=sendrecv a=extmap:2 urn:ietf:params:rtp-hdrext:toffset a=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time a=fingerprint:sha-256 C1:CB:BF:44:C5:A0:AD:C2:72:DA:6B:1D:3B:8B:6D:EA:48:56:21:A9:70:7B:F0:A1:AA:9B:BC:38:81:CF:5E:FA a=ice-options:google-ice a=ice-pwd:y/RCxcbHnWBQ11TkkIgguND7 a=ice-ufrag:zwx79P612mklrN8V a=mid:video a=rtcp-fb:100 ccm fir a=rtcp-fb:100 nack a=rtcp-fb:100 nack pli a=rtcp-mux a=rtpmap:100 VP8/90000 a=rtpmap:116 red/90000 a=rtpmap:117 ulpfec/90000 a=rtpmap:96 rtx/90000 a=setup:actpass a=ssrc:1338156545 cname:sH2LQZ+VcJ2oyRhi a=ssrc:1338156545 msid:f11srXWZnw7HYBbEfqK65NOcnuxjyX1nHCaz a574999b-48e2-448d-abd4-8c61bea4d24f a=ssrc:1338156545 mslabel:f11srXWZnw7HYBbEfqK65NOcnuxjyX1nHCaz a=ssrc:1338156545 label:a574999b-48e2-448d-abd4-8c61bea4d24f a=ssrc:4062078076 cname:sH2LQZ+VcJ2oyRhi a=ssrc:4062078076 msid:f11srXWZnw7HYBbEfqK65NOcnuxjyX1nHCaz a574999b-48e2-448d-abd4-8c61bea4d24f a=ssrc:4062078076 mslabel:f11srXWZnw7HYBbEfqK65NOcnuxjyX1nHCaz ``` The log has error messages like this: ``` ICE(PC:1429771770507818 (id=590 url=<censored>): Message does not correspond to any registered stun ctx Inconsistent message method: 103 expected 001 (PC:1429771770507818 (id=590 url=<censored>) has no stream matching stream 142977177050781 (PC:1429771770507818 (id=590 url=<censored>) specified too many components ``` **On the chrome** side I see some ambiguous error messages when trying to add the ICE candidates sent from Firefox through the signal channel. They look like this: ``` RTCIceCandidate candidate: "candidate:3 2 UDP 92274686 <ip> typ relay raddr <ip> rport 18910" sdpMLineIndex: 1 sdpMid: "null" ``` and the error message: ``` Failed to execute 'addIceCandidate' on 'RTCPeerConnectiion': The ICE candidate could not be added. ``` Is there some kind of inconsistency between firefox and chrome I am not addressing?
2015/04/24
[ "https://Stackoverflow.com/questions/29836610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4399172/" ]
not sure if this would work, but give the below code a try, before adding the ICE candidate, just try reforming the RTCIceCandidate from what is being sent... ``` ... candidate = new RTCIceCandidate({ sdpMLineIndex: candidate.label, candidate: candidate.candidate }); peerConnection.addIceCandidate(candidate, onSuccess, onFailure); ``` I am assuming RTCIceCandidate form is different in `firefox` and `chrome` hence the problem.
the "null" sdpMid looks wrong... does it work if you omit that? The mline index should be enough usually.
4,232,018
Simplify $$\sum\_{k=0} \binom{n−2k} k$$ Or alternatively, show that it can't be simplified any more. I tried Hockey stick identity but I had issues with the fact that the top had a -2k term. I then tried using $\binom {n+1}{k+1}$ = $\binom{n}{k} + \binom{n}{k+1}$, but again the -2k term means you can't add consecutive terms. Some values I calculated are 3 for n=4 4 for n=5 6 for n =6 9 for n=7. There doesn't seem to be a pattern.
2021/08/24
[ "https://math.stackexchange.com/questions/4232018", "https://math.stackexchange.com", "https://math.stackexchange.com/users/955800/" ]
This is only an alternative to find the recurrence relation above. The expression $\binom{n-k}{k}$ gives the number of solutions to the equation $n=\sum{x\_{i}}\phantom{x}|\phantom{x}x\_{i}\in\{1,3\}$ when there are $k$ threes. Therefore the following expression gives the number of possibilities to express $n$ as summation of ones and threes. $$ a\_{n}=\sum{\binom{n-2k}{k}} $$ There are only two possibilities for $x\_{1}$. If $x\_{1}=1$ then the other $x\_{i}$ are ones and threes that sum up to $n-1$. If $x\_{1}=3$ then the other $x\_{i}$ are ones and threes that sum up to $n-3$. Hence the following recurrence relation: $$ a\_{n}=a\_{n-1}+a\_{n-3} $$
**Recursive Solution** Considering [an old answer](https://math.stackexchange.com/a/1549204) to a related problem, I tried $$ \begin{align} a\_n &=\sum\_k\binom{n-2k}{k}[3k\le n]\tag{1a}\\[3pt] &=\sum\_k\binom{n-2k-1}{k}[3k\le n]+\sum\_k\binom{n-2k-1}{k-1}[3k\le n]\tag{1b}\\[3pt] &=\sum\_k\binom{n-2k-1}{k}[3k\le n]+\sum\_k\binom{n-2k-3}{k}[3k+3\le n]\tag{1c}\\ &=a\_{n-1}+\color{#C00}{\sum\_k\binom{n-2k-1}{k}\overbrace{([3k\le n]-[3k\le n-1])}^{[n=3k]}}\tag{1d}\\ &\phantom{={}}+a\_{n-3}+\color{#090}{\sum\_k\binom{n-2k-3}{k}\overbrace{([3k+3\le n]-[3k\le n-3])}^0}\tag{1e}\\[12pt] &=a\_{n-1}+a\_{n-3}+\color{#C00}{[n=0]}+\color{#090}{0}\tag{1f}\\[21pt] &=a\_{n-1}+a\_{n-3}+[n=0]\tag{1g} \end{align} $$ Explanation: $\text{(1b)}$: apply [Pascal's Rule](https://en.wikipedia.org/wiki/Pascal%27s_rule) $\text{(1c)}$: substitute $k\mapsto k+1$ in the second sum $\text{(1d)}$: add and subtract $a\_{n-1}$ from the left term of $\text{(1c)}$ $\text{(1e)}$: add and subtract $a\_{n-3}$ from the right term of $\text{(1c)}$ $\text{(1f)}$: $\binom{k-1}{k}=[k=0]$ $\text{(1g)}$: simplify $\text{(1a)}$ says that $a\_n=0$ for $n\lt0$. $\text{(1g)}$ says that $a\_0=1$, and for $n\gt0$, $$ a\_n=a\_{n-1}+a\_{n-3}\tag2 $$ Thus, $$ \begin{array}{c|c}n&0&1&2&3&4&5&6&7&8\\\hline a\_n&1&1&1&2&3&4&6&9&13\end{array} $$ Care needs to be taken with the upper limits of the sum, as shown in $\text{(1d)}$ and $\text{(1e)}$, but luckily, the terms cancel for $n\gt0$. --- **Solution to the Linear Recurrence Equation** A closed form solution to the constant coefficient linear recurrence equation takes the form $$\newcommand{\csch}{\operatorname{csch}} a\_n=c\_1r\_1^n+c\_2r\_2^n+c\_3r\_3^n\tag3 $$ where $r\_1,r\_2,r\_3$ are roots of $x^3-x^2-1=0$, which, if we substitute $x=t+\frac13$, becomes $t^3-\frac13t=\frac{29}{27}$. Multiplying the identity $4\cosh^3(u)-3\cosh(u)=\cosh(3u)$ by $\frac2{27}$ gives $$ \left(\frac23\cosh(u)\right)^3-\frac13\left(\frac23\cosh(u)\right)=\frac2{27}\cosh(3u)\tag4 $$ Applying $(4)$, we get the real root $$ r\_1=\frac13+\frac23\cosh\left(\frac13\cosh^{-1}\left(\frac{29}2\right)\right)\tag5 $$ and then, because $r\_1+r\_2+r\_3=r\_1r\_2r\_3=1$, we can compute the complex roots $$ r\_2=\frac{1-r\_1}2+i\frac{\sqrt{3r\_1^2-2r\_1-1}}2\tag{6a} $$ and $$ r\_3=\frac{1-r\_1}2-i\frac{\sqrt{3r\_1^2-2r\_1-1}}2\tag{6b} $$ and we can compute the coefficients using [Cramer's Rule](https://en.wikipedia.org/wiki/Cramer%27s_rule) and [Vandermonde Determinants](https://en.wikipedia.org/wiki/Vandermonde_matrix) $$ c\_1=\frac{\det\begin{bmatrix} 1&1&1\\ 1&r\_2&r\_3\\ 1&r\_2^2&r\_3^2 \end{bmatrix}} {\det\begin{bmatrix} 1&1&1\\ r\_1&r\_2&r\_3\\ r\_1^2&r\_2^2&r\_3^2 \end{bmatrix}} =\frac{r\_1^2+1}{r\_1^2+3}\tag{7a} $$ and similarly $$ c\_2=\frac{r\_2^2+1}{r\_2^2+3}\tag{7b} $$ and $$ c\_3=\frac{r\_3^2+1}{r\_3^2+3}\tag{7c} $$ Now we simply need to plug $(5)$, $(6)$, and $(7)$ into $(3)$ to get a closed form for the solution. --- **A Simple Closed Form** Note that $|c\_2|=|c\_3|\approx0.22968031\lt\frac14$. Since $r\_1\approx1.46557123\gt1$, and $r\_1r\_2r\_3=1$, we have that $|r\_2|=|r\_3|\lt1$. Thus, since $\left|c\_2r\_2^n+c\_3r\_3^n\right|\lt\frac12$, according to $(3)$, $a\_n$ is the closest integer to $c\_1r\_1^n$: $$ \begin{array}{r|r|l} n&a\_n&c\_1r\_1^n\\\hline 0&1&0.61149199\\ 1&1&0.89618507\\ 2&1&1.31342306\\ 3&2&1.92491505\\ 4&3&2.82110012\\ 5&4&4.13452318\\ 6&6&6.05943824\\ 7&9&8.88053836\\ 8&13&13.0150615\\ \end{array} $$ Therefore, a simple closed form would be $$ a\_n=\left\lfloor c\_1r\_1^n+\tfrac12\right\rfloor\tag8 $$ where, computed from $(5)$, $$ r\_1\approx1.4655712318767680267\tag{9a} $$ and, computed from $\text{(7a)}$, $$ c\_1\approx0.61149199195081251841\tag{9b} $$
29,670,261
Do we have any option of publishing any API to particular user/subscriber group which is visible only to those subscriber in wso2 API manager. For Example - I have created an API - userValidateAPI which require to be used only by internal application team & shouldn't be visible to all. If application team login in store mode, they should be able to see this API & subscribe but shouldn't be visible to other subscriber. Thanks, Amith
2015/04/16
[ "https://Stackoverflow.com/questions/29670261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4658730/" ]
A relatively simple one-liner might suffice: Tested on OSX, ``` md5 -q file*.txt | sort -u ``` If you see more than one line as output, the files are not the same
Put this script in the directory which has `file*.txt` and run ``` #!/bin/bash FILES=./file*.txt for filename in $FILES; do for other in $FILES; do if [ "$filename" != "$other" ] then cmp -s $filename $other retval=$? if [ $retval -eq 0 ] then echo "$filename $other are same" fi fi done done ``` And it will print both `file1.txt file3.txt are same` and `file3.txt file1.txt are same`. You can figure out how to avoid that.