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
11,898,647
I'd like to generate alarms on my Java desktop application : * alarms set with a specific date/time which can be in 5 minutes or 5 months * I need to be able to create a SWT application when the alarm is triggered * I need this to be able to work on any OS. The software users will likely have Windows (90% of them), and the rest Mac OS (including me) * the software license must allow me to use it in a commercial program, without requiring to open source it (hence, no GPL) * I cannot require the users to install Cygwin, so the implementation needs to be native to Windows and Unix I am developing using Java, Eclipse, SWT and my application is deployed from my server using Java Web Start. I'm using Mac OS X.6 for developing. --- I think I have a few options: 1. Run my application at startup, and handle everything myself; 2. Use a system service. 3. Use the cron table on Unix, and Scheduled Tasks on Windows --- Run at startup ============== I don't really like this solution, I'm hoping for something more elegant. Refs: [I would like to run my Java program on System Startup on Mac OS/Windows. How can I do this?](https://stackoverflow.com/questions/2949649/i-would-like-to-run-my-java-program-on-system-startup-on-mac-os-windows-how-can) System service ============== If I run it as a system service, I can benefit from this, because the OS will ensure that my software: * is always running * doesn't have/need a GUI * restarts on failure I've researched some resources that I can use: * [run4j](http://winrun4j.sourceforge.net/) — CPL — runs on Windows only, seems like a valid candidate * [jsvc](http://commons.apache.org/daemon/jsvc.html) — Apache 2.0 — Unix only, seems like a valid candidate * [Java Service Wrapper](http://wrapper.tanukisoftware.com/doc/english/licenseOverview.html) — Various — I cannot afford paid licenses, and the free one is a GPL. Hence, I don't want to/can't use this My questions in the system service options are: 1. Are there other options? 2. Is my planned implementation correct: * at the application startup, check for existence of the service * if it is not installed: + escalate the user to install the service (root on Unix, UAC on Windows) + if the host OS is Windows, use run4j to register the service + if the host OS is Unix, use jsvc to register the service * if it is not running, start it Thus, at the first run, the application will install the service and start it. When the application closes the service is still running and won't need the application ever again, except if it is unregistered. However, I think I still miss the "run on startup" feature. Am I right? Am I missing something? cron / Task Scheduler ===================== On Unix, I can easily use the cron table without needing the application to escalate the user to root. I don't need to handle restarts, system date changes, etc. Seems nice. On Windows, I can use the [Task Scheduler](http://support.microsoft.com/kb/308569), even in command-line using [At](http://technet.microsoft.com/en-us/library/bb726974.aspx) or [SchTasks](http://technet.microsoft.com/en-us/library/cc725744.aspx). This seems nice, but I need this to be compatible from XP up to 7, and I can't easily test this. --- So what would you do? Did I miss something? Do you have any advice that could help me pick the best and most elegant solution?
2012/08/10
[ "https://Stackoverflow.com/questions/11898647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/334493/" ]
Of the available options you have listed, IMHO Option 3 is better. As you are looking only for an external trigger to execute the application, CRON or Scheduled tasks are better solutions than other options you have listed. By this way, you remove a complexity from your application and also your application need not be running always. It could be triggered externally and when the execution is over, your application will stop. Hence, unnecessary resource consumption is avoided.
I believe your scenario is correct. Since services are system specific things, IMHO you should not user a generic package to cover them all, but have a specific mechanism for every system.
29,921,685
i am using this example <http://jsfiddle.net/MJTkk/2/> in order to find where the cursor is(left or right in my example). i also have two images and i want the second.png to hover over the other smoothly but to hover on the direction of the cursor(follow the cursor). ``` <div class="box" id="box" style="margin:100px 0px 0px 100px"> <a href="#" target="_blank"> <div class="under_div"></div> <div class="over_div"></div> </a> </div> .box { position:relative; width:100px; height:100px; } .under_div { background-size: 100px 100px; height: 100%; width: 100%; position: absolute; background-image:url(http://s30.postimg.org/dd01lyrjx/first.png); background-repeat: no-repeat; background-position: top right; -webkit-transition: all 0.5s ease; -moz-transition: all 0.5s ease; -ms-transition: all 0.5s ease; -o-transition: all 0.5s ease; transition: all 0.5s ease; } .over_div { background-size: 100px 100px; height: 100%; position: absolute; background-image:url(http://s21.postimg.org/wjrhdklar/second.png); background-repeat:no-repeat; background-position: top left; -webkit-transition: all 0.5s ease; -moz-transition: all 0.5s ease; -ms-transition: all 0.5s ease; -o-transition: all 0.5s ease; transition: all 0.5s ease; } .box:hover .over_div { -webkit-transition: all 0.5s ease; -moz-transition: all 0.5s ease; -ms-transition: all 0.5s ease; -o-transition: all 0.5s ease; transition: all 0.5s ease; } ``` i implement this <http://jsfiddle.net/9yj8or2z/1/> because i do not know how to explain it correctly. sorry for my english. i see that it does not work properly and the div moves when hover for some reason. if someone could help i will appreciate it!
2015/04/28
[ "https://Stackoverflow.com/questions/29921685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4394439/" ]
You should remove your `css` code in the `jquery` function completely for `.under_div` i updated your [FIDDLE](http://jsfiddle.net/9yj8or2z/3/) if this is what you want to achieve. **EDIT** i updated the fiddle once again. you got to give the over\_div if it's coming from the right (so in the `else` tag in the first function) a `position: absolute; right: 0; left: auto;` and in the second function `right: auto; left: 0;` [FIDDLE NO 2 BOTH DIRECTIONS WORKING](http://jsfiddle.net/9yj8or2z/5/) ask if you got any further questions, but this should be it!
I fixed some issues with it: <http://jsfiddle.net/9yj8or2z/2/> By adding `left: 0;` and `width: 0px;` to CSS, and also adding `overflow:hidden;`, I could fix that the gray box was moving at the beginning wrongly, but still animates. I hope this is what you were looking for :)
3,121,657
That is, do all the subgroups of, say, S6, look sort of like the subgroup generated by the cycles (123) and (45)? This seems like an overly simplistic characterization of the Abelian subgroups, but I can't think of any counterexamples.
2019/02/21
[ "https://math.stackexchange.com/questions/3121657", "https://math.stackexchange.com", "https://math.stackexchange.com/users/641262/" ]
What you did is fine. And then you use the fact that\begin{align}1-\cos(x)&=1-\left(\cos^2\left(\frac x2\right)-\sin^2\left(\frac x2\right)\right)\\&=2\sin^2\left(\frac x2\right).\end{align}
Please note how $1-cos(x) = \frac{1}{2} sin^2(\frac{x}{2})$ and $\frac{1}{1-cos(x)} = \frac{1}{2sin^2(\frac{x}{2})}=\frac{csc^2(\frac{x}{2})}{2}$.
17,117,759
I want to check if a variable of type guid exist. I used ``` new Db().JobCreate.Any(a => a.GuidVariable1.Equals(GuidVariable2, StringComparison.OrdinalIgnoreCase)); ``` but I get the error `Member 'object.Equals(object, object)' cannot be accessed with an instance reference; qualify it with a type name instead` How can I fix this?
2013/06/14
[ "https://Stackoverflow.com/questions/17117759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/807223/" ]
I'm assuming you have another instance variable named `GuidVariable2`. Unless there's something else involved I'd just do the following: ``` new Db().JobCreate.Any(a => a.GuidVariable1 == GuidVariable2); ``` If the variables are actually `string`s I'd do the following: ``` new Db().JobCreate.Any(a => a.GuidVariable1.ToLower() == GuidVariable2.ToLower()); ``` Update based on comment: `Guid` represents a hexidecimal number, so the case of the alpha digits is irrelevant. When represented as a `string`, case could be Upper, Lower or a combination but the actual number is the same: ``` var guid1 = Guid.Parse("a0449976-604e-4bdf-826d-234c4564c3e0"); var guid2 = Guid.Parse("A0449976-604E-4BDF-826D-234C4564C3E0"); var guid3 = Guid.Parse("A0449976-604E-4bdf-826d-234c4564c3e0"); guid1 == guid2; //true guid2 == guid3; //true ```
Here you go: ``` new Db().JobCreate.Any(a => string.Equals( a.GuidVariable1, GuidVariable2, StringComparison.OrdinalIgnoreCase)); ``` (this is of course assuming your so-called GUIDs are actually strings, if you want to compare GUIDs just do this:) ``` new Db().JobCreate.Any(a => a.GuidVariable1.Equals(GuidVariable2)); ```
48,578,642
I really want to reserve a specific set of memory locations with the `MAP_FIXED` option to `mmap`. However, by default `mmap` will `munmap` anything already at those addresses, which would be disastrous. How can I tell `mmap` to "reserve the memory at this address, but fail if it is already in use"?
2018/02/02
[ "https://Stackoverflow.com/questions/48578642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27074/" ]
According to me usage of noun is not necessary or comes under any standard,but yes it's usage helps your endpoint to be more specific and simple to understand. So if any nomenclature is making your URL more human readable or easy to understand then that type or URL I usually prefer to create and keep things simple. It also helps your service consumer who understand the functionality of any service partially by name itself.
> > For a restfull service, does the noun can be omitted and discarded? > > > Yes. REST doesn't care what spelling you use for your resource identifiers. URL shorteners *work* just fine. Choices of spelling are dictated by local convention, they are much like variables in that sense. Ideally, the spellings are independent of the underlying domain and data models, so that you can change the models without changing the api. Jim Webber expressed the idea this way > > The web is not your domain, it's a document management system. All the HTTP verbs apply to the document management domain. URIs do NOT map onto domain objects - that violates encapsulation. Work (ex: issuing commands to the domain model) is a side effect of managing resources. In other words, the resources are part of the anti-corruption layer. You should expect to have many many more resources in your integration domain than you do business objects in your business domain. > > > Resources adapt your domain model for the web > > > That said, if you are expecting clients to discover URIs in your documentation (rather than by reading them out of well specified hypermedia responses), then its going to be a good idea to use URI spellings that follow a simple conceptual model.
8,193,525
I'm wondering how to create the Jquery Nivo Slider transition effect, not creating the entire plugin. I tried playing with CSS's `clip` property but I couldn't get it to create the effect where part of the image fades or moves out block by block until the next slide shows. If anyone has a general idea or specific code of how to make the transition effects, it would be appreciated thanks.
2011/11/19
[ "https://Stackoverflow.com/questions/8193525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/701510/" ]
The generic idea is following: You have div with first image and then you have big number of divs with second image, you spawn them adjusting css properties Each second image div is just a small piece of it with adjusted background, so it overlays previous image, part of it With this method you can spawn pieces in any order you want with any effect you want. Slide them in, fade them im, randomally fill, anything Html will look like this: ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title></title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script> <style type="text/css"> .first{ height:500px; width:500px; position: absolute; background:url(1.jpg); z-index: 2; } .second_part1{ height:50px; width:50px; position: absolute; background:url(2.jpg) 0 0; z-index: 2; } .second_part2{ height:50px; width:50px; position: absolute; background:url(2.jpg) -50px 0; left:50px; z-index: 2 } .second_part3{ height:50px; width:50px; position: absolute; background:url(2.jpg) -200px -150px ; left:200px;; top:150px; z-index: 2 } </style> </head> <body> <div class="first"> </div> <div class="second_part1"> </div> <div class="second_part2"> </div> <div class="second_part3"> </div> </body> </html> ``` And you also can have another image2 div, which will be shown up after you have loaded all pieces. And destroy all pieces after you show it up There are plenty of ways to impement whole proccess on javascript As for me first of all make array of pieces(array of divs) and then you can create any number of effects you want, just by displaying them with different effects and different order I do not know if nivo uses this way or some other, but this works :)
Just dropped to this page via Google while finding a solution to my NivoSlider problem. NivoSlider, basically just create some div element as image replacement, then take the image URL to be used as background image with different background position for each pieces that will be animated later: ``` // Set the slices size var slice_w = $slider.width() / config.slices, slice_h = $slider.height(); // Build the slices for (var i = 0; i < config.slices; i++) { $('<div class="slice" />').css({ 'position':'absolute', 'width':slice_w, 'height':slice_h, 'left':slice_w*i, 'z-index':4, 'background-color':'transparent', 'background-repeat':'no-repeat', 'background-position':'-' + slice_w*i + 'px 0' }).appendTo($slider); } // Change the background image when slideshow starts from here... etc etc... ``` Here's an example I'v made long time ago: <http://reader-download.googlecode.com/svn/trunk/simple-useful-jquery-slideshow_nivo-slider-like-effect.html>
43,316,459
There are several attempts to optimize calculation of HOG descriptor with using of SIMD instructions: [OpenCV](https://github.com/opencv/opencv/blob/master/modules/objdetect/src/hog.cpp), [Dlib](https://github.com/davisking/dlib/blob/master/dlib/image_transforms/fhog.h), and [Simd](https://github.com/ermig1979/Simd/blob/master/src/Simd/SimdAvx2Hog.cpp). All of them use scalar code to add resulting magnitude to HOG histogram: ``` float histogram[height/8][width/8][18]; float ky[height], kx[width]; int idx[size]; float val[size]; for(size_t i = 0; i < size; ++i) { histogram[y/8][x/8][idx[i]] += val[i]*ky[y]*kx[x]; histogram[y/8][x/8 + 1][idx[i]] += val[i]*ky[y]*kx[x + 1]; histogram[y/8 + 1][x/8][idx[i]] += val[i]*ky[y + 1]*kx[x]; histogram[y/8 + 1][x/8 + 1][idx[i]] += val[i]*ky[y + 1]*kx[x + 1]; } ``` There the value of `size` depends from implementation but in general the meaning is the same. I know that problem of [histogram calculation with using of SIMD](https://stackoverflow.com/questions/39266476/how-to-speed-up-this-histogram-of-lut-lookups) does not have a simple and effective solution. But in this case we have small size (18) of histogram. Can it help in SIMD optimizations?
2017/04/10
[ "https://Stackoverflow.com/questions/43316459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2831104/" ]
I have found solution. It is a temporal buffer. At first we sum histogram to temporary buffer (and this operation can be vectorized). Then we add the sum from buffer to output histogram (and this operation also can be vectorized): ``` float histogram[height/8][width/8][18]; float ky[height], kx[width]; int idx[size]; float val[size]; float buf[18][4]; for(size_t i = 0; i < size; ++i) { buf[idx[i]][0] += val[i]*ky[y]*kx[x]; buf[idx[i]][1] += val[i]*ky[y]*kx[x + 1]; buf[idx[i]][2] += val[i]*ky[y + 1]*kx[x]; buf[idx[i]][3] += val[i]*ky[y + 1]*kx[x + 1]; } for(size_t i = 0; i < 18; ++i) { histogram[y/8][x/8][i] += buf[i][0]; histogram[y/8][x/8 + 1][i] += buf[i][1]; histogram[y/8 + 1][x/8][i] += buf[i][2]; histogram[y/8 + 1][x/8 + 1][i] += buf[i][3]; } ```
You can do a partial optimisation by using SIMD to calculate all the (flattened) histogram indices and the bin increments. Then process these in a scalar loop afterwards. You probably also want to strip-mine this such that you process one row at a time, in order to keep the temporary bin indices and increments in cache. It might appear that this would be inefficient, due to the use of temporary intermediate buffers, but in practice I have seen a useful overall gain in similar scenarios. ``` uint32_t i = 0; for (y = 0; y < height; ++y) // for each row { uint32_t inds[width * 4]; // flattened histogram indices for this row float vals[width * 4]; // histogram bin increments for this row // SIMD loop for this row - calculate flattened histogram indices and bin // increments (scalar code shown for reference - converting this loop to // SIMD is left as an exercise for the reader...) for (x = 0; x < width; ++x, ++i) { indices[4*x] = (y/8)*(width/8)*18+(x/8)*18+idx[i]; indices[4*x+1] = (y/8)*(width/8)*18+(x/8 + 1)*18+idx[i]; indices[4*x+2] = (y/8+1)*(width/8)*18+(x/8)*18+idx[i]; indices[4*x+3] = (y/8+1)*(width/8)*18+(x/8 + 1)*18+idx[i]; vals[4*x] = val[i]*ky[y]*kx[x]; vals[4*x+1] = val[i]*ky[y]*kx[x+1]; vals[4*x+2] = val[i]*ky[y+1]*kx[x]; vals[4*x+3] = val[i]*ky[y+1]*kx[x+1]; } // scalar loop for this row float * const histogram_base = &histogram[0][0][0]; // pointer to flattened histogram for (x = 0; x < width * 4; ++x) // for each set of 4 indices/increments in this row { histogram_base[indices[x]] += vals[x]; // update the (flattened) histogram } } ```
51,087,151
I've been wondering about a coding practice I've had for some time and I wanted to know if: * it had some importance * there was a better way to do so Imagine you have an update loop and two various states, A and B. In state A, you need a specific variable V that you wish to clear when exiting state A (or entering state B). So, what I usually do is creating a function in B saying that : ``` if V not null: V = null ``` Which means that each time I go into the loop, I check for the V not null condition. Does this have a cost ? Is there a cleaner way to do so ? Thanks a lot !
2018/06/28
[ "https://Stackoverflow.com/questions/51087151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8153539/" ]
The discussion is still on, and here you can find some answers and opinions, even directly from the Angular developers: <https://github.com/ngx-translate/core/issues/495> Personally, I would structure the app with the official i18n and eventually add some dedicated translation in the code with the ngx-translate library. > > Is there a way to do live language switching with angular i18n? > > > Actaully, there is. You need to build different dist of your app, but then you can switch live after the full deploy: [Official Angluar docs](https://angular.io/guide/i18n#build-for-multiple-locales) and [suggested tutorial](https://medium.com/@feloy/deploying-an-i18n-angular-app-with-angular-cli-fc788f17e358)
It is understandable why developers like an ngx-translate like library to take care of internationalization. After all it makes our lives so easy by making the translation problem a 1v1 mapping. Unfortunately this is not how it works with human languages. One has two know more than one language to better understand the shortcomings of this approach. Here's a little example: Say you have an app for travel expense, you have a tabular view in which one column title is "times" indicating when the expense was reported. Then imagine in such app you have a mini calculator for doing basic verification of your expenses which happens to have a multiplication button x with a layover saying "times". When you do ngx-translate you extract them both with the same key "TIMES" which in turn the translator guy gives you back one translation for. But the first occurrence of "time" is not necessarily translated the same as the second one in all the other languages. Take Spanish for instance: * "two TIMES three"(as in the calculator) -> "dos POR tres" * "expense TIMES"(as in tabular view) -> "TIEMPOS de gasto" This is actually why internationalization is moving to the direction of using a more sophisticated format such as XLF to support for meaning, description(in the case of Angular) rather the old 1-depth JSON style which cannot accommodate for translation with respect to context. Now you may argue that this is solvable by registering two different keys for "times" which in English they happen to map to the same thing but that requires you as a developer to know all the languages your app supports while developing or you would have to go through another iteration(time is money!) of getting customer's feedback and then adding a separate key whereas if you provide description and meaning for your message(text) then the translator takes care of it for you without you having any knowledge of the other language(If you know Spanish think about how complicated this can be with subjunctive and indicative forms of verb which are the same in English but not Spanish). To answer your other question "Is there a way to do live language switching with angular i18n?": yes there is. Have a look at [this awesome article](https://blog.nrwl.io/managing-state-in-angular-applications-22b75ef5625f) about state management in apps. Long story short you need to have your client and persistent states reflected in URL. Then all you need to do is to add a locale prefix to your path which causes your web server giving you the right locale build. Then whatever your app state was before changing locale change action happened is recoverable from URL(since it "reflects both the persistent and client state").
11,321,790
Nginx 1.1.4+ can serve upstream connection with HTTP1.1 **keepalive** directive, see the [official documentation](http://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive) (it's not the same as keepalived clients' connections). So the Unicorn configuration can look like as below: ``` upstream unicorn { server unix:/tmp/unicorn.todo.sock fail_timeout=0; keepalive 4; } server { try_files $uri/index.html $uri @unicorn; keepalive_timeout 70; location @unicorn { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://unicorn; proxy_http_version 1.1; proxy_set_header Connection ""; } } ``` These headers are required for HTTP connection: **proxy\_http\_version** and **proxy\_set\_header**. So the question is the configuration valid or socket-connection is permanent by itself?
2012/07/04
[ "https://Stackoverflow.com/questions/11321790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/290338/" ]
Yes, it's valid. There's no difference between UNIX-socket and TCP/IP-socket in terms of HTTP Keepalive.
Unicorn doesn't support persistent (keep-alive) connection by design. So, you shouldn't try to use persistent (keep-alive) connection to unicorn backend.
12,073,116
I have simple hide and show function but it is not working. any help would be appreciated ``` <head> <script type="text/javascript"> $(function(){ $('a').click(function(){ var visible= false; if(visible){ $('div').hide('slow') } else { $('div').show('slow') } visible=!visible; }) }) </script> </head> <body> <div style="background:#F00; width:500px; height:50px"></div> <a href="#">hide</a> <div class="append"></div> </body> ```
2012/08/22
[ "https://Stackoverflow.com/questions/12073116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2917268/" ]
Declare and initialise `visible` **outside** the event handler: ``` var visible= false; $('a').click(function(){ if(visible){ $('div').hide('slow') } else { $('div').show('slow') } visible=!visible; }); ``` Otherwise you are initialising `visible` with `false` *every time* the event handler is executed, so `if(visible)` will never be true. However, you can also use [`.toggle` *[docs]*](http://api.jquery.com/toggle/) to avoid having an additional status variable: ``` $('a').click(function(){ $('div').toggle(); }); ```
Try using `toggle` instead. Check out the second example here: <http://api.jquery.com/toggle/> Here's the example: ``` <!DOCTYPE html> <html> <head> <style> p { background:#dad; font-weight:bold; font-size:16px; } </style> <script src="http://code.jquery.com/jquery-latest.js"></script> </head> <body> <button>Toggle 'em</button> <p>Hiya</p> <p>Such interesting text, eh?</p> <script> $("button").click(function () { $("p").toggle("slow"); }); </script> </body> </html> ```
50,463,059
I have a column vector `X` of size *N*-by-*1* with two values: `10` and `25`. I want to switch those values, i.e. every element with value `10` should become `25` and vice versa. Pseudo-code: ``` A = [ 10; 25; 25; 10; 25; 25; 10] NewNew = find(A == 10) NewNew2 = find(A == 25) NewNew3 = [ ]; for NewNew3 if NewNew NewNew=25 else NewNew2 NewNew2=10 end ``` I tried this now still no success: ``` for B = 1:size(A) if A == 10 A = 25 elseif A == 25 A = 10 end end ``` How can I switch values?
2018/05/22
[ "https://Stackoverflow.com/questions/50463059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8269433/" ]
``` N=10; X = randi([1 2],N,1); A = zeros(size(X)); % create output vector A(X==2)=1; % whenever X==2, set A=1 A(X==1) = 2; % whenever X==1, set A=2 [X A] ans = 1 2 2 1 2 1 1 2 2 1 1 2 1 2 2 1 2 1 2 1 ``` You can do this with [logical indexing](https://stackoverflow.com/q/32379805/5211833). Just make sure to get a separate output vector, as setting `X(X==1)=2` will make your whole vector `2`, and then calling `X(X==2)=1` sets the whole vector to `1`. If necessary, use `X=A` at the end. Final advice: your `for` loop needs indexing, which is about as basic as MATLAB goes. You can solve this problem with a `for` loop, although I'd recommend using logical indexing as per the above. I strongly suggest you to either take a basic course in MATLAB, or read [the MathWork's own tutorial on MATLAB](http://mathworks.com/help/matlab/getting-started-with-matlab.html).
There are some other options you can consider. 1.) (Irrelevant option. Use ibancg's option, cleaner and faster.) If you have just those two values, a simpler and faster solution would be to initialize to one of these two numbers and flip just a subset of the numbers: ``` A = [ 10; 25; 25; 10; 25; 25; 10]; X = ones(size(A)) * 10; % initialize X with 10. X(A == 10) = 25; % Set values where A is 10 to 25. ``` 2.) (irrelevant, too slow): Another possibility if you know that some numbers will never appear is to use temporary third number and avoid creating a new matrix - operate kind of similar to the typical "swap two numbers" recipe. ``` A(A == 10) = 1; % Temp value A(A == 25) = 10; A(A == 1) = 25; ``` 3.) Finally, the third option would be to save logical matrix and then overwrite A. ``` Ais10 = A==10; Ais25 = A==25; A(Ais10) = 25; A(Ais25) = 10; ``` Now, for the benchmarks: I used very simple script, varying N and M. ``` tic for i = 1 : M X1 = randi([1 2],N,1); ... % depends on test cases. Result can be in X or A. toc ``` Therefore, it also times randi, but as it is a part of every code it should only mask the relative speed differences, keeping absolute ones the same. Computer is i7 4770k, 32GB RAM. Row vector has 1000 elements, 1M runs; 100M elements, 10 runs; 1B elements, 1 run; 3B elements, 1 run 1. Codes that rely on having just 2 values: * 1I): 18.3 s; 20.7 s; 20.3 s; 63.6 s * 1Z): 33.0 s; 38.2 s; 38.0 s; NA (out of memory) 2. Code relies on lacking one value that can be used for swap: * 2Z): 54.0 s; 60.5 s; 60.0 s; 659 s 3. Code handles arbitrary data, swapping 2 values. * 3A): 45.2 s; 50.5 s; 49.0 s; NA (out of memory) * 3Z): 41.0 s; 46.1 s; 45.8 s; NA (out of memory) So, to summarize, Ibancg's option is much faster and simpler than the rest and should be used if possible (= just those 2 different values in the vector). My 2nd option is far too slow to be relevant. Rather do step by step swap on the vector using any of the general methods. Either general option is fine.
19,711
I am using [this](https://tfhub.dev/google/Wiki-words-250/2) model for word embeddings trained using word2vec, I want to get the embedding using GloVe to compare the performance. The model is trained using the English Wikipedia corpus, nevertheless, I have not found such a dataset online. Does anyone knows where can I find the dataset?
2021/05/11
[ "https://opendata.stackexchange.com/questions/19711", "https://opendata.stackexchange.com", "https://opendata.stackexchange.com/users/28258/" ]
As [one of the comments](https://opendata.stackexchange.com/questions/19681/seeking-elevation-data#comment20067_19681) mentioned, you can use the 30m-resolution data from the [Shuttle Radar Topography Mission](https://en.wikipedia.org/wiki/Shuttle_Radar_Topography_Mission) that can be downloaded from various sites. Specifically for Washington State, you may find it more useful to look at the [list of links to WA elevation data](https://wagda.lib.washington.edu/data/geography/wa_state/#elevation) maintained by the Washington State Geospatial Data Archive, which includes higher-resolution data for parts of the state. Be prepared for the data to come in different formats, though – elevation data are usually stored as spatial rasters so KML is unlikely to be the format they're available in.
Find in this [comment](https://opendata.stackexchange.com/a/19757/1614) information concerning the newly published (2021) Copernicus DEM - Global and European Digital Elevation Model (COP-DEM).
54,615,285
I have function defined for getting the data from JSON and passing it in render. But I had to put 2 different condition to process the data. Below is the function: ``` filterItems = () => { let result = []; const { searchInput } = this.state; const filterbrandsnew = this.props.tvfilter.brand; if (filterbrandsnew) { let value = filterbrandsnew[0].options.map(({catgeory_name})=>catgeory_name); console.log (value); } const brand = value; if (searchInput) { result = this.elementContainsSearchString(searchInput, brand); } else { result = brand || []; } return result; } ``` I want to have the value in this const `const brand = value;` **Accessing the data in render method like below:** ``` render() { const filteredList = this.filterItems(); return ( <div className="filter-options"> <ul className="languages"> {filteredList.map(lang => ( <li className={lang === this.props.selectedLanguage ? 'selected' : ''} onClick={this.props.onSelect.bind(null, lang)} key={lang} > {lang} </li> ))} </ul> </div> ); } ```
2019/02/10
[ "https://Stackoverflow.com/questions/54615285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1328423/" ]
This is quite a common problem with the prevalence of bots. To mitigate this in an efficient manner you can use either of two AWS services that are on offer which can effectively reduce if not completely stop this. 1. Route your traffic through an **Elastic Load Balancer** to the EC2 instance - Elastic Load balance only forwards valid TCP requests. This renders DDoS attacks ineffective since they don't reach your instance. It also has an application load balancer which is of special use to you since it works best with HTTP and HTTPS traffic. It synergises with AWS WAF which can be another defense. 2. **Use AWS CloudFront** - This is a personal favorite approach. Cloudfront is a CDN that distributes traffic across multiple edge locations and filters requests to ensure only valid HTTP/HTTPS reaches the instance. It offers quick connections no matter where the request originates. This makes use of ELB. * This also allows **GeoBlocking** which is something that you stated you wanted. THis will prevent requests from particular geographic locations from being served. * A useful link to a Cloudfront guide that can be followed - <https://aws.amazon.com/blogs/networking-and-content-delivery/dynamic-whole-site-delivery-with-amazon-cloudfront/> Both these approaches effectively let AWS handle the bulk of connection filtering that is required.
From your shared nginx log, there is so many bot service request are come to the EC2 instance. The bot service are trying to crawl your web site like "YandexBot/3.0" may use the EC2 instance bandwidth heavily.
15,059,576
I am trying to enter the first and last name in one string and then display the first and last name on separate lines. I thought the nextLine(); command would work but is not displaying the first and last name on separate lines ``` String full_name; System.out.println("Please enter your first and last name?"); full_name = c.nextLine(); System.out.printf("Your name is: "+ full_name); ```
2013/02/25
[ "https://Stackoverflow.com/questions/15059576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2105902/" ]
You could try ... ``` System.out.print("Your name is: "+ full_name.replace(" ", "\n")); ```
Presuming that `c` is a `Scanner` set to listen to `System.in`, then by virtue of it being on the input stream, it wouldn't have an effect on the output stream. Instead, if you wanted to print the first and last name that was entered, and we presume that a first and last name is separated by a single space (may want logic for middle names), you can write this. ``` String[] brokenName = full_name.split(" "); System.out.printf("Your name is:\n%s\n%s", full_name[0], full_name[1]); ```
10,678,441
I have a boolean list in Python ``` mylist = [True , True, False,...] ``` which I want to change to the logical opposite `[False, False, True , ...]` Is there an inbuilt way to do this in Python (something like a call `not(mylist)` ) without a hand-written loop to reverse the elements?
2012/05/21
[ "https://Stackoverflow.com/questions/10678441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/505306/" ]
The unary tilde operator (~) will do this for a numpy.ndarray. So: ``` >>> import numpy >>> mylist = [True, True, False] >>> ~numpy.array(mylist) array([False, False, True], dtype=bool) >>> list(~numpy.array(mylist)) [False, False, True] ``` Note that the elements of the flipped list will be of type numpy.bool\_ not bool.
``` >>> import operator >>> mylist = [True , True, False] >>> map(operator.not_, mylist) [False, False, True] ```
18,860,620
I'm using ActivePython 2.7.2.5 on Windows 7. While trying to connect to a sql-server database with the pyodbc module using the below code, I receive the subsequent Traceback. Any ideas on what I'm doing wrong? CODE: ``` import pyodbc driver = 'SQL Server' server = '**server-name**' db1 = 'CorpApps' tcon = 'yes' uname = 'jnichol3' pword = '**my-password**' cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=server;DATABASE=db1;UID=uname;PWD=pword;Trusted_Connection=yes') cursor = cnxn.cursor() cursor.execute("select * from appaudit_q32013") rows = cursor.fetchall() for row in rows: print row ``` TRACEBACK: ``` Traceback (most recent call last): File "pyodbc_test.py", line 9, in <module> cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=server;DATABASE=db1;UID=uname;PWD=pword;Trusted_Connection=yes') pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (17) (SQLDriverConnect); [01000] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (53)') ```
2013/09/17
[ "https://Stackoverflow.com/questions/18860620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2668737/" ]
You're using a connection string of `'DRIVER={SQL Server};SERVER=server;DATABASE=db1;UID=uname;PWD=pword;Trusted_Connection=yes'`, you're trying to connect to a server called `server`, a database called `db1`, etc. It doesn't use the variables you set before, they're not used. It's possible to pass the connection string parameters as keyword arguments to the [`connect`](http://code.google.com/p/pyodbc/wiki/Module#connect) function, so you could use: ``` cnxn = pyodbc.connect(driver='{SQL Server}', host=server, database=db1, trusted_connection=tcon, user=uname, password=pword) ```
``` cnxn = pyodbc.connect(driver='{SQL Server}', host=server, database=db1, user=uname, password=pword) print(cnxn) ``` I removed "Trusted\_Connection" part and it worked for me.
12,027,656
For some reason I cannot use functions attached to the object I want to use. I added a comment to the line that is not working. As an error I get "Error; pointer to incomplete class type is not allowed" Please help This is code in dokter.ccp ``` int counter = 0; for (list<Wielrenner*>::iterator it = wielrenners.begin(); it != wielrenners.end(); it++){ Wielrenner* wielrennerOB = *it; cout << "\nID: " << counter; cout << "List size: " << persons.size() << endl; wielrennerOB->print(); // This is not working counter++; } ``` This is code in wielrenner.h ``` #ifndef WIELRENNER_H_ #define WIELRENNER_H_ //#include <fstream> #include "persoon.h" #include "Onderzoek.h" class Wielrenner : public Persoon { public: Wielrenner(string, string, Adres, string, Datum, Datum, string, int, float, float, float,list<Onderzoek>* ); ~Wielrenner(void); int getLengte() const; float getGewicht() const; float getVo2max() const; float getMaxVermogen() const; list<Onderzoek> getOnderzoekenList(); void setLengte(int); void setGewicht(float); void setVo2max(float); void setMaxVermogen(float); void voegOnderzoekToeList(Onderzoek); void showOnderzoeksList(); void setOnderzoeksLijst(list<Onderzoek>&); void print(); void printFile(ofstream&); private: int lengte; float gewicht; float vo2max; float maxVermogen; list<Onderzoek> onderzoeken; }; #endif /* WIELRENNER_H_ */ ``` code in wielrenner.CCP ``` using namespace std; #include <string> #include "Wielrenner.h" /* #include "Onderzoek.h" */ Wielrenner::Wielrenner(string voornaam, string achternaam, Adres adres, string telefoon, Datum datumInDienst, Datum geboorteDatum, string persoonType, int lengte, float gewicht, float vo2max, float maxVermogen,list<Onderzoek>* onderzoeken) : lengte(lengte), gewicht(gewicht), vo2max(vo2max), maxVermogen(maxVermogen), Persoon(voornaam, achternaam, adres, telefoon, datumInDienst, geboorteDatum, persoonType) { } Wielrenner::~Wielrenner(void) { } //setten van gegevens void Wielrenner::setLengte(int newLengte){ lengte = newLengte; } void Wielrenner::setGewicht(float newGewicht){ gewicht = newGewicht; } void Wielrenner::setVo2max(float newVo2max){ vo2max = newVo2max; } void Wielrenner::setMaxVermogen(float newMaxVermogen){ maxVermogen = newMaxVermogen; } void Wielrenner::voegOnderzoekToeList(Onderzoek newOnderzoek){ onderzoeken.push_back(newOnderzoek); } void Wielrenner::showOnderzoeksList(){ int teller=0; for (list<Onderzoek>::iterator it = onderzoeken.begin(); it != onderzoeken.end(); it++){ Onderzoek onderzoekOB = *it; cout << teller << " - "; onderzoekOB.print(); teller++; } } void Wielrenner::setOnderzoeksLijst(list<Onderzoek>& newOnderzoeksLijst){ onderzoeken = newOnderzoeksLijst; } void Wielrenner::print(){ cout << "(" << persoonID << ") Persoon: " << endl; cout << persoonType << endl; cout << voornaam << " " << achternaam << endl; adres.print(); cout << telefoon << endl; cout << "Datum in dienst: "; datumInDienst.print(); cout << "Geboortedatum: "; geboorteDatum.print(); cout << "> Extra wielrenner gegevens: " << endl; cout << "Lengte: " << lengte << endl; cout << "Gewicht: " << gewicht << endl; cout << "vo2max: " << vo2max << endl; cout << "maxVermogen: " << maxVermogen << endl; } void Wielrenner::printFile(ofstream &myfile){ myfile << persoonID << "\n"; myfile << persoonType << "\n"; myfile << voornaam << " " << achternaam << "\n"; adres.printFile(myfile); myfile << telefoon << "\n"; datumInDienst.printFile(myfile); geboorteDatum.printFile(myfile); myfile << lengte << "\n"; myfile << gewicht << "\n"; myfile << vo2max << "\n"; myfile << maxVermogen << "\n"; } // returnen van gegevens int Wielrenner::getLengte() const{ return lengte; } float Wielrenner::getGewicht() const{ return gewicht; } float Wielrenner::getVo2max() const{ return vo2max; } float Wielrenner::getMaxVermogen() const{ return maxVermogen; } list<Onderzoek> Wielrenner::getOnderzoekenList(){ return onderzoeken; } ```
2012/08/19
[ "https://Stackoverflow.com/questions/12027656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1346462/" ]
One thing to check for... If your class is defined as a typedef: ``` typedef struct myclass { }; ``` Then you try to refer to it as `struct myclass` anywhere else, you'll get Incomplete Type errors left and right. It's sometimes a mistake to forget the class/struct was typedef'ed. If that's the case, remove "struct" from: ``` typedef struct mystruct {}... struct mystruct *myvar = value; ``` Instead use... ``` mystruct *myvar = value; ``` Common mistake.
Check out if you are missing some import.
555,418
Electric potential at a point is defined as the amount of work done in bringing a test charge from infinity to that point..my question is that if we don't know where this point of infinity lies then how can we calculate the potential at a point in influence of electric field and if we do know where it lies can you tell me where.. Please also tell me the assumptions while calculating electric potential at a point Also how do we calculate electric potential at a point for practical purposes with respect to a common zero potential point
2020/05/28
[ "https://physics.stackexchange.com/questions/555418", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/265825/" ]
By [Bertrand's theorem,](https://en.wikipedia.org/wiki/Bertrand%27s_theorem) if the strength force is inveresly proportional to the square of the distance then the orbit will be closed, in that will return to the exact same spot each time. Which means that, in this case $$ \dfrac{m}{n} \pi =2\pi$$ Though however, this is only the case for a two body system. When there's three or more bodies this become much more complicated.
In messy systems, like the solar system, orbits aren't closed. When you look at the [this page](https://en.wikipedia.org/wiki/Tests_of_general_relativity#Perihelion_precession_of_Mercury) on wikipedia (Tests\_of\_general\_relativity#Perihelion\_precession\_of\_Mercury) you see that the precession of mercury is only a small part due to general relativity. The majority of the precession is due to interactions with other planets. Here is a table from said page: $$\begin{array}{ll} \textbf{Amount (arcsec/Julian century)} & \textbf{Cause} \\ \text{532.3035 } & \text{Gravitational tugs of other solar bodies } \\ \text{0.0286 } & \text{Oblateness of the Sun (quadrupole moment) } \\ \text{42.9799 } & \text{Gravitoelectric effects (Schwarzschild-like),}\\&\text{ a General Relativity effect } \\ \text{−0.0020 } & \text{Lense–Thirring precession } \\ \text{575.31 } & \text{Total predicted } \\ \text{574.10±0.65 } & \text{Observed } \end{array}$$ From this we can conclude that even without general relativity orbits are not closed. Closed orbits are only an approximation. Classical mechanics only predicts closed orbits when there are two, perfectly spherically symmetric bodies in orbit around each other. In that case the chance of getting a periodic orit is not zero but one, which follows from the equations of motions.
18,933,107
I'm sure this is a duplicate, but I can not find an answer to this. For whatever reason, I can not query my database. Simply I am trying to call a function but I get the error... ``` Warning: mysqli_query() expects parameter 1 to be mysqli, null given in ... on line 12 ``` My dbConnect.php file has ``` $adConn = mysqli_connect("myHost","myUser","myPword","myDB"); ``` My functions.php files has ``` require "dbConnect.php"; // Check connection if (mysqli_connect_errno($adConn)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } //-------------------------------------------------// // Gets total number of games for a given week // //-------------------------------------------------// function GetGamesCount($wID){ $sql = "SELECT * FROM schedule WHERE weekID=$wID"; $gamesRS = mysqli_query($adConn, $sql); $games = mysqli_fetch_array($gamesRS); } ``` I get no error from the connection check, I have tried putting it within the funcation as well. I know I can use the mysqli\_num\_rows function, which I will. I just need to figure out why it won't query the database. I have tried querying with other functions with the same problem. However, if I query within the page or using ajax from a separate file, I have no problems. I just don't see what I'm missing. Any help is greatly appreciated.
2013/09/21
[ "https://Stackoverflow.com/questions/18933107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2802080/" ]
Because `$adConn` is declared outside of the function is not in scope. That means you do not have access to it inside the function. To have access to it you need to pass it as aparameter of the function. ``` function GetGamesCount($wID, $adConn){ ```
`$adConn` is in the global scope and you cannot access it from the function, if you change `$adConn` to `$GLOBALS['adConn']` it should work.
19,474,712
I'm doing a Node.js project that contains sub projects. One sub project will have one Mongodb database and Mongoose will be use for wrapping and querying db. But the problem is * Mongoose doesn't allow to use multiple databases in single mongoose instance as the models are build on one connection. * To use multiple mongoose instances, Node.js doesn't allow multiple module instances as it has caching system in `require()`. I know disable module caching in Node.js but I think it is not the good solution as it is only need for mongoose. I've tried to use `createConnection()` and `openSet()` in mongoose, but it was not the solution. I've tried to deep copy the mongoose instance (<http://blog.imaginea.com/deep-copy-in-javascript/>) to pass new mongoose instances to the sub project, but it throwing `RangeError: Maximum call stack size exceeded`. I want to know is there anyways to use multiple database with mongoose or any workaround for this problem? Because I think mongoose is quite easy and fast. Or any other modules as recommendations?
2013/10/20
[ "https://Stackoverflow.com/questions/19474712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/763868/" ]
One thing you can do is, you might have subfolders for each projects. So, install mongoose in that subfolders and require() mongoose from own folders in each sub applications. Not from the project root or from global. So one sub project, one mongoose installation and one mongoose instance. ``` -app_root/ --foo_app/ ---db_access.js ---foo_db_connect.js ---node_modules/ ----mongoose/ --bar_app/ ---db_access.js ---bar_db_connect.js ---node_modules/ ----mongoose/ ``` In foo\_db\_connect.js ``` var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/foo_db'); module.exports = exports = mongoose; ``` In bar\_db\_connect.js ``` var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/bar_db'); module.exports = exports = mongoose; ``` In db\_access.js files ``` var mongoose = require("./foo_db_connect.js"); // bar_db_connect.js for bar app ``` Now, you can access multiple databases with mongoose.
As an alternative approach, Mongoose does export a constructor for a new instance on the default instance. So something like this is possible. ``` var Mongoose = require('mongoose').Mongoose; var instance1 = new Mongoose(); instance1.connect('foo'); var instance2 = new Mongoose(); instance2.connect('bar'); ``` This is very useful when working with separate data sources, and also when you want to have a separate database context for each user or request. You will need to be careful, as it is possible to create a LOT of connections when doing this. Make sure to call disconnect() when instances are not needed, and also to limit the pool size created by each instance.
35,963
I'm using RESTassured with Java. Getting response in compressed from UTF16 format. Response varies from developer tool to code debugging in Chrome/Firefox, here variation means some character got changed. **Steps:** 1. Loaded the URL 2. Opened developer tool by pressing `F12` 3. Selected the API and checked the response. Here i got response like: `ᯡࡈ䆼̀䬥堰攢䰢\ᙴঠ㙀ழⓒ` 4. Then gone to sources then checked the response it was something like this `ᯡࡈ䆼̀䬥堰攢䰢ᙴঠ㙀ழⓒ` How to handle this? what all the response contains? is it contains headers?
2018/10/09
[ "https://sqa.stackexchange.com/questions/35963", "https://sqa.stackexchange.com", "https://sqa.stackexchange.com/users/13179/" ]
Resolved this issue by following: ``` String x=respe.asString(); JSONParser par = new JSONParser(); String st = (String) par.parse(x); ```
I guess the trivial way to handle this is convert the charset to unicode and verify. Java String supports unicode by-default. The below article states how to convert to and from unicode charset: <http://tutorials.jenkov.com/java-internationalization/unicode.html> Coming to the second part of the question. Below are the major part of an HTTP Response. * Status * Response Header * Response Fields Below is the link which details out http Response: <https://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html>
56,790,261
I use the **pd.pivot\_table()** method to create a user-item matrix by pivoting the user-item activity data. However, the dataframe is so large that I got complain like this: > > Unstacked DataFrame is too big, causing **int32 overflow** > > > Any suggestions on solving this problem? Thanks! ``` r_matrix = df.pivot_table(values='rating', index='userId', columns='movieId') ```
2019/06/27
[ "https://Stackoverflow.com/questions/56790261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11708377/" ]
**Some Solutions:** * You can downgrade your pandas version to 0.21 which is no problem with pivot table with big size datas. * You can set your data to dictionary format like `df.groupby('EVENT_ID')['DIAGNOSIS'].apply(list).to_dict()`
If you want **movieId** as your columns, first sort the dataframe using movieId as the key. Then divide (half) the dataframe such that each subset contains all the ratings for a particular movie. ``` subset1 = df[:n] subset2 = df[n:] ``` Now, apply to each of the subsets ``` matrix1 = subset1.pivot_table(values='rating', index='userId', columns='movieId') matrix2 = subset2.pivot_table(values='rating', index='userId', columns='movieId') ``` Finally join matrix1 and matrix2 using, ``` complete_matrix = matrix1.join(matrix2) ``` On the other hand, if you want ***userId*** as your columns, sort the dataframe using userId as the key and repeat the above process. \*\*\*Please be sure to delete subset1, subset2, matrix1 & matrix2 after you're done or else you'll end up with Memory Error.
59,962
In an alternate history I am designing, France wins the Seven Years War and does not lose their land claims in America. A problem I have reached though is explaining why land east of the Mississippi winds up in American control. How can I explain why the land east of the Mississippi (represented by the red line) would come into American control? [![enter image description here](https://i.stack.imgur.com/OqHCV.png)](https://i.stack.imgur.com/OqHCV.png)
2016/10/29
[ "https://worldbuilding.stackexchange.com/questions/59962", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/11049/" ]
The American Revolution Happened Earlier ---------------------------------------- The reason that the French won the 7 Years War is that the America Revolution happened in the midst of it, and France recognized the territory of the newly independent USA in exchange for a cessation of hostilities on that front.
No explanation needed ===================== These were claims, not territory. There were no permanent French inhabitants, just a few soldiers, traders, and trappers. There were no settlers and families like there was in English North America. If American settlers just moved in an occupied the land, the ownership would resolve itself quickly. Even if the French won the 7 Years war, there was not a mass emigration from France to settle new lands as there was Irish and Scottish settlement in the 13 colonies. The US would have quickly outnumbered the French, with the only remaining dense French settlements around Montreal and New Orleans. It seems almost pre-ordained that American settlement would overtake most of the Ohio Valley, and probably the rest of the Great Plains as well.
102,065
Inspired by Paulo Cereda's [question](https://tex.stackexchange.com/questions/101813/helping-cardinals-elect-the-new-pope) here, I would like to draw tally marks using PSTricks (or TikZ, if no one can help with PSTricks). I have no idea how to start, so I cannot even present a try myself. `:(` (This is not good, I know!) What I would like to have, is a command like `\tallymarks`; ``` \tallymarks{1} \tallymarks{2} ... \tallymarks{10} ``` and get an output like the following: ![wanted](https://i.stack.imgur.com/GJdQo.gif) without the table and the arabic numerals, i.e., only the tally marks themselves. **Update 1** Inspired by Herbert's idea, here is an attempt to use PSTricks. ``` \documentclass{article} \usepackage{pstricks-add} \newcommand*{\tallymarksOne}{ \pslineByHand(0,0)(0,1) } \newcommand*{\tallymarksTwo}{ \pslineByHand(0,0)(0,1) \pslineByHand(0.25,0)(0.25,1) } \newcommand*{\tallymarksThree}{ \pslineByHand(0,0)(0,1) \pslineByHand(0.25,0)(0.25,1) \pslineByHand(0.5,0)(0.5,1) } \newcommand*{\tallymarksFour}{ \pslineByHand(0,0)(0,1) \pslineByHand(0.25,0)(0.25,1) \pslineByHand(0.5,0)(0.5,1) \pslineByHand(0.75,0)(0.75,1) } \newcommand*{\tallymarksFive}{ \pslineByHand(0,0)(0,1) \pslineByHand(0.25,0)(0.25,1) \pslineByHand(0.5,0)(0.5,1) \pslineByHand(0.75,0)(0.75,1) \pslineByHand(-0.75,0)(1,1) } \newcounter{TallyTemp} \def\tallymark#1{% \setcounter{TallyTemp}{#1}% \ifnum#1>5 {\Tally E}\addtocounter{TallyTemp}{-5}% \else{\Tally% \ifcase#1\or \tallymarksOne\addtocounter{TallyTemp}{-1}\or \tallymarksTwo\addtocounter{TallyTemp}{-2}\or \tallymarksThree\addtocounter{TallyTemp}{-3}\or \tallymarksFour\addtocounter{TallyTemp}{-4}\or \tallymarksFive\addtocounter{TallyTemp}{-5}% \fi}% \fi% \ifnum\theTallyTemp>0 \expandafter\tallymark\expandafter{\theTallyTemp}\fi } \begin{document} \tallymark{0} \tallymark{1} \tallymark{2} \tallymark{3} \tallymark{4} \tallymark{5} \tallymark{14} \end{document} ``` When compiling, I get an error: ``` ! Undefined control sequence. \tallymark ...ounter {TallyTemp}{-5}\else {\Tally \ifcase #1\or \tallymarksO... l.50 \tallymark{0} ``` **Update 2** Garbage Coloector's hinted me to the following in the PSTricks manual, but the code won't compile: ``` \documentclass{article} \usepackage{pstricks-add} \def\PstLineFuzzy[#1](#2,#3)(#4,#5)(#6,#7)(#8,#9){% \pscurve[#1](! #2 rand 101 mod 1000 div sub #3 rand 101 mod 1000 div sub) (! #4 rand 101 mod 1000 div sub #5 rand 101 mod 1000 div sub) (! #6 rand 101 mod 1000 div sub #7 rand 101 mod 1000 div sub) (! #8 rand 101 mod 1000 div sub #9 rand 101 mod 1000 div sub)} \def\PstSticks#1{% \multido{\iStick=0+1,\nXA=0.1+0.1,\nXB=-0.5+0.1, \nXC=-0.35+0.10,\nXD=-0.15+0.10}{#1}{% \pst@cnta=\iStick \pst@cnth=\iStick \divide\pst@cnth by 5 \multiply\pst@cnth by 5 \ifnum\iStick>0\relax \ifnum\pst@cnta=\pst@cnth \PstLineFuzzy[linecolor=red]% (\nXB,0.2)(\nXC,0.4)(\nXD,0.6)(\nXA,0.8) \hbox to 0.2\psxunit{} \fi \fi \PstLineFuzzy[](\nXA,0.1)(\nXA,0.4)(\nXA,0.7)(\nXA,1)}} \begin{document} \psset{xunit=0.8,yunit=0.3}% \begin{tabular}{|l|r|p{5.5cm}|} \hline Linux & 27 & \PstSticks{27} \\ \hline Mac OS X & 14 & \PstSticks{14} \\ \hline Windows XP & 43 & \PstSticks{43} \\ \hline \end{tabular} \end{document} ``` The error is ``` ! Undefined control sequence. <inserted text> \pst @cnta=\iStick \pst @cnth=\iStick \divide \pst @cnth by ... l.38 & 27 & \PstSticks{27} \\ \hline ```
2013/03/12
[ "https://tex.stackexchange.com/questions/102065", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/15874/" ]
You mentioned that a Ti*k*Z solution might be acceptable (if Herbert's excellent answer wasn't present). Also, I prefer the "box method" (I din't know if it has a proper name) for such counting tasks, so I did this here. I don't know if the lines ought to be jittery, it could be added, but so far I did not. The command does not break across lines. Code ---- ``` \documentclass[12pt]{article} \usepackage{tikz} \usepackage{xifthen} \begin{document} \newcommand{\tally}[1] { \begin{tikzpicture}[scale=0.5] \pgfmathtruncatemacro{\Rest}{#1} \xdef\GlobalRest{\Rest} \coordinate (temp); \whiledo {\GlobalRest > 9} { \fill (temp) ++ (0.2,0) circle (0.04) ++ (0.5,0) circle (0.04) ++ (0,0.5) circle (0.04) ++ (-0.5,0) circle (0.04); \draw[line cap=round] (temp) ++ (0.2,0) rectangle ++ (0.5,0.5) -- ++ (-0.5,-0.5) ++ (0.5,0) coordinate (temp) -- ++ (-0.5,0.5); \pgfmathtruncatemacro{\Rest}{\GlobalRest-10} %\node[below] at (temp) {\Rest}; \xdef\GlobalRest{\Rest} } \ifthenelse{\GlobalRest > 0} { \fill (temp) ++ (0.2,0) circle (0.04);}{} \ifthenelse{\GlobalRest > 1} { \fill (temp) ++ (0.7,0) circle (0.04);}{} \ifthenelse{\GlobalRest > 2} { \fill (temp) ++ (0.7,0.5) circle (0.04);}{} \ifthenelse{\GlobalRest > 3} { \fill (temp) ++ (0.2,0.5) circle (0.04);}{} \ifthenelse{\GlobalRest > 4} { \draw (temp) ++ (0.2,0) -- ++ (0.5,0);}{} \ifthenelse{\GlobalRest > 5} { \draw (temp) ++ (0.7,0) -- ++ (0,0.5);}{} \ifthenelse{\GlobalRest > 6} { \draw (temp) ++ (0.7,0.5) -- ++ (-0.5,0);}{} \ifthenelse{\GlobalRest > 7} { \draw (temp) ++ (0.2,0.5) -- ++ (0,-0.5);}{} \ifthenelse{\GlobalRest > 8} { \draw (temp) ++ (0.2,0) -- ++ (0.5,0.5);}{} \end{tikzpicture} } \foreach \T in {11,...,20,37,49,54,62,89,243} { Lorem ipsum: \tally{\T} } \end{document} ``` Output ------ [![enter image description here](https://i.stack.imgur.com/eRCxp.png)](https://i.stack.imgur.com/eRCxp.png)
Simplest way I found was to use `\usepackage[misc]{ifsym}` and then use commands `\StrokeFive`, `\StrokeFour`, `\StrokeOne`, etc. accordingly [![enter image description here](https://i.stack.imgur.com/3F60l.jpg)](https://i.stack.imgur.com/3F60l.jpg)
55,521,723
I am trying to sort an array of names alphabetically by using `compareTo()` and a method `String addSort(String name)` but I get an error when compiling at the line "return name", saying that my "variable "name" may not be initialized" when it already is. I've made the method and the code for sorting alphabetically which I think should be correct when using compareTo() as a way of sorting the array. (The array "moreFriends" is a new array which doubles the size of the original array "friends" when it gets full) (Note this is not all of the code) ``` public class SimpleDataStructure{ private String [] friends; private String [] moreFriends; private int counter; public SimpleDataStructure() { friends= new String[5]; counter=0; } ``` ``` public String addSort(){ String name; for(int i = 0; i < moreFriends.length; i++){ for(int j = i + 1; j < moreFriends.length; j++){ if(moreFriends[i].compareTo(moreFriends[j]) > 0){ String temp = moreFriends[i]; moreFriends[i] = moreFriends[j]; moreFriends[j] = temp; } } } System.out.println("Names in sorted order:"); for(int i = 0; i < moreFriends.length -1; i++){ System.out.println(moreFriends[i]); } return name; } ``` ``` public static void main( String [] arg){ SimpleDataStructure sortedfriends = new SimpleDataStructure(); System.out.println(sortedfriends.addSort(name)); } ``` This is the error message I get when i try to compile the program: ``` SimpleDataStructure.java:85: error: variable name might not have been initialized return name; ^ 1 error ``` When I expect the output to eventually be: ``` (unsorted) Kalle Bob Carl Alice Lewis (sorted) Alice Bob Carl Kalle Lewis ```
2019/04/04
[ "https://Stackoverflow.com/questions/55521723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11310989/" ]
The reason that you are getting the compile error is because you never set a value to the `String name` before trying to use it. You should be passing in the value like you have in your description `addSort(String name)`. This will remove that error. I do not see a reason why you are returning the `String` in your function. This function does not appear to add the passed in name either.
You need to include your variable name, that holds the names, inside addSort ``` SimpleDataStructure sorted = new SimpleDataStructure(); System.out.println("Sorted:"); System.out.println(Arrays.toString(sorted.addSort(**HERE**))); ```
43,026
I read the following on the internet: > > According to my present understanding of Dhamma, nobody will be able > to shake my faith. > > > Can a puthujjana (unenlightened commoner still immersed in self instinct) have unshakable faith in the Buddha-Dhamma? What happens if a puthujjana does a meditation retreat and freaks out when in solitude or experiencing ego-death? What are the conditions or criteria for unshakable faith ([acalā saddha](https://suttacentral.net/sn55.51/en/sujato#3.1))?
2020/10/25
[ "https://buddhism.stackexchange.com/questions/43026", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/8157/" ]
Right view arises with two conditions: > > [AN2.126:1.1](https://suttacentral.net/an2.118-129/en/sujato#an2.126:1.1): “There are two conditions for the arising of right view. What two? The words of another and proper attention. These are the two conditions for the arising of right view.” > > > Unshakeable faith happens thus: > > [MN106:13.3](https://suttacentral.net/mn106/en/sujato#mn106:13.3): But sir, what is noble liberation?” “Ananda, it’s when a mendicant reflects like this: ‘Sensual pleasures in this life and in lives to come, sensual perceptions in this life and in lives to come, visions in this life and in lives to come, perceptions of visions in this life and in lives to come, perceptions of the imperturbable, perceptions of the dimension of nothingness, perceptions of the dimension of neither perception nor non-perception; that is identity as far as identity extends. This is the deathless, namely the liberation of the mind through not grasping. > > > Importantly, "perceptions of the imperturbable" are also identity and to be relinquished without grasping. So declaring "I am imperturbable" misses the mark. Better to just walk while walking and just stand while standing. Decades ago I went to a retreat, perceived non-self and freaked out. That was definitely unpleasant, but it was an important clue about the Noble Truths. It's taken a lifetime to muster proper attention and find the words of another. With proper attention and the words of another, one can have faith that the Noble Eightfold Path will give rise to unshakeable faith upon release from all the fetters.
This question is well answered by [MN 27](https://www.accesstoinsight.org/tipitaka/mn/mn.027.than.html) and the commentary of its translator, Ven. Thanissaro. According to the sutta, the one who attains the four jhanas, the knowledge of past lives/ abodes recollection and the knowledge of beings passing away and reappearing, is not yet able to come to the conclusion (i.e. have unshakable faith, or have no doubt at all) regarding the Buddha, the Dhamma and the Sangha: > > "This, too, is called a footprint of the Tathagata, a scratch mark of > the Tathagata, a tusk slash of the Tathagata, but a disciple of the > noble ones **would not yet come to the conclusion**, 'The Blessed One is > rightly self-awakened; the Dhamma is well-taught by the Blessed One; > the Sangha of the Blessed One's disciples has practiced rightly.' > > > However, the sutta continues: > > "With his mind thus concentrated, purified, and bright, unblemished, > free from defects, pliant, malleable, steady, and attained to > imperturbability, the monk directs and inclines it to the knowledge of > the ending of the mental fermentations. He discerns, as it has come to > be, that 'This is stress... This is the origination of stress... This > is the cessation of stress... This is the way leading to the cessation > of stress... These are mental fermentations... This is the origination > of fermentations... This is the cessation of fermentations... This is > the way leading to the cessation of fermentations.' > > > "This, too, is called a footprint of the Tathagata, a scratch mark of > the Tathagata, a tusk slash of the Tathagata. **A disciple of the noble > ones has not yet come to conclusion, but he comes to the conclusion**, > 'The Blessed One is rightly self-awakened; the Dhamma is well-taught > by the Blessed One; the Sangha of the Blessed One's disciples has > practiced rightly.' > > > So, when he fully understands the four noble truths, only then does he come to the conclusion (i.e. have unshakable faith, or have no doubt at all) regarding the Buddha, the Dhamma and the Sangha. But he himself has not yet come to a conclusion, i.e. he is not yet an Arahant. So, what is his attainment at this stage? Ven. Thanissaro, the translator, [comments](https://www.accesstoinsight.org/tipitaka/mn/mn.027.than.html#fn-5): > > This stage in the practice would seem to correspond to reaching > stream-entry, inasmuch as one of the standard definitions of > stream-entry is direct vision of the four noble truths. It is also the > stage at which one reaches unwavering conviction in the Buddha, > Dhamma, and Sangha. > > > The sentence stating that the stream-enterer has come to a conclusion > without coming to conclusion is a play on words. The idiomatic > expression for coming to a conclusion — *ni.t.tha.m gacchati* — can also > mean coming to a finish, reaching completion, or coming to an end. To > distinguish these two meanings, the text here uses the form > *ni.t.tha.ngato* to mean having come to a finish, and *ni.t.tha.m > gacchati* to mean coming to a conclusion. > > > **That means only the one who has gained stream entry could have unshakable faith in the Buddha, the Dhamma and the Sangha.** Then the sutta goes on to describe the Arahant (who comes to a conclusion): > > "His heart, thus knowing, thus seeing, is released from the > fermentation of sensuality, the fermentation of becoming, the > fermentation of ignorance. With release, there is the knowledge, > 'Released.' He discerns that 'Birth is ended, the holy life fulfilled, > the task done. There is nothing further for this world.' > > > "This, too, is called a footprint of the Tathagata, a scratch mark of > the Tathagata, a tusk slash of the Tathagata, and it is here that a > disciple of the noble ones has come to conclusion: 'The Blessed One is > rightly self-awakened; the Dhamma is well-taught by the Blessed One; > the Sangha of the Blessed One's disciples has practiced rightly.'" > > >
17,137,827
If I want to see if one substring equals any of several other substrings. Is this possible to do without putting each case beside each other: Current way: ``` if ( substr.equals("move") || substr.equals("mv") || substr.equals("mov") ){…} ``` Shorter version (not working): ``` if ( substr.equals("move" || "mv" || "mov") ) ```
2013/06/16
[ "https://Stackoverflow.com/questions/17137827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1234721/" ]
I can think of at least 3 different ways to do this: 1. Use a `Set<String>` to hold all the possible matches and use `Set<String>.contains()` in your if statmeent. 2. If you are using JDK 1.7, you can use a `switch` statement: ``` switch (substr) { case "move": case "mv": case "mov": // ... break; } ``` 3. Use a regular expression: ``` if (substr.matches("move|mov|mv") { //... } ```
Try: ``` private static final Set<String> SUBSTRINGS = new HashSet<>(Arrays.asList("move", "mv", "mov")); ... SUBSTRINGS.contains(substr); ```
34,796,901
I know I am not the first to ask about this, but I can't find an answer in the previous questions. I have this in one component ```html <div class="col-sm-5"> <laps [lapsData]="rawLapsData" [selectedTps]="selectedTps" (lapsHandler)="lapsHandler($event)"> </laps> </div> <map [lapsData]="rawLapsData" class="col-sm-7"> </map> ``` In the controller `rawLapsdata` gets mutated from time to time. In `laps`, the data is output as `HTML` in a tabular format. This changes whenever `rawLapsdata` changes. My `map` component needs to use `ngOnChanges` as a trigger to redraw markers on a Google Map. The problem is that `ngOnChanges` does not fire when `rawLapsData` changes in the parent. What can I do? ```js import {Component, Input, OnInit, OnChanges, SimpleChange} from 'angular2/core'; @Component({ selector: 'map', templateUrl: './components/edMap/edMap.html', styleUrls: ['./components/edMap/edMap.css'] }) export class MapCmp implements OnInit, OnChanges { @Input() lapsData: any; map: google.maps.Map; ngOnInit() { ... } ngOnChanges(changes: { [propName: string]: SimpleChange }) { console.log('ngOnChanges = ', changes['lapsData']); if (this.map) this.drawMarkers(); } ``` --- **Update:** `ngOnChanges` is not working, but it looks as though `lapsData` is being updated. In the `ngOnInit` is an event listener for zoom changes that also calls `this.drawmarkers`. When I change the zoom I do indeed see a change in markers. So the only issue is that I don't get the notification at the time the input data changes. In the parent, I have this line. (Recall that the change is reflected in laps, but not in `map`). ```js this.rawLapsData = deletePoints(this.rawLapsData, this.selectedTps); ``` And note that `this.rawLapsData` is itself a pointer to the middle of a large json object ```js this.rawLapsData = this.main.data.TrainingCenterDatabase.Activities[0].Activity[0].Lap; ```
2016/01/14
[ "https://Stackoverflow.com/questions/34796901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1923190/" ]
I stumbled upon the same need. And I read a lot on this so, here is my copper on the subject. If you want your change detection on push, then you would have it when you change a value of an object inside right ? And you also would have it if somehow, you remove objects. As already said, use of changeDetectionStrategy.onPush Say you have this component you made, with changeDetectionStrategy.onPush: ``` <component [collection]="myCollection"></component> ``` Then you'd push an item and trigger the change detection : ``` myCollection.push(anItem); refresh(); ``` or you'd remove an item and trigger the change detection : ``` myCollection.splice(0,1); refresh(); ``` or you'd change an attrbibute value for an item and trigger the change detection : ``` myCollection[5].attribute = 'new value'; refresh(); ``` Content of refresh : ``` refresh() : void { this.myCollection = this.myCollection.slice(); } ``` The slice method returns the exact same Array, and the [ = ] sign make a new reference to it, triggering the change detection every time you need it. Easy and readable :) Regards,
Here's an example using [IterableDiffer](https://angular.io/api/core/IterableDiffer) with ngDoCheck. IterableDiffer is especially useful if you need to track changes over time as it lets you do things like iterate over only added/changed/removed values etc. A simple example not using all advantages of IterableDiffer, but it works and shows the principle: ```ts export class FeedbackMessagesComponent implements DoCheck { @Input() messages: UserFeedback[] = []; // Example UserFeedback instance { message = 'Ooops', type = Notice } @HostBinding('style.display') display = 'none'; private _iterableDiffer: IterableDiffer<UserFeedback>; constructor(private _iterableDiffers: IterableDiffers) { this._iterableDiffer = this._iterableDiffers.find([]).create(null); } ngDoCheck(): void { const changes = this._iterableDiffer.diff(this.messages); if (changes) { // Here you can do stuff like changes.forEachRemovedItem() // We know contents of this.messages was changed so update visibility: this.display = this.messages.length > 0 ? 'block' : 'none'; } } } ``` This will now automatically show/hide depending on myMessagesArray count: ```html <app-feedback-messages [messages]="myMessagesArray" ></app-feedback-messages> ```
615,961
Imagine, a deep empty universe consisting of only one particle muon. Will it decay? As there isn't any change in its surroundings and thus time will lose its meaning. But if the muon will decay in that situation, doesn't it prove that time is something deeper than our experience or what a clock shows!
2021/02/20
[ "https://physics.stackexchange.com/questions/615961", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/285359/" ]
There isn't such a thing as "otherwise empty space". If the quantum fields that permeate spacetime, permit only muons, and no decay to anything else, then only muons can exist. If they permit anything else, eventually some muons will decay (tunnel, transform...) Into some of those other things. Or at least, that's our best current understanding........
A muon is a kind of clock in relativity theory. But in an empty universe there would be no other clock to compare it to and no relativity. . Without relativity the universe as we know it is not defined and cannot exist.The answer to your question is therefore no
19,748,806
Reading a C++ book I encountered the following example on using iterators: ``` vector<string::iterator> find_all(string& s, char c) { vector<string::iterator> res; for(auto p = s.begin(); p != s.end(); ++p) if(*p == c) res.push_back(p); return res; } void test() { string m {"Mary had a little lamb"}; for(auto p : find_all(m, 'a')) if(*p != 'a') cerr << "a bug!\n"; } ``` I'm a little confused about what the vector returned by **find\_all()** contains. Is it essentially "pointers" to the elements of the string **m** created above it? Thanks.
2013/11/03
[ "https://Stackoverflow.com/questions/19748806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1948945/" ]
This answer is 2 years late, still for the benefit of others I'd like to point out that the accepted answer unnecessarily extends from AnyVal. There is just a minor bug that needs to be fixed in the original answer. The `def **` method needs only one parameter, i.e. the exponent as the base is already passed in the constructor and not two as in the original code. Fixing that and removing the backticks results in: ``` import scala.math.pow implicit class PowerInt(i: Int) { def ** (b: Int): Int = pow(i, b).intValue } ``` Which works as expected as seen [here](http://ideone.com/II9KyF). Scala compiler will cast an `Int` to a `PowerInt` *only* if the method that is called on it is undefined. That's why you don't need to extend from AnyVal. Behind the scenes, Scala looks for an implicit class whose constructor argument type is the same as the type of the object that is cast. Since the object can have only one type, implicit classes cannot have more than one argument in their constructor. Moreover, if you define two implicit classes with the same constructor type, make sure their functions have unique signatures otherwise Scala wouldn't know which class to cast to and will complain about the ambiguity.
This is my solution using recursion (so I don't need `import scala.Math.pow`): ``` object RichInt { implicit class PowerInt(val base:Double) { def ** (pow:Double):Double = if (pow==0) 1 else base*(base**(pow-1)) } def main(args:Array[String]){ println(2.0**3.0) //8.0 println(2.0**0.0) //1.0 } } ```
23,628,114
I would like to know if it is possible to generate diagonal lines in css or svg to cover a div which will allow the background colour of the div to show through. Something like the following. If anyone has an example that would be helpful. ![enter image description here](https://i.stack.imgur.com/o7uvz.png)
2014/05/13
[ "https://Stackoverflow.com/questions/23628114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96854/" ]
You can use base64 data as a png image. For example: ``` background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAQElEQVQYV2NkIAKckTrzn5GQOpAik2cmjHgVwhSBDMOpEFkRToXoirAqxKYIQyEuRSgK8SmCKySkCKyQGEUghQD+Nia8BIDCEQAAAABJRU5ErkJggg==); ``` [This is a good generator](http://www.patternify.com/) [An example of it at work](http://jsfiddle.net/J7Pv4/)
There's a tool called stripe generator which solely purposes to create striped images. <http://www.stripegenerator.com/index.php> When done, tweak as required using the following css: ``` .stripes { background-image: url(/assets/images/stripe.png); background-position: 4px 0; background-size: 16px; } ```
601,489
When I started to recover the wifi key using reaver 1.4, after writing the command ``` root@kunjesh-Ideapad-Z570:~/reaver-1.4/src# reaver -i mon0 -b <USSID> ``` it is giving the error ``` Reaver v1.4 WiFi Protected Setup Attack Tool Copyright (c) 2011, Tactical Network Solutions, Craig Heffner <cheffner@tacnetsol.com> [-] Failed to initialize interface 'mon0' [-] Failed to recover WPA key ``` kindly help me.
2015/03/26
[ "https://askubuntu.com/questions/601489", "https://askubuntu.com", "https://askubuntu.com/users/200461/" ]
Had the same problem, and after a few hours I realized that I'm not running reaver as root (run with `sudo`)
mon0 is not a terribly likely name for a wireless interface. I know it's the one in their screenshot, that doesn't mean it's right for your system. Try `ifconfig` to see what yours is called. Incidentally, mine runs with `wlan0` BUT wants to be told my own mac address with `-m` switch, & doesn't like `mon0` at all.
14,376,535
Timestamp data type cannot take or store this date format “ Thursday 17th of January 2013 at 11:47:49 AM “ yet this is the format I would like to store in the db because the client likes that format . I can store it using varchar or text but those data types cannot allow me make some minutes calculations using TIMESTAMPDIFF function . any help please :
2013/01/17
[ "https://Stackoverflow.com/questions/14376535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1984108/" ]
Finally I found a solution. We can use the pm utility for that. If you put any shell script in /etc/pm/sleep.d folder it will be executed automatically just before the system going to sleep and after the system is resumed. The content will be like ``` #!/bin/bash case $1 in suspend) #suspending to RAM /home/harikrishnan/Desktop/sleepd Sleeping ;; resume) #resume from suspend sleep 3 /home/harikrishnan/Desktop/sleepd Woken ;; esac ``` here it will execute the /home/harikrishnan/Desktop/sleepd program with the arguments
AFAIK there's no such signal in Linux, but you can try a) `acpid` daemon hooks, if its present, acpid configs are usually in `/etc/acpi` b) [DBus daemon hooks](https://serverfault.com/questions/191381/what-dbus-signal-is-sent-on-system-suspend), again if its presend on a system c) reading `acpid` sources to see how it gets the signals d) writing your own kernel module
6,024,677
I try (without success) to make a regex for find a submit button even if button code is in one two or more lines. I use now this patter `/<(button|input)(.*type=['\"](submit|button)['\"].*)?>/i` and works fine if the button code is in one line `<input type="submit" name="mybutton" class="button_class" value="Submit" title="Click Me" />` I want to make it work if my button code look like `<input type="submit" name="mybutton"` `class="button_class" value="Submit"` `title="Click Me" />` Thanks
2011/05/16
[ "https://Stackoverflow.com/questions/6024677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/756520/" ]
Add `s` (not `m`) as a [modifier](http://pt2.php.net/manual/en/reference.pcre.pattern.modifiers.php): ``` /<(button|input)(.*type=['\"](submit|button)['\"].*)?>/is ``` > > **s (PCRE\_DOTALL)** > > > If this modifier is set, a dot > metacharacter in the pattern matches > all characters, including newlines. > Without it, newlines are excluded. > This modifier is equivalent to Perl's > /s modifier. A negative class such as > [^a] always matches a newline > character, independent of the setting > of this modifier. > > > --- > > **m (PCRE\_MULTILINE)** > > > By default, PCRE treats the subject > string as consisting of a single > "line" of characters (even if it > actually contains several newlines). > The "start of line" metacharacter (^) > matches only at the start of the > string, while the "end of line" > metacharacter ($) matches only at the > end of the string, or before a > terminating newline (unless D modifier > is set). This is the same as Perl. > When this modifier is set, the "start > of line" and "end of line" constructs > match immediately following or > immediately before any newline in the > subject string, respectively, as well > as at the very start and end. This is > equivalent to Perl's /m modifier. If > there are no "\n" characters in a > subject string, or no occurrences of ^ > or $ in a pattern, setting this > modifier has no effect. > > >
Add `/s` to the end of the regular expression to make `.` match any character, including newlines. It's also a good idea to change greedy `.*` to lazy `.*?` in order to stop it matching whole chunks of the HTML. It's still not recommended to use regex for parsing HTML.
796,768
i am searching for a series with this condition that $\prod 1+a\_n$ converges but $\Sigma a\_n$ diverges. i know that if $a\_n = n^{\frac{1}{2}}$ then $\Sigma a\_n$ diverges but i dont know it is exactly what i want, does $\prod 1+a\_n$ converges? i really don't know how to check the divergence or convergence of a product series. if i'm wrong can anyone tell me such example? thank u
2014/05/16
[ "https://math.stackexchange.com/questions/796768", "https://math.stackexchange.com", "https://math.stackexchange.com/users/115608/" ]
According to the usual definition (as mentioned by Bruno), "convergence" for an infinite product means "convergence of the partial products to a *nonzero* limit". So, assuming $a\_n>-1$ for all $n$, the convergence of $\prod (1+a\_n)$ is equivalent to the convergence of the series $\sum\log(1+a\_n)$. Hence, the question is: to find a sequence $(a\_n)$ such that the series $\sum a\_n$ is divergent but the series $\sum\log(1+a\_n)$ is convergent. Consider the sequence defined by $$a\_n=\frac{(-1)^n}{\sqrt n}+\frac1{2n}\cdot $$ Then $\sum a\_n$ is divergent because $\sum\frac{(-1)^n}{\sqrt n}$ is convergent and $\sum\frac1n$ is divergent. Let us show that, on the other hand, the series $\sum\log(1+a\_n)$ is convergent. By the Taylor expansion for $\log(1+u)$, we may write $$\log(1+a\_n)=a\_n-\frac{a\_n^2}2+O(a\_n^3)\, . $$ Since $\vert a\_n\vert\sim\frac1{\sqrt n}$, the $O(a\_n^3)$ term is $O(1/n^{3/2})$ and hence the corresponding series is convergent. So it is enough to show that the series $\sum(a\_n-\frac{a\_n^2}2)$ is convergent. Now we have \begin{eqnarray}a\_n-\frac{a\_n^2}2&=&\frac{(-1)^n}{\sqrt n}+\frac1{2n}-\frac12\left(\frac1n+\frac{(-1)^n}{n^{3/2}}+\frac1{4n^2} \right) \\&=&\frac{(-1)^n}{\sqrt n}+O\left(\frac1{n^{3/2}}\right) , \end{eqnarray} so the series is indeed convergent, being the sum of a convergent alternating series and an absolutely convergent series.
The [usual definition](http://en.wikipedia.org/wiki/Infinite_product) of convergence for infinite products rules out such a possibility by definition. In any case, if the $a\_n\geq 0$, then the product converges to a finite limit if and only if $\sum a\_n<\infty$. If you consider a product which converges to $0$ to be convergent, then there are examples. For instance $(1-1/2)(1-1/3)\dots$ "converges to $0$", but it is usually considered to be a divergent product for this very reason. Even sillier: $(1-1)(1-1)\dots = 0$ but $1+1+\dots$ diverges.
26,901,466
I'm working on a sidebar for my personal website and I'm looking to show/hide a Facebook follow button when visitors click on a Facebook icon. I am wondering if it is possible with stricly HTML/CSS and if not, what would be the easiest way to do it with JavaScript. I've seen many jQuery solutions around but I have yet to find a purely HTML/CSS one. ``` <div class="sidebar-follow"> <div class="sidebar-follow-icon"> <img src="/follow_facebook.jpg" alt="Follow on Facebook" height="32" width="160"> </div> <div class="sidebar-follow-button"> This is the follow button. </div> </div> ``` Clicking on *.sidebar-follow-icon* should reveal *.sidebar-follow-button* and clicking again on *.sidebar-follow-icon* show hide *.sidebar-follow-button*.
2014/11/13
[ "https://Stackoverflow.com/questions/26901466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2431414/" ]
Html ``` <label for="toggle-1"> Button </label> <input type="checkbox" id="toggle-1"> <div class="facebook"> Facebook Content</div> ``` CSS ``` /* Checkbox Hack */ input[type=checkbox] { position: absolute; top: -9999px; left: -9999px; } label { -webkit-appearance: push-button; -moz-appearance: button; display: inline-block; margin: 60px 0 10px 0; cursor: pointer; } /* Default State */ .facebook { background: green; width: 400px; height: 100px; line-height: 100px; color: white; text-align: center; } /* Toggled State */ input[type=checkbox]:checked ~ .facebook { display: none; } ``` fiddle [Here](http://jsfiddle.net/ucw2x9sb/4/) And more About this [csstricks](http://css-tricks.com/the-checkbox-hack/)
We had a similar need for a CSS-only solution, and found that this works with these conditions: (1) the checkbox "button" and items to be toggled are all within the same overall container, such as body or div or p, and items to be toggled are not separated by being in a sub-container, and (2) the label and checkbox input must be defined ahead of the items to be toggled.
57,220,006
I have been trying to **scrape** user reviews from DM website without any luck. An example page: <https://www.dm.de/l-oreal-men-expert-men-expert-vita-lift-vitalisierende-feuchtigkeitspflege-p3600523606276.html> I have tried to load the product-detail pages with *beautifulsoup4* and *scrapy*. ```py from bs4 import BeautifulSoup import requests url = "https://www.dm.de/l-oreal-men-expert-men-expert-vita-lift-vitalisierende-feuchtigkeitspflege-p3600523606276.html" response = requests.get(url) print(response.text) ``` Running the code shows no content of the reviews- like you'd get from amazon.de! It only shows the scripts from the website. EDIT: From the Dev tool, it can be seen that, the reviwes are stored in JSON in the following folder. This exactly what I am trying to extract. [JSON file to Extract](https://i.stack.imgur.com/FPnZw.jpg)
2019/07/26
[ "https://Stackoverflow.com/questions/57220006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6899607/" ]
I don't have time to play around with the params, but it's all there in the request url to get back that json. ``` import requests import json url = "https://api.bazaarvoice.com/data/batch.json?" num_reviews = 100 query = 'passkey=caYXUVe0XKMhOqt6PdkxGKvbfJUwOPDhKaZoAyUqWu2KE&apiversion=5.5&displaycode=18357-de_de&resource.q0=reviews&filter.q0=isratingsonly%3Aeq%3Afalse&filter.q0=productid%3Aeq%3A596141&filter.q0=contentlocale%3Aeq%3Ade*%2Cde_DE&sort.q0=submissiontime%3Adesc&stats.q0=reviews&filteredstats.q0=reviews&include.q0=authors%2Cproducts%2Ccomments&filter_reviews.q0=contentlocale%3Aeq%3Ade*%2Cde_DE&filter_reviewcomments.q0=contentlocale%3Aeq%3Ade*%2Cde_DE&filter_comments.q0=contentlocale%3Aeq%3Ade*%2Cde_DE&limit.q0=' +str(num_reviews) + '&offset.q0=0&limit_comments.q0=3&callback=bv_1111_19110' url = "https://api.bazaarvoice.com/data/batch.json?" request_url = url + query response = requests.get(request_url) jsonStr = response.text jsonStr = response.text.split('(',1)[-1].rsplit(')',1)[0] jsonData = json.loads(jsonStr) reviews = jsonData['BatchedResults']['q0']['Results'] for each in reviews: print ('Rating: %s\n%s\n' %(each['Rating'], each['ReviewText'])) ``` **Output:** ``` Rating: 5 Immer wieder zufrieden Rating: 5 ich bin mit dem Produkt sehr zufrieden und kann es nur weiterempfehlen. Rating: 5 Super Creme - zieht schnell ein - angenehmer Geruch - hält lange vor - nicht fettend - ich hatte schon das Gefühl, dass meine Falten weniger geworden sind. Sehr zu empfehlen Rating: 5 Das Produkt erfüllt meine Erwärtungen in jeder Hinsicht-ich kaufe es gerne immer wieder Rating: 5 riecht super, zieht schnell ein und hinterlsst ein tolles Hautgefhl Rating: 3 ganz ok...die Creme fühlt sich nur etwas seltsam an auf der Haut...ich konnte auch nicht wirklich eine Verbesserung des Hautbildes erkennen Rating: 4 Für meinen Geschmack ist das Produkt zu fettig/dick zum auftauen. Rating: 1 Ich bin seit mehreren Jahren treuer Benutzer von L'oreal Produkten und habe bis jetzt immer das blaue Gesichtsgel verwendet. Mit dem war ich mehr als zufrieden. Jetzt habe ich die rote Creme gekauft und bin total enttäuscht. Nach ca. einer Stunde entwickelt sich ein sehr seltsamer Geruch, es riecht nach ranssigem Öl! Das ist im Gesicht nicht zu ertragen. ``` .... **Edit:** Ton of cleaning up to do to make this more compact, but here's the basic query: ``` import requests import json url = "https://api.bazaarvoice.com/data/batch.json" num_reviews = 100 payload = { 'passkey': 'caYXUVe0XKMhOqt6PdkxGKvbfJUwOPDhKaZoAyUqWu2KE', 'apiversion': '5.5', 'displaycode': '18357-de_de', 'resource.q0': 'reviews', 'filter.q0': 'productid:eq:596141', 'sort.q0': 'submissiontime:desc', 'stats.q0': 'reviews', 'filteredstats.q0': 'reviews', 'include.q0': 'authors,products,comments', 'filter_reviews.q0': 'contentlocale:eq:de*,de_DE', 'filter_reviewcomments.q0': 'contentlocale:eq:de*,de_DE', 'filter_comments.q0': 'contentlocale:eq:de*,de_DE', 'limit.q0': str(num_reviews), 'offset.q0': '0', 'limit_comments.q0': '3', 'resource.q1': 'reviews', 'filter.q1': 'productid:eq:596141', 'sort.q1': 'submissiontime:desc', 'stats.q1': 'reviews', 'filteredstats.q1': 'reviews', 'include.q1': 'authors,products,comments', 'filter_reviews.q1': 'contentlocale:eq:de*,de_DE', 'filter_reviewcomments.q1': 'contentlocale:eq:de*,de_DE', 'filter_comments.q1': 'contentlocale:eq:de*,de_DE', 'limit.q1': str(num_reviews), 'offset.q1': '0', 'limit_comments.q1': '3', 'resource.q2': 'reviews', 'filter.q2': 'productid:eq:596141', 'sort.q2': 'submissiontime:desc', 'stats.q2': 'reviews', 'filteredstats.q2': 'reviews', 'include.q2': 'authors,products,comments', 'filter_reviews.q2': 'contentlocale:eq:de*,de_DE', 'filter_reviewcomments.q2': 'contentlocale:eq:de*,de_DE', 'filter_comments.q2': 'contentlocale:eq:de*,de_DE', 'limit.q2': str(num_reviews), 'offset.q2': '0', 'limit_comments.q2': '3', 'callback': 'bv_1111_19110'} response = requests.get(url, params = payload) jsonStr = response.text jsonStr = response.text.split('(',1)[-1].rsplit(')',1)[0] jsonData = json.loads(jsonStr) reviews = jsonData['BatchedResults']['q0']['Results'] for k, v in jsonData['BatchedResults'].items(): for each in v['Results']: print ('Rating: %s\n%s\n' %(each['Rating'], each['ReviewText'])) ```
As most modern websites it seems dm.de only loads content through javascript after the page initially loaded. This is problematic because pythons requests library and scrapy only deal with http, but do not load any javascript. The same thing happens on amazon, but there it is detected and you get a javascript-free version. You can try this for yourself by disabling javascript in your browser and then opening the site you want to scrape. Solutions include using a scraper that supports javascript, or scrape using an automated browser (using a full browser also supports js of course). Selenium with chromium worked well for me.
332,006
When editing Stack Exchange posts, a whole ton of them don't have [alt text](https://en.wikipedia.org/wiki/Alt_attribute) on images. Alt text is important so the visually impaired that have to rely on screen readers can experience and value Stack Exchange’s content as much as anyone with normal sight can. To be clear, it is the text you would put instead of *enter image description here* in Markdown: > > `![enter image description here](https://i.stack.imgur.com/1BAIm.png)` > > > A lot of the time, I don't know what to put in the alt text. **How can I write good alt text for my posts?**
2019/08/08
[ "https://meta.stackexchange.com/questions/332006", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/399694/" ]
For me, adding alt text is really important. Historically I didn't understand why it was important but I've since learned better - people accessing the site using screen readers or otherwise text-only should have the best experience that we can offer them, so if you're editing someone's work that has an image and the alt text is the default, it's very much appreciated if you fix that problem. Images and infographics are really succinct ways to convey information to people who aren't visually impaired but you should be certain to cover the same information in the alt text - as much as you can. I generally combine explaining the image in the actual body of the post and adding whatever is missing to the alt text. Let's look at an example that many of you may be familiar with. This is the iconic image we've used for years to help users understand what is an answer and what is not, particularly regarding link-only answers. It's from Shog9's question [Your answer is in another castle: when is an answer not an answer?](https://meta.stackexchange.com/questions/225370/your-answer-is-in-another-castle-when-is-an-answer-not-an-answer) [![Image composed of five images explaining the variety of answer types through fruit. 1. a red apple, labeled "Answer"; 2. an orange, labeled "NOT Answer"; 3. an apple core, labeled "Partial Answer"; 4. a sign with a pictograph of an apple and an arrow pointing up, labeled "NOT answer" representing link-only answers; 5. a half rotted apple with worms in it, labeled "Low-Quality Answer".](https://i.stack.imgur.com/vAUaw.png)](https://i.stack.imgur.com/vAUaw.png) Currently the alt text for this reads: > > A, NAA, A, NAA, VLQ > > > Well... this is... possibly useful to people who know what these letters mean but they don't actually describe the image so that someone who can't see it can benefit from it. Now let's look at the version of the alt text I'm using in this question. > > Image composed of five images explaining the variety of answer types through fruit. 1. a red apple, labeled "Answer"; 2. an orange, labeled "NOT Answer"; 3. an apple core, labeled "Partial Answer"; 4. a sign with a pictograph of an apple and an arrow pointing up, labeled "NOT answer" representing link-only answers; 5. a half rotted apple with worms in it, labeled "Low-Quality Answer". > > > Yes, this is a long description but it actually makes the image useful. Remember, "[a picture is worth a thousand words](https://en.wikipedia.org/wiki/A_picture_is_worth_a_thousand_words)", so sometimes, long descriptions may be necessary. While my description above is long, it doesn't go into unnecessary detail. I don't describe the color of the apples or the arrow. I don't note which have leaves and which do not. They're irrelevant to the image. I could have chosen a set of images with green apples and made the same point. And, this sort of description *is* necessary in Shog's post because he doesn't otherwise explain the image in the question. If the body had included a paragraph like: > > These are our five different answer types. We want the whole apple. The orange is not an answer because we want an apple. The half-eaten apple partial answer is not really going to satisfy us. The pointer to where you can find apples is the equivalent of a link-only answer, which has the risks of link-rot described above. And... the rotten low-quality answer apple just makes us feel ill. > > > It would have been possible (though not necessary) to shorten the alt text and refer to the prior or following paragraph as explanatory. > > An image composed of five images of fruit: a whole apple, an orange, an apple core, a sign pointing out where to find apples and a rotten apple with worms. Further explanation in text. > > > It's good to include any text in the image that is important, as in my long description I noted the labels for each image. Without that text, describing the fruit is less useful. [Recently I was posting screenshots](https://meta.stackexchange.com/questions/329119/logic-behind-automatically-added-se-sites-to-your-communities/329129#329129) of my sock accounts "My Communities" section of the site switcher to illustrate how it works. Here's the image and alt text: [![My site switcher showing Parenting - 83 rep, Computer Science Educators - 46 rep, Meta Stack Exchange - 3 rep, Android Enthusiasts - 1 rep, and Arqade - 1 rep](https://i.stack.imgur.com/UhDoT.png)](https://i.stack.imgur.com/UhDoT.png) > > My site switcher showing Parenting - 83 rep, Computer Science Educators - 46 rep, Meta Stack Exchange - 3 rep, Android Enthusiasts - 1 rep, and Arqade - 1 rep > > > I explain the relevant parts of the image - which sites are listed and my reputation on those sites - but I don't mention the "edit" link or the "more Stack Exchange Communities" or "company blog" because it's not helping to illustrate my point. Now, is this perfect? I'm still assuming that someone knows what a site switcher is... but I'm hoping that, in concert with the rest of the text in the question and answer, this does more than "enter image description here".
I posited a similar question to chat some years ago as I was finding myself creating somewhat elaborate bits of text to describe the picture in the eponymous thousands words or so. I was informed that that was bad form (screen readers sometimes read all of that text in an unskippable manner, and most people won't see it), so most of mine (on the SF&F SE) simply state what the image is (generally something like "Book cover for *Captains of the Universe*") and adding a mention of a salient cover feature if relevant (for example, if someone was looking for a "book about some space-travelers with a cover that had a lizard-man stepping on a woman's head", I might post that with alt-text of "Book cover for *Captains of the Universe*. Cover depicts a lizard-man stepping on a woman's head"). Basically, you want to be informative, but not overwhelmingly so. The alt-text should at least let someone using a screen-reader know what's supposed to be there, ideally providing more information than just "picture showing solution to the question" (maybe, for Puzzling SE, something like "The five colored discs in a straight line in Red Green Yellow Orange Grey order" to say what's actually there).
58,187,763
I have his route defined in app.module ``` {path:'empleados/:año/:mes', component:ListaEmpleadosComponent}, ``` Then in my app.component.ts that bootstrap the application I have this ``` export class AppComponent { tituloPagina = 'Parte de Horas'; fechaActual:Date=new Date(); mesActual:number=this.fechaActual.getMonth(); añoActual:number=this.fechaActual.getFullYear(); } ``` And the template associated: app.component.html ```html <nav class='navbar navbar-expand navbar-light bg-light'> <a class='navbar-brand'>{{tituloPagina}}</a> <ul class='nav nav-pills'> <li><a class='nav-link' [routerLink]="['welcome']">Home</a></li> <li><a class='nav-link' [routerLink]="['/empleados',{{añoActual}}, {{mesActual}}]">Empleados</a></li> <label>{{fechaActual}}</label> </ul> </nav> <div class='container'> <router-outlet></router-outlet> </div> ``` But I get this error Uncaught Error: Template parse errors: Parser Error: Got interpolation ({{}}) where expression was expected at column 20 in [[/empleados/datos/',{{añoActual}}, {{mesActual}}]] in ng:///AppModule/AppComponent.html@5:30 ( Any idea please? Regards
2019/10/01
[ "https://Stackoverflow.com/questions/58187763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3367720/" ]
Your syntax is wrong you should pass variable without the quote like this ``` [routerLink]="['/empleados', añoActual, mesActual]" ``` But I would recommend you change your variable `añoActual` to become alphabet variable witout having speacial character
You should pass the route parameters like this, ``` <a class='nav-link' [routerLink]="['/empleados', añoActual, mesActual]">Empleados</a> ``` Don't analyze the URL. Let the router do it. The router extracts the route parameters from the URL and supplies it to the ListaEmpleadosComponent via the ActivatedRoute service. The router composes the destination URL from the array like this: localhost:4200/empleados/x/y. Reference: <https://angular.io/guide/router#setting-the-route-parameters-in-the-list-view>
19,493,876
I am editing this code from cSipSimple: <https://code.google.com/p/csipsimple/source/browse/trunk/CSipSimple/src/com/csipsimple/ui/incall/InCallCard.java?spec=svn2170&r=2170> And wish to add this method: ``` public void pushtotalk2(final View view) { final boolean on = ((ToggleButton) view).isChecked(); ((ToggleButton) view).setEnabled(false); new Thread(new Runnable() { @Override public void run() { try { Instrumentation inst = new Instrumentation(); if (on) { inst.sendKeyDownUpSync(KeyEvent.KEYCODE_NUMPAD_MULTIPLY); Thread.sleep(500); inst.sendKeyDownUpSync(KeyEvent.KEYCODE_9); Thread.sleep(500); runOnUiThread(new Runnable() { public void run() { ((ToggleButton) view).setBackgroundResource(R.drawable.btn_blue_glossy); ((ToggleButton) view).setEnabled(true); } }); } else { inst.sendKeyDownUpSync(KeyEvent.KEYCODE_POUND); Thread.sleep(500); inst.sendKeyDownUpSync(KeyEvent.KEYCODE_9); Thread.sleep(500); runOnUiThread(new Runnable() { public void run() { ((ToggleButton) view).setBackgroundResource(R.drawable.btn_lightblue_glossy); ((ToggleButton) view).setEnabled(true); } }); } } catch (InterruptedException e) { Log.d(TAG, "Failed to send keycodes: " + e.getMessage()); } } }).start(); } ``` However I get the error: `runOnUiThread(new Runnable(){}) is undefined for the type new Thread(){}` My understanding is that the activity class has this method, but how do I access it from my code? I tried making a constructor and got this error: `Implicit super constructor FrameLayout() is undefined. Must explicitly invoke another constructor` Any ideas on how this is done correctly?
2013/10/21
[ "https://Stackoverflow.com/questions/19493876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1803007/" ]
Since you want to run something in the UI Thread from a non `Activity` class, you can use a `Handler` instead. ``` new Handler().post(new Runnable() { public void run() { ((ToggleButton) view).setBackgroundResource(R.drawable.btn_blue_glossy); ((ToggleButton) view).setEnabled(true); } }); ```
runOnUiThread is not defined for Views. Only for Activities. And InCallCard is just a view. You can use the post(Runnable) method instead of runOnUiThread().
4,267,760
I started using Ant, that ships with Eclipse. It annoys me, that I get hundreds of warnings in the lines of: > > [javac] warning: > java\io\BufferedInputStream.class(java\io:BufferedInputStream.class): > major version 51 is newer than 50, the > highest major version supported by > this compiler. > > [javac] It is recommended that the compiler be upgraded. > > > How do I upgrade compiler?
2010/11/24
[ "https://Stackoverflow.com/questions/4267760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/97754/" ]
Major version 51 is Java 7 - looks like you're developing against a preview Java 7 API library but compiling with a Java 6 javac. Either make sure ant uses the Java 7 compiler, or use a Java 6 API library to compile against.
I solved my warning with answer from Bao. I had JDK1.6 installed before. Then installed JDK1.7 and ant was stil using JKD1.6 for compiling. What I have changed is also set the JDK for the project: right click on project > properties > Java Build Path If you have JDK1.6 here, try to change it to JDK1.7.
289,163
I would like to use the source code of "fill sinks (wang and liu)". I checked through QGIS3 folders, but could not find much related to it. Anyone know where the code could be?
2018/07/11
[ "https://gis.stackexchange.com/questions/289163", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/123876/" ]
Fill Sinks (Wang and Liu) is a QGIS processing algorithm that calls an external (3rd party) tool SAGA. The code to call SAGA is in [SagaAlgorithm.py](https://github.com/qgis/QGIS/blob/master/python/plugins/processing/algs/saga/SagaAlgorithm.py). The source for the SAGA command is either: * [FillSinks\_WL.cpp](https://github.com/saga-gis/saga-gis/blob/master/saga-gis/src/tools/terrain_analysis/ta_preprocessor/FillSinks_WL.cpp) or * [FillSinks\_WL\_XXL.cpp](https://github.com/saga-gis/saga-gis/blob/master/saga-gis/src/tools/terrain_analysis/ta_preprocessor/FillSinks_WL_XXL.cpp)
In addition to the Groovy-based implementation that Chris mentioned (a Whitebox GAT plugin), there is also a newer and more efficient [Rust](https://www.rust-lang.org/en-US/)-based open-source implementation of the Wang and Lui depression filling method available in [`WhiteboxTools`](https://www.uoguelph.ca/~hydrogeo/WhiteboxTools/index.html). The source code for this tool can be found in the `WhiteboxTools` [Github repository](https://github.com/jblindsay/whitebox-tools/blob/master/src/tools/hydro_analysis/fill_depressions.rs). Importantly, `WhiteboxTools` can be run independent of `Whitebox GAT` (i.e. the Whitebox GIS user interface) and can be scripted using Python (See [here](https://www.uoguelph.ca/~hydrogeo/WhiteboxTools/interacting_through_python.html) for details). ```py from WBT.whitebox_tools import WhiteboxTools wbt = WhiteboxTools() dem = "/path/to/data/DEM.tif" output = "/path/to/data/filled_DEM.tif" wbt.fill_depressions(dem, output) ``` Additionally, this Rust-based depression filling tool is available from the [Whitebox for Processing](https://plugins.bruy.me/processing-whitebox.html) QGIS plugin: [![enter image description here](https://i.stack.imgur.com/SIkJM.png)](https://i.stack.imgur.com/SIkJM.png)
17,026,982
I've been trying to pass this array to the function but i keep on getting, **error C2664: 'correctans' : cannot convert parameter 2 from 'std::string [3][3]' to 'std::string \*\*'** , don;t mind the silly questions in the code its just random for testing. code: ``` #include <iostream> #include <string> using namespace std; int correctans(string *arr1, string **arr2, int *arr3, int questions, int choices) { int count=0; int ans; for(int i=0; i<questions; i++) { cout << "Question #" << i+1; cout << arr1[i] << endl; for(int j=0; j<choices; j++) cout << j+1 << arr2[i][j] << " "; cout << "your answer:"; cin >> ans; if(ans==arr3[i]) count++; } return count; } int main() { int correct; string Questions[3]={"HowAreYou", "HowManyHandsDoYouHave", "AreYouCrazyOrCrazy"}; string Choices[3][3]={{"Banana", "Peanut", "Fine"},{"Five", "Two", "One"},{"I'mCrazy", "I'mCrazyBanana", "I'mDoubleCrazy"}}; int Answers[3]={3, 2, 3}; correct=correctans(Questions, Choices, Answers, 3, 3); cout << "You have " << correct << " correct answers" <<endl; return 0; } ```
2013/06/10
[ "https://Stackoverflow.com/questions/17026982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2471413/" ]
Here you go int correctans(string \*arr1, string (&arr2)[3][3], int \*arr3, int questions, int choices)`
Well, as compiler said `std::string [3][3]` can not be converted to `std::string **`. You can try this ``` int correctans(string *arr1, string (* arr2)[ 3 ], int *arr3, int questions, int choices) ``` or this ``` int correctans(string *arr1, string arr2[][ 3 ], int *arr3, int questions, int choices) ``` But better solution is to use `std::vector`.
97,516
I ran sp\_spaceused and Disk Usage by Top Tables standard report for a table. The results for sp\_spaceused are: ***name rows reserved data index\_size unused*** SomeTable <1301755> <7691344 KB> <3931672 KB> <3673840 KB> <85832 KB> However Disk Usage by Top Tables report shows: ``` Table Name # Records Reserved (KB) Data (KB) Indexes (KB) Unused (KB) SomeTable 1.301.755 4.340.216 3.931.672 324.776 83.768 ``` Record count is the same but there is a big gap between the two in terms of space used. sp\_spaceused shows 7.691.344 KB as reserved while the report shows 4.340.216 KB. Which one is correct?
2015/04/10
[ "https://dba.stackexchange.com/questions/97516", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/49056/" ]
Frankly, I wouldn't use either. You can find your biggest tables immediately - with more flexibility - and not worry about where `@updateusage` has been set. ``` CREATE PROCEDURE dbo.TopTables @NumberOfObjects INT = 100, @MinimumSizeInMB INT = 10 AS BEGIN SET NOCOUNT ON; SELECT TOP (@NumberOfObjects) [object] = QUOTENAME(s.name) + N'.' + QUOTENAME(t.name), index_count = COUNT(i.index_id), size_in_MB = SUM(p.reserved_page_count)*8/1024.0 FROM sys.schemas AS s INNER JOIN sys.objects AS t ON s.[schema_id] = t.[schema_id] INNER JOIN sys.indexes AS i ON t.[object_id] = i.[object_id] INNER JOIN sys.dm_db_partition_stats AS p ON t.[object_id] = p.[object_id] AND i.index_id = p.index_id WHERE t.is_ms_shipped = 0 GROUP BY s.name, t.name HAVING SUM(p.reserved_page_count)*8/1024.0 >= @MinimumSizeInMB ORDER BY size_in_MB DESC; END GO ```
This post might give you an alternative approach. I have found sys.database\_files is pretty much reliable. <https://stackoverflow.com/questions/9630279/listing-information-about-all-database-files-in-sql-server> ``` Select DB_NAME() AS [DatabaseName], Name, physical_name, Cast(Cast(Round(cast(size as decimal) * 8.0/1024.0,2) as decimal(18,2)) as nvarchar) Size, Cast(Cast(Round(cast(size as decimal) * 8.0/1024.0,2) as decimal(18,2)) - Cast(FILEPROPERTY(name, 'SpaceUsed') * 8.0/1024.0 as decimal(18,2)) as nvarchar) As FreeSpace From sys.database_files; ```
57,638,226
I added the font-awesome CDN Html link from the website and placed in the head, and still, the icon wouldn't show. I'm new to Html and need specific instructions on how to fix this. I even tried downloading it and linking the file locally but that didn't work. ```html <head> <title>Social Media</title> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> </head> <ul> <li> <i class="fas fa-search"></i> </li> </ul> ```
2019/08/24
[ "https://Stackoverflow.com/questions/57638226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11971117/" ]
The problem here is that the icon `fas fa-search` is from Fontawesome version 5, but you are loading Fontawesome version 4.7. Fontawesome 4.7 has instead the `fa fa-search` icon.
```html <head> <title>Social Media</title> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> </head> <ul> <li> <i class="fa fa-search" style="font-size:30px;"></i> </li> </ul> ``` Please check first what font you are using i mean latest or old there are old 4.7.0 there are different between fa and fas
30,070,810
I ve been learning JQuery, and everything was clear. Until I reached the strings. So far I knew that when you want to call something you do it this way `$('callSomething')`. Now Im learning how to move html elements around, and it was written to call something with double comment lines `$("callSomething")`. I started playing around the code, and I ve noticed that no matter what I will use `' '` or `" "` the code will work. ``` $('#one').after("<p>test</p>"); var $p = $("p"); $("#two").after($p) ``` Now I'm not sure what to use where. I understand that `" "` is used to call Strings. But I could use it to call elements too. My question: Is there a specific reason when to use `' '`? Or should I always use `" "` since its working and save myself the confusion? Any explanation maybe on when to use `' '` and when '" "`(if there is actual difference between them other than calling a string`("< .p>test<./ p >")`? Thank you for your time
2015/05/06
[ "https://Stackoverflow.com/questions/30070810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4801627/" ]
This can help, I wouldn't say there is a preferred method, you can use either. However If you are using one form of quote in the string, you might want to use the other as the literal. ``` alert('Say "Hello"'); alert("Say 'Hello'"); ``` The most likely reason is programmer preference / API consistency. [When to use double or single quotes in JavaScript?](https://stackoverflow.com/questions/242813/when-to-use-double-or-single-quotes-in-javascript)
Both are equivalent, it's mainly a matter of preference and code legibility. If your string contains a single quote, you'll probably want to enclose it in double quotes and vice versa, so you don't have to escape your quotes, e.g. `"It's nice"` vs `'It\'s nice'` or `'And she said "Oh my God"'` vs `"And she said \"Oh my God\""` You can find a more exhaustive answer to that question at <https://stackoverflow.com/a/242833/4604579>
10,490,860
Assume I have an array: ``` $elements = array('foo', 'bar', 'tar', 'dar'); ``` Then I want to build up a `DELETE IN` SQL query: ``` $SQL = "DELETE FROM elements WHERE id IN ('" . implode(',', $elements) . "')"; ``` The problem is that the ids in the elements array aren't quoted each individually. I.E the query looks like: ``` $SQL = "DELETE FROM elements WHERE id IN ('foo,bar,tar,dar'); ``` What's the best, most elegants way to fix this?
2012/05/08
[ "https://Stackoverflow.com/questions/10490860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/425964/" ]
You can run a simple array\_map() function to wrap the strings in quotes and then wrap that around the implode() to add the commas: ``` $array = ["one", "two", "three", "four"]; implode(",", array_map(function($string) { return '"' . $string . '"'; }, $array)); ```
You can do like this as well ``` $elements = array('foo', 'bar', 'tar', 'dar'); $data = '"' . implode('", "', $elements) . '"'; echo $data; // "foo", "bar", "tar", "dar" ```
50,974
Sometimes I hear examples of paradoxes, like The Grandfather Paradox: if you went back in time and killed your grandfather then you wouldn't have been born, so you couldn't go back to kill your grandfather, which means you couldn't have killed your grandfather, so you would have been born so you could go back and kill him, etc. Whenever I've heard other people interpret paradoxes, they have always seemed to interpret a paradox as a problem that needed to be solved, they seemed to put effort into looking deeper and finding a way that you could, for example, go back to kill your grandfather. For me, paradoxes seem like a simple counterexample, or a proof against an idea. When I hear an example like the grandfather paradox, I interpret it as a counterexample to "going back in time", or a proof that "going back in time" is not possible. So I think that paradoxes are counterexamples, while other people seem to think that paradoxes are problems that need to be solved. Are these other people irrational? Or am I missing something?
2018/04/13
[ "https://philosophy.stackexchange.com/questions/50974", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/-1/" ]
The Grandfather paradox comes up in science fiction. There are four solutions that I found in science fiction: 1. The time loop. You go back in the past, make changes, and somehow the changes affect the future in exactly the right way to make you go back in the past, make the same changes etc etc etc. 2. The impossibility. Not the impossibility of time travel, but the impossibility of making the change. You can go back in the past, but something, somehow will prevent you from killing your grandfather. 3. Multiple universes. You don't travel back in time, but you travel into a different universe that looks exactly like ours 50 years ago. Since it is a different universe, there is no paradox. In half the universes a visitor killed your grandfather so you don't even exist. In the other half you visit another universe and kill someone there looking like your grandfather. 4. The laws of physics don't like it. You try to build a time machine, something will destroy it. If necessary, your sun turns into a nova and wipes out your planet including the time machine. If you put the plans on a spaceship and sent it off to a neighbouring star, more novae and more planets wiped out. The time machine won't be built.
The Grandfather paradox is not actually a paradox because that situation is not possible. Time travel is a movie concept and that's it. "Going back in time" is not possible not due to a possible paradox resulting from that but because time is was a concept created to be able to measure the speed differences in state changes, it is a logical construct using various measurements in order to sequence events. Also, there is no such thing as time dilation. Time was conceived as constant exactly so we have a good scale for measuring differences. In Einstein's formulas, it is not the time that varies it is the space that compresses or decompresses in situations of different gravimetric interactions. Time cannot be altered because it is not a physical construct but a conceptual one. A ruler that has centimeters on it, although it was designed also as a measurement system can be altered because it is a physical object. For example it will contract or compress because of temperature variations. Therefore, I can say that time travel in an absurd concept (and more and more scientists agree to this), it's like saying we can do a 'current travel' in a wire. I also do not consider Schroedinger's Cat a paradox. In that case it's all about how you display the problem. Not knowing a result does not mean it is in both states, it means you just don't know it's state. Think of a school test. You do the test, but you do not know the result. The professors checks the test and gives you the score accordingly. That's the end of it. You obtained a score (let's say 90) based on what you completed on a paper. That cannot change. The paper sits in the professor's desk with the score on it. The fact that you are not yet informed of your score and that you can assume you either got a 90 or an 80 does not change anything, does not influence the result and does not mean you have both 90 and 80. Therefore, your knowledge about the state of the Cat is irrelevant for the Cat. So as you can see, to use a paradox as a counter-argument it must first not be a pseudo-paradox.
59,490,169
I am trying to mock `resultset` in scala using mockito like below `val resultset = mock[java.util.ResultSet]` However when i try to mock `getString` method like below i am getting **ambiguous reference to overloaded definition error** as getString can accept either string or int `(resultset.getString _).expects(any[String]).returns("test")` what could be the issue?
2019/12/26
[ "https://Stackoverflow.com/questions/59490169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7688538/" ]
This is an known issue with Java/Scala interop, please migrate to [mockito-scala](https://github.com/mockito/mockito-scala) which solves it. Then you can use the examples amer has posted (just use the methods from the traits and not from the `Mockito` class) or you can try the scala syntax ``` resultset.getString(*) returns "test" ```
Try something like this maybe: ``` Mockito.when(resultset.getString(any())) thenReturn "test" ``` or ``` Mockito.when(resultset.getString(anyString())) thenReturn "test" ```
1,113,353
``` - (void)mouseDragged:(NSEvent *)theEvent { NSSize dynamicImageSize; dynamicImageSize = [[self image] size]; NSSize contentSize = [(NSScrollView*)[[self superview] superview] contentSize]; if(dynamicImageSize.height > contentSize.height || dynamicImageSize.width > contentSize.width) { float x = startOrigin.x - ([theEvent locationInWindow].x - startPt.x); float y = startOrigin.y - ([theEvent locationInWindow].y - startPt.y); [self scrollPoint:NSMakePoint(x, y)]; } } ``` In the above code I need to animate the scrolling. How can I achieve this? Thanks.
2009/07/11
[ "https://Stackoverflow.com/questions/1113353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132117/" ]
In my app, I set the `clipView`'s `boundsOrigin` using its animator: ``` [NSAnimationContext beginGrouping]; NSClipView* clipView = [[myView enclosingScrollView] contentView]; NSPoint newOrigin = [clipView bounds].origin; newOrigin.x = my_new_origin.x; [[clipView animator] setBoundsOrigin:newOrigin]; [NSAnimationContext endGrouping]; ```
I'm not sure if this is a supported animation type, but have you tried calling through the `animator` proxy object? eg. `[[self animator] scrollPoint:NSMakePoint(x, y)];`
1,311,810
So I'm looking to modify the CLSQL abstractions to suit my own needs. I've been using the clsql-sys package and that's suited most of my needs. However, I can't seem to find how to get a list of field names and field types from the result set. In fact, I just seem can't to find anything ANYWHERE to get types (names I can just hack into the database-query-result-set method.) Any help would be much appreciated, especially on the types. thanks! Jieren
2009/08/21
[ "https://Stackoverflow.com/questions/1311810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/118843/" ]
You do: ``` .article { margin-left: 100px; /* example */ } .col-left { width: 100px; /* same as margin-left above, might not work with percentage */ } ```
may be add clear: right; to .col-left? --edited You can pack all divs on the right in a new div called .col-right and make it floats right aswell as giving it a width property. Then add clear:right; to your .col-left style. That would have the effect that the right column won't continue under the left one. I tested it with Firebug and it worked.
28,030,268
when I insert an array in the db, I get the error "unidentified index" in some of the variables even though they all have their corresponding values. Tried using print\_r, and it returned an array with values, but when I try to insert the array, the values become null. I dont understand why and I can't see the error in my code. here's my controller ``` public function test() { if($this->session->userdata('logged_in')) { $session_data = $this->session->userdata('logged_in'); $user_id = $session_data['user_id']; $table_id = $this->input->post('table'); $start = $this->input->post('start'); $end = $this->input->post('end'); $query = $this->process_resto_list->test($table_id); if ($query->num_rows() > 0) { $row = $query->row(); $resto_id = $row->resto_id; $table_number= $row->table_number; $table_size = $row->table_size; } //$resto_id = $session_data['user_id']; $values = array( 'resto_id' => $resto_id, 'diner_id' => $user_id, 'date' => $this->input->post('date'), 'start_time' => $start, 'end_time' => $end, 'table_number' => $table_number, 'number_of_people' => $table_size, ); if($this->process_resto_list->insert_reservation($values)) redirect('reservation_test/reservation', 'location'); //print_r($values); } ``` Here's my model ``` public function insert_reservation($values) { date_default_timezone_set("Asia/Manila"); $data = array( 'resto_id' => $values['resto_id'], 'diner_id' => $values['user_id'], 'date' => date('Y-m-d'), 'start_time' => $values['start'], 'end_time' => $values['end'], 'table_number' => $values['table_number'], 'number_of_people' => $values['table_size'], ); return $this->db->insert('resto_reservations', $data); } ``` When using print\_r here's the result of the array > > Array ( [resto\_id] => 9 [diner\_id] => 14 [date] => [start\_time] => 11:00 [end\_time] => 13:00 [table\_number] => 6 [number\_of\_people] => 4 ) > > > Please help me point out the error. Thank you
2015/01/19
[ "https://Stackoverflow.com/questions/28030268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3400419/" ]
In your model. Change values as follows ``` $data = array( 'resto_id' => $values['resto_id'], 'diner_id' => $values['diner_id'], 'date' => date('Y-m-d'), 'start_time' => $values['start_time'], 'end_time' => $values['end_time'], 'table_number' => $values['table_number'], 'number_of_people' => $values['number_of_people'], ); ```
I just replaced my model with this. Thanks everyone! ``` $data = array( 'resto_id' => $values['resto_id'], 'diner_id' => $values['diner_id'], 'date' => date('Y-m-d'), 'start_time' => $values['start_time'], 'end_time' => $values['end_time'], 'table_number' => $values['table_number'], 'number_of_people' => $values['number_of_people'], ); ```
18,710,734
I am new to android development and I was just wondering how can I create three evenly spaced buttons at the bottom of the screen. I was also wondering what style I could use to make these buttons appear neat and tidy. The code I have written so far. ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="fill_parent" android:orientation="vertical" > <LinearLayout android:layout_width="wrap_content" android:layout_height="0dip" android:layout_weight="1" android:orientation="vertical"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/Fragment1" android:id="@+id/worldTextView" /> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/Button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/Button1" /> <Button android:id="@+id/Button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/Button2" /> <Button android:id="@+id/Button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/Button3" /> </LinearLayout> ```
2013/09/10
[ "https://Stackoverflow.com/questions/18710734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2318535/" ]
Keep your three button in a different layout(Linear layout with orientation horizontal) at the bottom and give weight to each button and layout\_width as zero.
**Try this way** ``` <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/Button1" android:layout_width="0dp" android:layout_height="wrap_content" android:text="@string/Button1" android:layout_weight="1" /> <Button android:id="@+id/Button2" android:layout_width="0dp" android:layout_height="wrap_content" android:text="@string/Button2" android:layout_weight="1" /> <Button android:id="@+id/Button3" android:layout_width="0dp" android:layout_height="wrap_content" android:text="@string/Button3" android:layout_weight="1" /> </LinearLayout> ```
11,905
Q: How can I best search the web for **exact** LaTeX commands (e.g., `\show` as opposed to `show`)? It appears that Google will not allow us to escape the `\` character. So, searches for `\show` are interpreted as `show`. Needless to say, results would be tremendously more helpful if the search were interpreted as the former. (note: `"\show"` doesn't help either) Q: Has anyone had success searching LaTeX commands using **other** search engine? More generally, does anyone know of search engines that are particularly well-suited for searching non-standard characters?
2011/02/24
[ "https://tex.stackexchange.com/questions/11905", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/3762/" ]
[Google code search](http://www.google.com/codesearch) will let you search by regular expression and, if you like, restrict your search to TeX/LaTeX source files only.
You can use this site: <http://detexify.kirelabs.org/classify.html> This site is really handy as you can just draw the symbol and it guesses perfectly.
69,741,870
I'm trying to compare time pasted to form with time saved in DB for deleting this record. I don't understand why it's not working when in DB is stored `8:15:00` and the user pasted `08:15`. The field in DB is `TimeField` and for comparing I'm using `.filter(time__contains=t)` where `t` is string pasted from form. Only difference is in zero before 8. When in DB is it stored like `08:15:00`, all is working. ```py class WateringSchedule(models.Model): time = models.TimeField() t = '08:15' print(WateringSchedule.objects.filter(time__contains=t).count()) ``` Thanks.
2021/10/27
[ "https://Stackoverflow.com/questions/69741870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14986336/" ]
I've only seen [`contains`](https://docs.djangoproject.com/en/3.2/ref/models/querysets/#contains) used with `CharField`. There is no reason to use it here. Just use the field name: ``` print(WateringSchedule.objects.filter(time=t).count()) ``` Here I assume Django will parse the input string into a `datetime.time` object. You may need to use `strptime()` to do so manually. Alternatively, you can use [`hour`](https://docs.djangoproject.com/en/3.2/ref/models/querysets/#hour) and [`minute`](https://docs.djangoproject.com/en/3.2/ref/models/querysets/#minute).
You should try `icontains` instead of `contains`.
799,731
I want to create a method that changes enabled property. How do I pass the contorl name and property to a method. If the following were my original method: ``` public void ChangeProperties() { btnAcesScore.Enabled = true; } ``` I want to be able to change the "btnAcesScore" each time I call this method. How do I pass this to the method. I tried passing it as a string but that doesn't work. Here is what I tried: ``` public void ChangeProperties(string category) { category = true; } ChangeProperties("btnAcesScore.Enabled"); ``` Susan
2009/04/28
[ "https://Stackoverflow.com/questions/799731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Try this : ``` public void ChangeProperties(Control ctrl) { ctrl.Enabled = true; } ``` and call it like that : ``` ChangeProperties(btnAcesScore); ```
``` Main() { ChangeProperties(ref category,True); //Where Category is the ID of the Textbox control i.e <asp:textbox ID="Category "></textbox> } public void ChangeProperties(ref TextBox category,bool val) { category.Enabled = val; } ```
29,794,553
I have two vectors ``` x <- c(2, 3, 4) y <- rep(0, 5) ``` I want to get the following output: ``` > z 2, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0 ``` How can I create `z`? I have tried to use `paste` and `c` but nothing seems to work. The only thing I can think of is using a `for()` and it is terribly slow. I have googled this and I am sure the solution is out there and I am just not hitting the right keywords. UPDATE: For benchmarking purposes: Using Nicola's solution: ``` > system.time( + precipitation <- `[<-`(numeric(length(x)*(length(y)+1)),seq(1,by=length(y)+1,length.out=length(x)),x) + ) user system elapsed 0.419 0.407 0.827 ``` This is ridiculously fast! I must say! Can someone please explain this to me? My `for()` which I know is always wrong in `R` would have taken at least a day if it even finished. The other suggestions: ``` > length(prate) [1] 4914594 > length(empty) [1] 207 > system.time( + precipitation <- unlist(sapply(prate, FUN = function(prate) c(prate,empty), simplify=FALSE)) + ) user system elapsed 16.470 3.859 28.904 ``` I had to kill ``` len <- length(prate) precip2 <- c(rbind(prate, matrix(rep(empty, len), ncol = len))) ``` After 15 minutes.
2015/04/22
[ "https://Stackoverflow.com/questions/29794553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3458788/" ]
You could also try to vectorize as follows ``` len <- length(x) c(rbind(x, matrix(rep(y, len), ncol = len))) ## [1] 2 0 0 0 0 0 3 0 0 0 0 0 4 0 0 0 0 0 ``` A more compact, but potentially slower option (contributed by @akrun) would be ``` c(rbind(x, replicate(len, y))) ## [1] 2 0 0 0 0 0 3 0 0 0 0 0 4 0 0 0 0 0 ```
Here's another way: ``` options(scipen=100) as.numeric(unlist(strsplit(as.character(x * 10^5), ""))) ``` And some benchmarks: ``` microbenchmark({as.numeric(unlist(strsplit(as.character(x*10^5), "")))}, {unlist(t(matrix(c(as.list(x),rep(list(y),length(x))),ncol=2)))}, {unlist(sapply(x, FUN = function(x) c(x,y), simplify=FALSE))}, times=100000) Unit: microseconds expr { as.numeric(unlist(strsplit(as.character(x * 10^5), ""))) } { unlist(t(matrix(c(as.list(x), rep(list(y), length(x))), ncol = 2))) } { unlist(sapply(x, FUN = function(x) c(x, y), simplify = FALSE)) } min lq mean median uq max neval 9.286 10.644 12.15242 11.678 12.286 1650.133 100000 9.485 11.164 13.25424 12.288 13.067 1887.761 100000 5.607 7.429 9.21015 8.147 8.784 30457.994 100000 ``` And here's another idea (but it seems slow): ``` r = rle(1) r$lengths = rep(c(1,5), length(x)) r$values = as.vector(rbind(x, 0)) inverse.rle(r) ```
18,480,521
I have create a sample program in Asp.net which updates time on a button click. This time is shown in a label. Button and and label both are inside update panel say upd1. Following is the aspx code ``` <script type="text/javascript" > function fnhn() { __doPostBack("upd1",""); return false; } </script> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager id="ScriptManager1" runat="server" EnablePageMethods ="true" > </asp:ScriptManager> <div> <asp:UpdatePanel ID="upd1" runat ="server" ><ContentTemplate > <asp:label runat="server" id="lbl_c" ></asp:label> <asp:button runat="server" id="btn_b" Text="Click" /> </ContentTemplate> </asp:updatepanel> </div> </form> </body> ``` and following is the source code. ``` Partial Class _Default Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load lbl_c.Text = Date.Now.ToString End Sub End Class ``` Now problem which i facing is as follows. I am able to update this time on button click without any postback in any browser other than IE 10. In IE10 my whole page gets refresh. which I obviously dont want to happen. Plz help me guys. In a thread I also come to know about up leveling the user agent of IE10 through following. ``` Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init If Request.UserAgent.ToLower.ToString.Contains("msie 10.0") Then Page.ClientTarget = "uplevel" End If End Sub ``` Which didnt help me to come out of this issue. Any comment suggestion and solution is valuable.
2013/08/28
[ "https://Stackoverflow.com/questions/18480521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/833228/" ]
1. Add new numeric column. 2. Copy from old char column to new column with trim and conversion. 3. Drop old char column. 4. Rename numeric column to old column name. This worked for me (with decimals but I suppose it will work with ints): ``` alter table MyTable add MyColNum decimal(15,2) null go update MyTable set MyColNum=CONVERT(decimal(15,2), REPLACE(LTRIM(RTRIM(MyOldCol)), ',', '.')) where ISNUMERIC(MyOldCol)=1 go alter table MyTable drop column MyOldCol go EXEC sp_rename 'MyTable.MyColNum', 'MyOldCol', 'COLUMN' go ```
1. *Create a temp column* `ALTER TABLE MYTABLE ADD MYNEWCOLUMN NUMBER(20,0) NULL;` 2. *Copy and casts the data from the old column to the new one* `UPDATE MYTABLE SET MYNEWCOLUMN=CAST(MYOLDCOLUMN AS NUMBER(20,0));` 3. *Delete the old column* `ALTER TABLE MYTABLE DROP COLUMN MYOLDCOLUMN;` 4. *Rename the new one to match the same name as the old one.* `ALTER TABLE MYTABLE RENAME COLUMN MYNEWCOLUMN TO MYOLDCOLUMN;`
22,867
From *Spiegel Magazine*: > > Das ist eine Vermutung, nicht unbegründet, aber eben eine Vermutung. Um **sich** der Wahrheit weiter anzunähern, wird es auf die Ermittler ankommen. > > > Am I correct in understanding that **sich** here is impersonal, i.e., does not refer to anyone in particular? Is it similar to something like the following? > > Es ist nicht einfach, **sich** so etwas vorzustellen. > > >
2015/04/15
[ "https://german.stackexchange.com/questions/22867", "https://german.stackexchange.com", "https://german.stackexchange.com/users/5478/" ]
If you aim at an ironic effect (not a literal translation), you can also say > > Nicht so zahlreich! > > >
You may also say "Ist ja wie auf einer Beerdigung hier." which is a sloppy phrase for the mood/silence is like being on a funeral where there shouldn't be.
26,403
I know he wears a hat on the cover of every book in the series. But, does it ever actually mention him wearing a hat in the books?
2012/11/01
[ "https://scifi.stackexchange.com/questions/26403", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/6911/" ]
The [publisher is responsible for the hat](http://www.tor.com/blogs/2008/07/chris-mcgrath-and-the-dresden-files). The logic was evidently 'Wizard + P.I. = Duster, Staff, Fedora.' The fact that this contradicts the book is a non-issue for them - cover art is more a marketing item than anything else and the author has little to no say in it. Jim has mentioned this in Q&A Sessions: > > I INTRODUCED THE NOVELS TO MY FIANCEE WHO IMMEDIATELY CONSUMED ALL OF THEM [IN THE SPACE OF A WEEK?] AND AT THE END OF IT SHE LOOKED AT ME AND SHE SAID "I REALLY LOVE THESE NOVELS BUT - WHY IN THE COVER ART DOES HE WEAR A HAT? > > > What's with Dresden's hat in the cover art is the question - the answer to that is the art department thought it was a good idea. They thought it was the perfect visual shorthand for wizard detective - he's got a wizard staff and he's got a detective fedora - wizard/detective right there. So that's what they wanted and that's what they got. And they said - Jim, you approve of this -right?!?! [Laughter] > > > Word is the Dresden Files cover artist (Chris McGrath) has become a fan of the books after doing the first few covers, and understands that the hat is contradictory. At this point it's a bit of an in-joke for fans, and the line in Changes was a reference to the covers. Unfortunately the Jim Butcher forums where I read this has had an upgrade (or crash, or something) and none of the old topics that had quotes regarding this are still around. [There](http://www.jimbutcheronline.com/bb/index.php/topic,34533.0.html) [are](http://www.jimbutcheronline.com/bb/index.php/topic,34077.msg1598884.html) [plenty](http://www.jimbutcheronline.com/bb/index.php/topic,34265.msg1616319.html) of [un-cited](http://www.jimbutcheronline.com/bb/index.php/topic,22558.msg1325940.html#msg1325940) comments about it though.
HE DOESN'T WEAR A HAT! EVER! He categorically states that he hates them several time throughout several books- I think due to the black hood on his head during the trial re Justin DuMornes death and subsequent doom of damacales as his sentence note he rips the hood of molly during her trial and always says how his head is unprotected unlike what he gets from his duster the hat may be coming as an extra 'mantle' of the winter knight but it's not here yet. In summary. No hat.
47,665,410
I am trying to push items from one Array to another depending on the order that is supplied. Essentially i have a 2d array with a name and a price : ``` var myArray = [['Apples',22],['Orange',55],['Berry',23]]; ``` Another array with the order it should be in : ``` var myOrder = [0,2,1]; ``` My resulting array would look like this : ``` var finalArray = [['Apples',22],['Berry',23],['Orange',55]] ``` My initial thought process was to loop through myArray and loop through myOrder , store the object temporary at a specified index in myOrder then push to final array. I think i am over thinking it a bit, i made several attempts but with no luck whatsoever. Any help would be greatly appreciated!
2017/12/06
[ "https://Stackoverflow.com/questions/47665410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7516811/" ]
This is a simple `map()` that doesn't require anything else ```js var myArray = [['Apples',22],['Orange',55],['Berry',23]]; var myOrder = [0,2,1]; let final = myOrder.map(i => myArray[i]) console.log(final) ```
``` function reorder(arr, order) { return order.map(function(i) { return arr[i]; }); } var myArray = [['Apples',22],['Orange',55],['Berry',23]]; var myOrder = [0,2,1]; reorder(myArray, myOrder); // => [["Apples",22],["Berry",23],["Orange",55]] ```
51,530
I am learning solidity & web3js and am able to make a decent DAPP with it using ReactJS as front end. Most of the online tutorials, online blogs etc - they all show very simple DAPP like this which are easy to explain. But in real life applications should be very complex in nature. For ex: Lets assume I am creating a dapp in which I am interested in storing user's demographic information as well + additional info.I do not think ethereum is the right place for that. How to handle such cases?
2018/06/19
[ "https://ethereum.stackexchange.com/questions/51530", "https://ethereum.stackexchange.com", "https://ethereum.stackexchange.com/users/40597/" ]
If it is text information surely you can store it on Ethereum. Represent it the way you want using structs and maps or arrays (whatever you are looking for) and code them in Solidity. Web3.js is a very useful library to interact with you Ethereum node and invoking smart contracts. You will be able to get a lot of information related to your transactions. Storing images on the other hand on Ethereum will be costly if that is what you are looking for. If you want to store it on the private chain sure go ahead but the more efficient solution to that is IPFS which you can integrate with the blockchain text data on your DApp. You can always make complex DApps but your architecture should always cater for what the smart contracts can store. Depending on what Transaction/second speed you need, you will have to think about Ethereum and handle a lot of load balancing and buffers depending on your use case. Quorum is a fork of ethereum and is a lot faster so if you are looking to push transactions really fast then Quorum is a good choice. If you already know Ethereum learning Quorum would be not that difficult. Think about your use cases, think about what Solidity has to offer and IPFS club them using web3js and sky is the limit my friend.
Depends on your requirements: 1. If you want to guarantee (without any centralized authority) that the data is stored and is accessible, you the best place would be logs and events- it's a cheap storage than the contract memory in the blockchain itself. 2. If it's all for your app's requirements and you control a given storage (your server, your hdd, user's phone/ browswer) then just store it there. Using a blockchain for everything is just an overkill. 3. Or as @Smalik suggested, use a local blockchain- but do ask yourself if you really need it? The security of a blockchain doesn't come from its functionalities- if it's private blockchain then it's no more secure than a normal storage with so much complexity and performance issues.
59,218,057
I have multiple .xls (~100MB) files from which I would like to load multiple sheets (from each) into R as a dataframe. I have tried various functions, such as `xlsx::xlsx2` and `XLConnect::readWorksheetFromFile`, both of which always run for a very long time (>15 mins) and never finish and I have to force-quit RStudio to keep working. I also tried `gdata::read.xls`, which does finish, but it takes more than 3 minutes per one sheet and it cannot extract multiple sheets at once (which would be very helpful to speed up my pipeline) like `XLConnect::loadWorkbook` can. The time it takes these functions to execute (and I am not even sure the first two would ever finish if I let them go longer) is way too long for my pipeline, where I need to work with many files at once. Is there a way to get these to go/finish faster? In several places, I have seen a recommendation to use the function `readxl::read_xls`, which seems to be widely recommended for this task and should be faster per sheet. This one, however, gives me an error: ``` > # Minimal reproducible example: > setwd("/Users/USER/Desktop") > library(readxl) > data <- read_xls(path="test_file.xls") Error: filepath: /Users/USER/Desktop/test_file.xls libxls error: Unable to open file ``` I also did some elementary testing to make sure the file exists and is in the correct format: ``` > # Testing existence & format of the file > file.exists("test_file.xls") [1] TRUE > format_from_ext("test_file.xls") [1] "xls" > format_from_signature("test_file.xls") [1] "xls" ``` The `test_file.xls` used above is available [here](https://drive.google.com/file/d/13NIs4fi6dHQ8eFKKycYCPjy89N29vln0/view?usp=sharing). Any advice would be appreciated in terms of making the first functions run faster or the `read_xls` run at all - thank you! ### UPDATE: It seems that some users are able to open the file above using the `readxl::read_xls` function, while others are not, both on Mac and Windows, using the most up to date versions of `R`, `Rstudio`, and `readxl`. The [issue has been posted on the readxl GitHub](https://github.com/tidyverse/readxl/issues/598) and has not been resolved yet.
2019/12/06
[ "https://Stackoverflow.com/questions/59218057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8865518/" ]
I found that I was unable to open the file with `read_xl` immediately after downloading it, but if I opened the file in Excel, saved it, and closed it again, then `read_xl` was able to open it without issue. My suggested workaround for handling hundreds of files is to build a little C# command line utility that opens, saves, and closes an Excel file. Source code is below, the utility can be compiled with visual studio community edition. ```cs using System.IO; using Excel = Microsoft.Office.Interop.Excel; namespace resaver { class Program { static void Main(string[] args) { string srcFile = Path.GetFullPath(args[0]); Excel.Application excelApplication = new Excel.Application(); excelApplication.Application.DisplayAlerts = false; Excel.Workbook srcworkBook = excelApplication.Workbooks.Open(srcFile); srcworkBook.Save(); srcworkBook.Close(); excelApplication.Quit(); } } } ``` Once compiled, the utility can be called from R using e.g. `system2()`.
I was seeing a similar error and wanted to share a short-term solution. ``` library(readxl) download.file("https://mjwebster.github.io/DataJ/spreadsheets/MLBpayrolls.xls", "MLBPayrolls.xls") MLBpayrolls <- read_excel("MLBpayrolls.xls", sheet = "MLB Payrolls", na = "n/a") ``` Yields (on some systems in my classroom but not others): > > Error: filepath: MLBPayrolls.xls libxls error: Unable to open file > > > The temporary solution was to paste the URL of the xls file into Firefox and download it via the browser. Once this was done we could run the `read_excel` line without error. This was happening today on Windows 10, with R 3.6.2 and R Studio 1.2.5033.
33,995,244
I have a service where I pass some data on click what works great, but now I wanna pull that data from the service and add it to a scope in another controller and just log everytime there is something added with the $watch function. My service: ``` app.service('infoService', function() { var currentInfo = []; return this.method = function(data){ return currentInfo = data; }; }); ``` Where I try to pull the data ``` app.controller('clickController', function($scope, infoService) { $scope.data = infoService.method(); $scope.$watch('data', function(newVal, oldVal) { console.log(newVal, oldVal); }); }); ``` The only thing I currently see the last hour are errors and errors.
2015/11/30
[ "https://Stackoverflow.com/questions/33995244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3607118/" ]
Indeed the information is scattered around so it seems to make no sense. But there is a [precious hint in the doc](http://doc.qt.io/qt-4.8/qprogressdialog.html#details) : > > QProgressDialog ... estimates the time the operation will take > (***based on time for steps***), and only shows itself if that > estimate is beyond minimumDuration() (4 seconds by default). > > > The dialog seems to use the `value` property to approximate the time required for steps. And it is seems that value property by default is not set [value property](http://doc.qt.io/qt-4.8/qprogressdialog.html#value-prop) : > > For the progress dialog to work as expected, you should initially set > this property to 0 and finally set it to QProgressDialog::maximum(); > > > Indeed, `dialog->value()` returns -1 in my machine after construction. To wrap up : 1. Not setting value is an issue. You **have to set** value sometimes to make it work. 2. **The dialog is shown as soon as it interpolates that the *total amount* of work is going to take more than minimumDuration** 3. Setting a value to anything lower than `QProgressDialog::minimum()`, which is the case by default, causes the progressbar to stay hidden. 4. Your second cases set the value to `0 = minimum`. After 8 seconds, you still havent updated that value. which means the processing of a single item take more than 8 seconds. Should show. 5. You **should** modify the value from `0 -> minimum -> maximum` for proper behavior. Your third case, fail to do this because value goes from -1 to 1, without being set to 0 = minimum. Unspecified, in this version doesnt show. 6. Your 4th case means "the first processing took 0 second, the second is not done yet". So the minimumDuration behavior kicks in. Should show. 7. **Now that there is one second duration for the first task (case 5)**, the dialog **approximates** that 10 tasks are going to take 10s, which is bigger than `8s`, so the dialog is shown as soon as `dlg->setValue(1);` is executed.
I tested this on OS X, with Qt 5 and get the same results Looking closer at the documentation for [setValue](http://doc.qt.io/qt-5/qprogressdialog.html#value-prop), it states: - > > For the progress dialog to work as expected, you should initially set this property to QProgressDialog::minimum() and finally set it to QProgressDialog::maximum(); you can call setValue() any number of times in-between. > > > With this in mind, it works as expected, as can be seen when you first set the value to zero, then another value. ``` QProgressDialog* dlg = new QProgressDialog("Test", "cancel", 0, 10); dlg->setMinimumDuration(8000); dlg->setValue(0); dlg->setValue(1); ``` So, I think the documentation for setMinimumDuration should probably link to this too, but the behaviour is correct according to the documentation, when taking setValue into account.
66,979,516
I have a string `2021-04-07T13:51:39.664+11:00` which I use to create a `Date` object: `d = new Date('2021-04-07T13:51:39.664+03:00')`. After that, `d` is an instance to represent the date time. Now I'd like to get the timezone offset from `d`, but `d.getTimezoneOffset()` always return local timezone offset which is `-600` in my case. How can I get the timezone offset from the string? Does it get lost when I build the `date` instance? Do I have to parse the string to get it? If I have a `date` object, how can I generate a string with the offset at the end: `2021-04-07T13:51:39.664+03:00`? `toISOString()` only generate UTC time. I know `moment` is a good date library but I don't want to add this dependency since it is too large.
2021/04/07
[ "https://Stackoverflow.com/questions/66979516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5421539/" ]
This is probably not the best possible approach, but it is portable and quite useful if you are in control of the application environment. ```js friendlyDate = function( x ){ var label = "Day Month Date Year Time Offset".split(" "), d = x ? new Date(x) : new Date(), s = ( d + "" ) .split( / / ); s.length = label.length; for( var x in s )s[ label[ x ] ] = s[ x ]; s.length = 0; return s } /**/ dte = friendlyDate(); for(var x in dte)console.log(x + ": "+ dte[x]); ``` p.s.: you might need to readjust\rearrange the labels for certain targeted browsers. [Not all browser vendor\version date string representations are returned equal ;)]
[How to initialize a JavaScript Date to a particular time zone](https://stackoverflow.com/questions/15141762/how-to-initialize-a-javascript-date-to-a-particular-time-zone) > > There is no time zone or string format stored in the Date object itself. > > > Seems like either string parsing or a library (there are lighter-weight ones than moment if you're interested).
73,549,816
I am working on a long running multi-module Maven Java project. I tried to update the PMD plugin from 3.17.0 to 3.18.0, but I get a java.lang.NoSuchMethodError from PMD almost immediately. The 3.17.0 version of the PMD plugin works fine on this project and I havent found anything in the release notes that helps me understand the error. Hoping something here understands the PMD plugin or the error and can orient me towards the root issue. The project is built using Maven 3.5, JKD 11 with a compile target of JDK8. PMD version is 6.48.0 POM snippet and error output below. ``` <artifactId>maven-pmd-plugin</artifactId> <version>${pmd.plugin.version}</version> <executions> <execution> <phase>verify</phase> <goals> <goal>check</goal> <goal>cpd-check</goal> </goals> </execution> </executions> <configuration> <skip>${skip.analyze}</skip> <analysisCache>true</analysisCache> <analysisCacheLocation>${project.build.directory}/pmd/pmd.cache</analysisCacheLocation> <failOnViolation>false</failOnViolation> <rulesets> <ruleset>../ruleset.xml</ruleset> </rulesets> <printFailingErrors>false</printFailingErrors> <linkXRef>false</linkXRef> <targetJdk>1.8</targetJdk> </configuration> <dependencies> <dependency> <groupId>net.sourceforge.pmd</groupId> <artifactId>pmd-core</artifactId> <version>${pmd.version}</version> </dependency> <dependency> <groupId>net.sourceforge.pmd</groupId> <artifactId>pmd-java</artifactId> <version>${pmd.version}</version> </dependency> <dependency> <groupId>net.sourceforge.pmd</groupId> <artifactId>pmd-javascript</artifactId> <version>${pmd.version}</version> </dependency> <dependency> <groupId>net.sourceforge.pmd</groupId> <artifactId>pmd-jsp</artifactId> <version>${pmd.version}</version> </dependency> <dependency> <groupId>net.sourceforge.pmd</groupId> <artifactId>pmd-apex</artifactId> <version>${pmd.version}</version> </dependency> <dependency> <groupId>net.sourceforge.pmd</groupId> <artifactId>pmd-visualforce</artifactId> <version>${pmd.version}</version> </dependency> </dependencies> </plugin>``` Command: mvn pmd:check ``` ``` [ERROR] Failed to execute goal org.apache.maven.plugins:maven-pmd-plugin:3.18.0:pmd (pmd) on project test-utils: Execution pmd of goal org.apache.maven.plugins:maven-pmd-plugin:3.18.0:pmd failed: An API incompatibility was encountered while executing org.apache.maven.plugins:maven-pmd-plugin:3.18.0:pmd: java.lang.NoSuchMethodError: org.fusesource.jansi.AnsiConsole.out()Lorg/fusesource/jansi/AnsiPrintStream; [ERROR] ----------------------------------------------------- [ERROR] realm = plugin>org.apache.maven.plugins:maven-pmd-plugin:3.18.0 [ERROR] strategy = org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy [ERROR] urls[0] = file:/Users/john.camerin/.m2/repository/org/apache/maven/plugins/maven-pmd-plugin/3.18.0/maven-pmd-plugin-3.18.0.jar [ERROR] urls[1] = file:/Users/john.camerin/.m2/repository/org/apache/maven/shared/maven-artifact-transfer/0.13.1/maven-artifact-transfer-0.13.1.jar [ERROR] urls[2] = file:/Users/john.camerin/.m2/repository/org/sonatype/aether/aether-util/1.7/aether-util-1.7.jar [ERROR] urls[3] = file:/Users/john.camerin/.m2/repository/org/sonatype/sisu/sisu-inject-bean/1.4.2/sisu-inject-bean-1.4.2.jar [ERROR] urls[4] = file:/Users/john.camerin/.m2/repository/org/sonatype/sisu/sisu-guice/2.1.7/sisu-guice-2.1.7-noaop.jar [ERROR] urls[5] = file:/Users/john.camerin/.m2/repository/org/codehaus/plexus/plexus-interpolation/1.14/plexus-interpolation-1.14.jar [ERROR] urls[6] = file:/Users/john.camerin/.m2/repository/org/sonatype/plexus/plexus-sec-dispatcher/1.3/plexus-sec-dispatcher-1.3.jar [ERROR] urls[7] = file:/Users/john.camerin/.m2/repository/org/sonatype/plexus/plexus-cipher/1.4/plexus-cipher-1.4.jar [ERROR] urls[8] = file:/Users/john.camerin/.m2/repository/org/codehaus/plexus/plexus-component-annotations/2.1.1/plexus-component-annotations-2.1.1.jar [ERROR] urls[9] = file:/Users/john.camerin/.m2/repository/org/apache/maven/shared/maven-common-artifact-filters/3.3.1/maven-common-artifact-filters-3.3.1.jar [ERROR] urls[10] = file:/Users/john.camerin/.m2/repository/commons-io/commons-io/2.11.0/commons-io-2.11.0.jar [ERROR] urls[11] = file:/Users/john.camerin/.m2/repository/org/apache/commons/commons-lang3/3.12.0/commons-lang3-3.12.0.jar [ERROR] urls[12] = file:/Users/john.camerin/.m2/repository/net/sourceforge/pmd/pmd-core/6.48.0/pmd-core-6.48.0.jar [ERROR] urls[13] = file:/Users/john.camerin/.m2/repository/org/antlr/antlr4-runtime/4.7.2/antlr4-runtime-4.7.2.jar [ERROR] urls[14] = file:/Users/john.camerin/.m2/repository/com/beust/jcommander/1.48/jcommander-1.48.jar [ERROR] urls[15] = file:/Users/john.camerin/.m2/repository/net/sourceforge/saxon/saxon/9.1.0.8/saxon-9.1.0.8.jar [ERROR] urls[16] = file:/Users/john.camerin/.m2/repository/org/ow2/asm/asm/9.3/asm-9.3.jar [ERROR] urls[17] = file:/Users/john.camerin/.m2/repository/com/google/code/gson/gson/2.8.9/gson-2.8.9.jar [ERROR] urls[18] = file:/Users/john.camerin/.m2/repository/net/sourceforge/saxon/saxon/9.1.0.8/saxon-9.1.0.8-dom.jar [ERROR] urls[19] = file:/Users/john.camerin/.m2/repository/net/sourceforge/pmd/pmd-java/6.48.0/pmd-java-6.48.0.jar [ERROR] urls[20] = file:/Users/john.camerin/.m2/repository/net/sourceforge/pmd/pmd-javascript/6.48.0/pmd-javascript-6.48.0.jar [ERROR] urls[21] = file:/Users/john.camerin/.m2/repository/org/mozilla/rhino/1.7.14/rhino-1.7.14.jar [ERROR] urls[22] = file:/Users/john.camerin/.m2/repository/net/sourceforge/pmd/pmd-jsp/6.48.0/pmd-jsp-6.48.0.jar [ERROR] urls[23] = file:/Users/john.camerin/.m2/repository/org/slf4j/jul-to-slf4j/1.7.36/jul-to-slf4j-1.7.36.jar [ERROR] urls[24] = file:/Users/john.camerin/.m2/repository/org/apache/maven/doxia/doxia-sink-api/1.11.1/doxia-sink-api-1.11.1.jar [ERROR] urls[25] = file:/Users/john.camerin/.m2/repository/org/apache/maven/doxia/doxia-logging-api/1.11.1/doxia-logging-api-1.11.1.jar [ERROR] urls[26] = file:/Users/john.camerin/.m2/repository/org/apache/maven/doxia/doxia-decoration-model/1.11.1/doxia-decoration-model-1.11.1.jar [ERROR] urls[27] = file:/Users/john.camerin/.m2/repository/org/apache/maven/doxia/doxia-site-renderer/1.11.1/doxia-site-renderer-1.11.1.jar [ERROR] urls[28] = file:/Users/john.camerin/.m2/repository/org/apache/maven/doxia/doxia-core/1.11.1/doxia-core-1.11.1.jar [ERROR] urls[29] = file:/Users/john.camerin/.m2/repository/org/apache/commons/commons-text/1.3/commons-text-1.3.jar [ERROR] urls[30] = file:/Users/john.camerin/.m2/repository/org/apache/httpcomponents/httpcore/4.4.14/httpcore-4.4.14.jar [ERROR] urls[31] = file:/Users/john.camerin/.m2/repository/org/apache/maven/doxia/doxia-skin-model/1.11.1/doxia-skin-model-1.11.1.jar [ERROR] urls[32] = file:/Users/john.camerin/.m2/repository/org/apache/maven/doxia/doxia-module-xhtml/1.11.1/doxia-module-xhtml-1.11.1.jar [ERROR] urls[33] = file:/Users/john.camerin/.m2/repository/org/apache/maven/doxia/doxia-module-xhtml5/1.11.1/doxia-module-xhtml5-1.11.1.jar [ERROR] urls[34] = file:/Users/john.camerin/.m2/repository/org/codehaus/plexus/plexus-i18n/1.0-beta-10/plexus-i18n-1.0-beta-10.jar [ERROR] urls[35] = file:/Users/john.camerin/.m2/repository/junit/junit/3.8.1/junit-3.8.1.jar [ERROR] urls[36] = file:/Users/john.camerin/.m2/repository/org/codehaus/plexus/plexus-velocity/1.2/plexus-velocity-1.2.jar [ERROR] urls[37] = file:/Users/john.camerin/.m2/repository/org/apache/velocity/velocity/1.7/velocity-1.7.jar [ERROR] urls[38] = file:/Users/john.camerin/.m2/repository/commons-lang/commons-lang/2.4/commons-lang-2.4.jar [ERROR] urls[39] = file:/Users/john.camerin/.m2/repository/org/apache/velocity/velocity-tools/2.0/velocity-tools-2.0.jar [ERROR] urls[40] = file:/Users/john.camerin/.m2/repository/commons-beanutils/commons-beanutils/1.7.0/commons-beanutils-1.7.0.jar [ERROR] urls[41] = file:/Users/john.camerin/.m2/repository/commons-digester/commons-digester/1.8/commons-digester-1.8.jar [ERROR] urls[42] = file:/Users/john.camerin/.m2/repository/commons-chain/commons-chain/1.1/commons-chain-1.1.jar [ERROR] urls[43] = file:/Users/john.camerin/.m2/repository/commons-logging/commons-logging/1.1/commons-logging-1.1.jar [ERROR] urls[44] = file:/Users/john.camerin/.m2/repository/dom4j/dom4j/1.1/dom4j-1.1.jar [ERROR] urls[45] = file:/Users/john.camerin/.m2/repository/oro/oro/2.0.8/oro-2.0.8.jar [ERROR] urls[46] = file:/Users/john.camerin/.m2/repository/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar [ERROR] urls[47] = file:/Users/john.camerin/.m2/repository/org/apache/maven/reporting/maven-reporting-api/3.1.1/maven-reporting-api-3.1.1.jar [ERROR] urls[48] = file:/Users/john.camerin/.m2/repository/org/apache/maven/reporting/maven-reporting-impl/3.2.0/maven-reporting-impl-3.2.0.jar [ERROR] urls[49] = file:/Users/john.camerin/.m2/repository/javax/annotation/javax.annotation-api/1.2/javax.annotation-api-1.2.jar [ERROR] urls[50] = file:/Users/john.camerin/.m2/repository/javax/enterprise/cdi-api/1.2/cdi-api-1.2.jar [ERROR] urls[51] = file:/Users/john.camerin/.m2/repository/org/eclipse/sisu/org.eclipse.sisu.inject/0.3.5/org.eclipse.sisu.inject-0.3.5.jar [ERROR] urls[52] = file:/Users/john.camerin/.m2/repository/org/apache/maven/doxia/doxia-integration-tools/1.11.1/doxia-integration-tools-1.11.1.jar [ERROR] urls[53] = file:/Users/john.camerin/.m2/repository/org/apache/maven/shared/maven-shared-utils/3.3.4/maven-shared-utils-3.3.4.jar [ERROR] urls[54] = file:/Users/john.camerin/.m2/repository/org/codehaus/plexus/plexus-resources/1.2.0/plexus-resources-1.2.0.jar [ERROR] urls[55] = file:/Users/john.camerin/.m2/repository/org/codehaus/plexus/plexus-utils/3.3.0/plexus-utils-3.3.0.jar [ERROR] Number of foreign imports: 1 [ERROR] import: Entry[import from realm ClassRealm[project>com.messagegears:accelerator-parent:22.2.1.0-SNAPSHOT, parent: ClassRealm[maven.api, parent: null]]] ```
2022/08/31
[ "https://Stackoverflow.com/questions/73549816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10454072/" ]
Please see the discussion here: <https://issues.apache.org/jira/browse/MPMD-353> In short, you have the following options: * Upgrade to maven 3.8.6 or later * Stay on maven-pmd-plugin 3.17.0 * ~~Wait until a new version of maven-pmd-plugin is released with a fix for that problem, that makes it working again with old maven versions.~~ * Upgrade to maven-pmd-plugin 3.19.0, which contains the fix for MPMD-353
Did you also try to upgrade `pmd.version` to `6.48.0` or `6.50.0`? I was having the similar problem for the pmd plugin version `3.19.0` and I've upgraded the `pmd-java` and `pmd-core` version to the latest one and worked like a charm.
26,330,492
I would like to apply a filter to a photo from the user's library then write it back to disk. I'm using `UIImageJPEGRepresentation`. This function takes a `UIImage` and a `compressionQuality` value between 0.0 and 1.0. Because I want to preserve the original quality, I set it to 1.0. But I found this actually creates an image file that's larger in file size than the original, somewhat significantly larger even. I noticed in Apple's Sample Photo Editing Extension app they always set the quality to 0.9. I tried that and it does output a file size close to the original photo file size. This doesn't make sense to me. Can someone explain this? Is it appropriate to always use 0.9? Does the iOS camera compress it using that value and thus 0.9 is the original quality? Or why isn't 0.9 actually 1.0, if there's nothing that's better quality? ``` NSData *renderedJPEGData = UIImageJPEGRepresentation(image, 0.9f); ```
2014/10/12
[ "https://Stackoverflow.com/questions/26330492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1795356/" ]
FWIW, I converted the same 600x800 image using AsJPEG() with these compressions to see the sizes & gauge the visible quality loss: 1.0: 642KB 0.9: 212KB 0.7: 144KB 0.5: 86KB Visible quality didn't suffer much, even at 0.5 (!). I'll be using these on a webpage where visible perfection isn't critical, so I'll use 0.5 to gain the benefit of the small (13%) filesize. Of course, your mileage may vary :)
You can convert image in PNG representation for original image quality. ``` UIImagePNGRepresentation(image) ```
4,194,581
There is a lot to commend MVC, but one problem I keep getting is ID name collisions. I first noticed it when generating a grid using a foreach loop. With the help of SO I found the solution was to use Editor Templates. Now I have the same problem with tabs. I used this reference to find out how to use tabs; <http://blog.roonga.com.au/search?updated-max=2010-06-14T19:27:00%2B10:00&max-results=1> The problem with my tabs is that I am using a date field with a date picker. In the example above, ID name collisions are avoided by referencing a generated unique Id of the container element. However for a datepicker, the ID of the container is irrelevant, only the ID of the date field matters. So what happens is that if I create my second tab the same as the first, when I update my second tab, the date on the first is updated. So below is my View, and a partial view which displays the date. When I click the "Add Absence for 1 day button, I create a tab for that screen; ``` <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/AdminAccounts.master" Inherits="System.Web.Mvc.ViewPage<SHP.WebUI.Models.AbsenceViewModel>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> AbsenceForEmployee </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="AdminAccountsContent" runat="server"> <script type="text/javascript"> $(function () { $('#tabs').tabs( { cache: true }, { ajaxOptions: { cache: false, error: function (xhr, status, index, anchor) { $(anchor.hash).html("Couldn't load this tab."); }, data: {}, success: function (data, textStatus) { } }, add: function (event, ui) { //select the new tab $('#tabs').tabs('select', '#' + ui.panel.id); } }); }); function addTab(title, uri) { var newTab = $("#tabs").tabs("add", uri, title); } function closeTab() { var index = getSelectedTabIndex(); $("#tabs").tabs("remove", index) } function getSelectedTabIndex() { return $("#tabs").tabs('option', 'selected'); } function RefreshList() { $('#frmAbsenceList').submit(); } </script> <% using (Html.BeginForm()) {%> <%: Html.AntiForgeryToken() %> <fieldset> <legend>Select an employee to edit absence record</legend> <div style="padding-bottom:30px;padding-left:10px;"> <div class="span-7"><b>Name:</b> <%: Model.Employee.GetName() %></div> <div class="span-6"><b>Division:</b><%: Model.DivisionName %></div> <div class="span-6"><b>Department:</b> <%: Model.DepartmentName %></div></div> <p>Attendance record for the year <%: Html.DropDownListFor(model => model.SelectedYearId, Model.YearList, new { onchange = "this.form.submit();" })%></p> <div id="tabs"> <ul> <li><a href="#tabs-1">Absence List</a></li> </ul> <div id="tabs-1"> <input id="btnAddOneDayTab" type="button" onclick="addTab('Add Absence (1 day)','<%= Url.Action("AddAbsenceOneDay", "Employee") %>')" value='Add Absence for 1 day' /> <input id="btnAddDateRangeTab" type="button" onclick="addTab('Add Absence (date range)','<%= Url.Action("AddAbsenceDateRange", "Employee") %>')" value='Add Absence for a range of dates' /> <hr /> <% Html.RenderPartial("ListAbsence", Model.ListEmployeeAbsenceThisYear); %> </div> </div> </fieldset> <% } %> ``` Add new date partial view ... ----------------------------- ``` <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SHP.Models.EmployeeOtherLeaf>" %> <% var unique = DateTime.Now.Ticks.ToString(); %> <script language="javascript" type="text/javascript"> $(document).ready(function () { $('#frmAddAbsenceOneDay<%= unique %> #NullableOtherLeaveDate').datepicker({ dateFormat: 'dd-MM-yy' }); $('#frmAddAbsenceOneDay<%= unique %> #MorningOnlyFlag').click(function () { $('#frmAddAbsenceOneDay<%= unique %> #AfternoonOnlyFlag').attr('checked', false); }) $('#frmAddAbsenceOneDay<%= unique %> #AfternoonOnlyFlag').click(function () { $('#frmAddAbsenceOneDay<%= unique %> #MorningOnlyFlag').attr('checked', false); }) }); var options = { target: '#frmAddAbsenceOneDay<%= unique %>', success: RefreshList }; $(document).ready(function () { $('#frmAddAbsenceOneDay<%= unique %>').ajaxForm(options); }); </script> <div id="AddAbsenceOnDay<%= unique %>"> <% using (Html.BeginForm("AddAbsenceOneDay", "Employee", FormMethod.Post, new { id = "frmAddAbsenceOneDay" + unique })) { %> <%: Html.ValidationSummary(true) %> <fieldset> <legend>Add an absence for a day or half day</legend> <table> <tr> <td><%: Html.LabelFor(model => model.OtherLeaveId)%></td> <td> <%: Html.DropDownListFor(model => model.OtherLeaveId, Model.SelectLeaveTypeList, "<--Select-->")%> <%: Html.ValidationMessageFor(model => model.OtherLeaveId)%> </td> </tr> <tr> <td> <%: Html.LabelFor(model => model.NullableOtherLeaveDate)%> </td> <td> <%: Html.EditorFor(model => model.NullableOtherLeaveDate)%> <%: Html.ValidationMessageFor(model => model.NullableOtherLeaveDate)%> <%if (ViewData["ErrorDateMessage"] != null && ViewData["ErrorDateMessage"].ToString().Length > 0) { %> <p class="error"> At <% Response.Write(DateTime.Now.ToString("T")); %>. <%: ViewData["ErrorDateMessage"]%>. </p> <%} %> </td> </tr> <tr> <td> <%: Html.LabelFor(model => model.MorningOnlyFlag)%> </td> <td> <%: Html.CheckBoxFor(model => model.MorningOnlyFlag)%> <%: Html.ValidationMessageFor(model => model.MorningOnlyFlag)%> </td> </tr> <tr> <td> <%: Html.LabelFor(model => model.AfternoonOnlyFlag)%> </td> <td> <%: Html.CheckBoxFor(model => model.AfternoonOnlyFlag)%> <%: Html.ValidationMessageFor(model => model.AfternoonOnlyFlag)%> </td> </tr> </table> <p> <span style="padding-right:10px;"><input type="submit" value="Create" /></span><input type="button" value="Close" onclick="closeTab()" /> </p> </fieldset> <% } %> </div> ``` You can see the ID of the date in the following HTML from Firebug ``` <div id="main"> <div id="adminAccounts"> <table> <tbody><tr> <td> <div style="padding-top: 15px;"> // Menu removed </div> </td> <td> <script type="text/javascript"> $(function () { $('#tabs').tabs( { cache: true }, { ajaxOptions: { cache: false, error: function (xhr, status, index, anchor) { $(anchor.hash).html("Couldn't load this tab."); }, data: {}, success: function (data, textStatus) { } }, add: function (event, ui) { //select the new tab $('#tabs').tabs('select', '#' + ui.panel.id); } }); }); function addTab(title, uri) { var newTab = $("#tabs").tabs("add", uri, title); } function closeTab() { var index = getSelectedTabIndex(); $("#tabs").tabs("remove", index) } function getSelectedTabIndex() { return $("#tabs").tabs('option', 'selected'); } function RefreshList() { $('#frmAbsenceList').submit(); } </script> <form method="post" action="/Employee/AbsenceForEmployee?employeeId=1"><input type="hidden" value="8yGn2w+fgqSRsho/d+7FMnPWBtTbu96X4u1t/Jf6+4nDSNJHOPeq7IT9CedAjrZIAK/DgbNX6idtTd94XUBM5w==" name="__RequestVerificationToken"> <fieldset> <legend>Select an employee to edit absence record</legend> <div style="padding-bottom: 30px; padding-left: 10px;"> <div class="span-7"><b>Name:</b> xaviar caviar</div> <div class="span-6"><b>Division:</b>ICT</div> <div class="span-6"><b>Department:</b> ICT</div></div> <p>Absence Leave record for the year <select onchange="this.form.submit();" name="SelectedYearId" id="SelectedYearId"><option value="2" selected="selected">2010/11</option> </select></p> <div id="tabs" class="ui-tabs ui-widget ui-widget-content ui-corner-all"> <ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all"> <li class="ui-state-default ui-corner-top"><a href="#tabs-1">Absence List</a></li> <li class="ui-state-default ui-corner-top"><a href="#ui-tabs-2"><span>Add Absence (1 day)</span></a></li><li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#ui-tabs-4"><span>Add Absence (1 day)</span></a></li></ul> <div id="tabs-1" class="ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide"> <input type="button" value="Add Absence for 1 day" onclick="addTab('Add Absence (1 day)','/Employee/AddAbsenceOneDay')" id="btnAddOneDayTab"> <input type="button" value="Add Absence for a range of dates" onclick="addTab('Add Absence (date range)','/Employee/AddAbsenceDateRange')" id="btnAddDateRangeTab"> <hr> <script type="text/javascript"> var options = { target: '#AbsenceList' }; $(document).ready(function() { $('#frmAbsenceList').ajaxForm(options); }); </script> <div id="AbsenceList"> <table class="grid"><thead><tr><th class="sort_asc"><a href="/Employee/AbsenceForEmployee?Direction=Descending&amp;employeeId=1"></a></th><th><a href="/Employee/AbsenceForEmployee?Column=OtherLeaveName&amp;Direction=Ascending&amp;employeeId=1">Leave Type</a></th><th><a href="/Employee/AbsenceForEmployee?Column=MorningOnlyFlag&amp;Direction=Ascending&amp;employeeId=1">Morning Only</a></th><th><a href="/Employee/AbsenceForEmployee?Column=AfternoonOnlyFlag&amp;Direction=Ascending&amp;employeeId=1">Afternoon Only</a></th><th><a href="/Employee/AbsenceForEmployee?Column=DayAmount&amp;Direction=Ascending&amp;employeeId=1">Day Amount</a></th><th><a href="/Employee/AbsenceForEmployee?Column=OtherLeaveDate&amp;Direction=Ascending&amp;employeeId=1">Date</a></th></tr></thead><tbody><tr class="gridrow"><td><a href="/Employee/DeleteAbsence?_employeeOtherLeaveId=60">Delete</a></td><td>Sickness</td><td>False</td><td>False</td><td>1</td><td>04/11/2010</td></tr><tr class="gridrow_alternate"><td><a href="/Employee/DeleteAbsence?_employeeOtherLeaveId=51">Delete</a></td><td>Unpaid Sickness</td><td>False</td><td>False</td><td>1</td><td>08/11/2010</td></tr><tr class="gridrow"><td><a href="/Employee/DeleteAbsence?_employeeOtherLeaveId=54">Delete</a></td><td>Unpaid Compassionate</td><td>False</td><td>False</td><td>1</td><td>09/11/2010</td></tr><tr class="gridrow_alternate"><td><a href="/Employee/DeleteAbsence?_employeeOtherLeaveId=45">Delete</a></td><td>Compassionate</td><td>False</td><td>False</td><td>1</td><td>10/11/2010</td></tr><tr class="gridrow"><td><a href="/Employee/DeleteAbsence?_employeeOtherLeaveId=43">Delete</a></td><td>Compassionate</td><td>False</td><td>False</td><td>1</td><td>15/11/2010</td></tr><tr class="gridrow_alternate"><td><a href="/Employee/DeleteAbsence?_employeeOtherLeaveId=55">Delete</a></td><td>Unpaid Sickness</td><td>False</td><td>False</td><td>1</td><td>16/11/2010</td></tr><tr class="gridrow"><td><a href="/Employee/DeleteAbsence?_employeeOtherLeaveId=56">Delete</a></td><td>Compassionate</td><td>False</td><td>False</td><td>1</td><td>17/11/2010</td></tr><tr class="gridrow_alternate"><td><a href="/Employee/DeleteAbsence?_employeeOtherLeaveId=44">Delete</a></td><td>Compassionate</td><td>False</td><td>False</td><td>1</td><td>22/11/2010</td></tr><tr class="gridrow"><td><a href="/Employee/DeleteAbsence?_employeeOtherLeaveId=37">Delete</a></td><td>Unpaid Sickness</td><td>False</td><td>False</td><td>1</td><td>24/11/2010</td></tr><tr class="gridrow_alternate"><td><a href="/Employee/DeleteAbsence?_employeeOtherLeaveId=36">Delete</a></td><td>Sickness</td><td>False</td><td>False</td><td>1</td><td>25/11/2010</td></tr><tr class="gridrow"><td><a href="/Employee/DeleteAbsence?_employeeOtherLeaveId=48">Delete</a></td><td>Unpaid Sickness</td><td>False</td><td>False</td><td>1</td><td>26/11/2010</td></tr><tr class="gridrow_alternate"><td><a href="/Employee/DeleteAbsence?_employeeOtherLeaveId=38">Delete</a></td><td>Unpaid Sickness</td><td>False</td><td>False</td><td>1</td><td>29/11/2010</td></tr><tr class="gridrow"><td><a href="/Employee/DeleteAbsence?_employeeOtherLeaveId=5">Delete</a></td><td>Compassionate</td><td>False</td><td>False</td><td>1</td><td>30/11/2010</td></tr><tr class="gridrow_alternate"><td><a href="/Employee/DeleteAbsence?_employeeOtherLeaveId=46">Delete</a></td><td>Unpaid Sickness</td><td>False</td><td>False</td><td>1</td><td>13/12/2010</td></tr><tr class="gridrow"><td><a href="/Employee/DeleteAbsence?_employeeOtherLeaveId=61">Delete</a></td><td>Compassionate</td><td>False</td><td>False</td><td>1</td><td>26/12/2010</td></tr></tbody></table> <p></p><div class="pagination"><span class="paginationLeft">Showing 1 - 15 of 21 </span><span class="paginationRight">first | prev | <a href="/Employee/AbsenceForEmployee?page=2&amp;employeeId=1">next</a> | <a href="/Employee/AbsenceForEmployee?page=2&amp;employeeId=1">last</a></span></div> </div> </div><div id="ui-tabs-2" class="ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide"> <div id="AddAbsenceOnDay634255177533718544"> <form method="post" id="frmAddAbsenceOneDay634255177533718544" action="/Employee/AddAbsenceOneDay"> <fieldset> <legend>Add an absence for a day or half day</legend> <table> <tbody><tr> <td><label for="OtherLeaveId">Leave Type</label></td> <td> <select name="OtherLeaveId" id="OtherLeaveId"><option value="">&lt;--Select--&gt;</option> <option value="1">Sickness</option> <option value="2">Unpaid Sickness</option> <option value="6">Compassionate</option> <option value="7">Unpaid Compassionate</option> <option value="8">Unauthorised</option> <option value="9">Unpaid Unauthorised</option> <option value="10">Other</option> <option value="11">Unpaid Other</option> </select> </td> </tr> <tr> <td> <label for="NullableOtherLeaveDate">Date</label> </td> <td> <input type="text" value="" name="NullableOtherLeaveDate" id="NullableOtherLeaveDate" class="datePicker hasDatepicker"> </td> </tr> <tr> <td> <label for="MorningOnlyFlag">Morning Only</label> </td> <td> <input type="checkbox" value="true" name="MorningOnlyFlag" id="MorningOnlyFlag"><input type="hidden" value="false" name="MorningOnlyFlag"> </td> </tr> <tr> <td> <label for="AfternoonOnlyFlag">Afternoon Only</label> </td> <td> <input type="checkbox" value="true" name="AfternoonOnlyFlag" id="AfternoonOnlyFlag"><input type="hidden" value="false" name="AfternoonOnlyFlag"> </td> </tr> </tbody></table> <p> <span style="padding-right: 10px;"><input type="submit" value="Create"></span><input type="button" onclick="closeTab()" value="Close"> </p> </fieldset> </form> </div> </div><div id="ui-tabs-4" class="ui-tabs-panel ui-widget-content ui-corner-bottom"> <div id="AddAbsenceOnDay634255177583860349"> <form method="post" id="frmAddAbsenceOneDay634255177583860349" action="/Employee/AddAbsenceOneDay"> <fieldset> <legend>Add an absence for a day or half day</legend> <table> <tbody><tr> <td><label for="OtherLeaveId">Leave Type</label></td> <td> <select name="OtherLeaveId" id="OtherLeaveId"><option value="">&lt;--Select--&gt;</option> <option value="1">Sickness</option> <option value="2">Unpaid Sickness</option> <option value="6">Compassionate</option> <option value="7">Unpaid Compassionate</option> <option value="8">Unauthorised</option> <option value="9">Unpaid Unauthorised</option> <option value="10">Other</option> <option value="11">Unpaid Other</option> </select> </td> </tr> <tr> <td> <label for="NullableOtherLeaveDate">Date</label> </td> <td> <input type="text" value="" name="NullableOtherLeaveDate" id="NullableOtherLeaveDate" class="datePicker hasDatepicker"> </td> </tr> <tr> <td> <label for="MorningOnlyFlag">Morning Only</label> </td> <td> <input type="checkbox" value="true" name="MorningOnlyFlag" id="MorningOnlyFlag"><input type="hidden" value="false" name="MorningOnlyFlag"> </td> </tr> <tr> <td> <label for="AfternoonOnlyFlag">Afternoon Only</label> </td> <td> <input type="checkbox" value="true" name="AfternoonOnlyFlag" id="AfternoonOnlyFlag"><input type="hidden" value="false" name="AfternoonOnlyFlag"> </td> </tr> </tbody></table> <p> <span style="padding-right: 10px;"><input type="submit" value="Create"></span><input type="button" onclick="closeTab()" value="Close"> </p> </fieldset> </form> </div> </div> <div id="ui-tabs-1" class="ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide"></div><div id="ui-tabs-3" class="ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide"></div></div> </fieldset> </form></td> </tr> </tbody></table></div> <div id="footer"> </div> </div> ``` If you have got this far(!), I have been asked for the controller, so here it is. ``` [Authorize(Roles = "Administrator, AdminAccounts, ManagerAccounts")] public ActionResult AddAbsenceOneDay() { return View(new EmployeeOtherLeaf()); } [HttpPost] [Authorize(Roles = "Administrator, AdminAccounts, ManagerAccounts")] public ActionResult AddAbsenceOneDay(EmployeeOtherLeaf _absence) { if (ModelState.IsValid) { _absence.EmployeeId = SessionObjects.EmployeeId; _absence.OtherLeaveDate = _absence.NullableOtherLeaveDate.GetValueOrDefault(DateTime.Today); Tuple<bool, string> errorInfo = _absence.IsDateValid(); if (errorInfo.Item1 == true) { _absence.AddAndSave(); ViewData["SuccessMessage"] = "Successfully Added."; return View("EditAbsenceOneDay", _absence); } else { ViewData["ErrorDateMessage"] = errorInfo.Item2; return View(_absence); } } else { return View(_absence); } } ```
2010/11/16
[ "https://Stackoverflow.com/questions/4194581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/125673/" ]
Most obvious answer missing? Netbeans - > Services - > Glassfish -> Properties -> Password show?
First, login to the Administration Console using admin/adminadmin and then change the password. After that, you will be able to connect from Netbeans. I did that with Netbeans 8.
21,661,444
I need to generate a text container that contains something like this: This is **some** random text where a **few** of the words are **coloured** and **clickable** The clickable words should have different actions bound to them and should be in a certain colour. The container will have a fixed width and I need to know the resulting height of the container given a certain text. What I've tried: Tried making each word a separate UILabel, added actions where actions were needed, calculated line breaks myself. The problem with this approach was that it was too slow, especially UILabel sizeThatFits. I need to generate a lot of text for a scrolling UITableView and this approach killed the scrolling performance. What I also tried: UIWebView. For a few different reasons, it's just not an option. What I would prefer: A solution that does not require third party code. This is optional, though if they are open source. iOS 7-only solutions are acceptable. Lastly, what needs to be fast is the generation of the text and the measuring of its height. Determining where to click is allowed to take some time.
2014/02/09
[ "https://Stackoverflow.com/questions/21661444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/970952/" ]
To answer your question, you need the following after the sizes are changed to make sure the layout manager is invoked: ``` filler.revalidate(); ``` However that is NOT a good solution as your entire approach to the problem is wrong. You should not be manually calculating sizes of components like that. That is the job of a layout manager. So you need to rethink your layout stategy. Don't forget you can nest panels with different layout managers. For example if you need a changing gap in the frame then you should probably use a BoxLayout and you can add "glue" to the start and end. Or maybe you can use a GridBagLayout because you can control how components resize based on the space available. Read the Swing tutorial on [Layout Managers](http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html) for more information.
It wouldn't let me put a long enough comment under your answer camickr :( I wanted to add that after posting this I also found this, similar but not identical problem with resizing BorderLayouts, and they describe a similar situation of NORTH/SOUTH positioned controls not paying attention to vertical sizing - [Java Swing BorderLayout resize difficulties](https://stackoverflow.com/questions/12267311/java-swing-borderlayout-resize-difficulties) I'd tried based on the replies to that to use GridBagLayout, and did get that to work after a bit of effort. Basically its a 1x5 grid layout then with cells containing (space I forcibly resize, controls, glue, more controls, space I forcibly resize), and this worked. > > > > > > You should not be manually calculating sizes of components like that. > > > > > > > > > The only thing I'm manually setting the size of is the gap above+below the controls, all the controls themselves I'm letting the layout manager deal with. The size of those gaps has to match a background image on the frame which is sized to the frame but preserving aspect ratio, so the width of that border isn't something the layout manager can figure out, the real code for the 'calc' bit in my SSCCE above is: ``` final int edge = Math.min (contentPane.getWidth () / 4, contentPane.getHeight () / 3); final int imgHeight = edge * 3; final int borderSize = (contentPane.getHeight () - imgHeight) / 2; ``` So if the user resizes the window to be wide, there's black borders left+right of the image, and borderSize = 0. If the user resizes the window to be tall, there's black borders above+below the image, and I want the controls to avoid going there, so they always sit in the background image. But thanks very much for the push in the right direction :)
149,533
* The bird has two yellow spots on its wings. versus * The bird has a yellow spot on both wings. Do they mean the same? Which one describes more accurately the yellow spots of the following bird? ![A blackbird with a yellow spot on each wing.](https://i.stack.imgur.com/kyYrj.jpg) (Other alternatives are welcomed too).
2014/02/03
[ "https://english.stackexchange.com/questions/149533", "https://english.stackexchange.com", "https://english.stackexchange.com/users/4070/" ]
As a long-time birder, I'd reject both in favor of "...yellow patch evident on wings during flight." But I'm guessing you just selected 'birds' as a random "prop" for your usage question.
> > “Two yellow spots on its wings” > > > This is vague, as it could mean two spots on each wing, or two spots in total, on its wings. Replace the word "two" with "three" and it'd be even more confusing: three spots on each, or two on one, one on the other? > > “a yellow spot on both wings?” > > > This is also vague, as it could mean one spot on each wing, or one spot which spans across both wings. However, if you replace the word "a" with "three" on this phrase, it wouldn't be complicated: three spots on both wings quite clearly means three spots on each wing. In short, the latter phrase is slightly less complicated, but it is recommended to simply say "a yellow spot on each wing".
6,887,336
I know what CSS Reset is, but recently I heard about this new thing called Normalize.css What is the difference between the [Normalize.css](https://necolas.github.io/normalize.css/) and [Reset CSS](http://meyerweb.com/eric/tools/css/reset/)? What is the difference between normalizing CSS and resetting CSS? Is it just a new buzz word for the CSS Reset?
2011/07/31
[ "https://Stackoverflow.com/questions/6887336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84201/" ]
Normalize.css is mainly a set of styles, based on what its author thought would look good, and make it look consistent across browsers. Reset basically strips styling from elements so you have more control over the styling of everything. I use both. Some styles from Reset, some from Normalize.css. For example, from Normalize.css, there's a style to make sure all input elements have the same font, which doesn't occur (between text inputs and textareas). Reset has no such style, so inputs have different fonts, which is not normally wanted. So bascially, using the two CSS files does a better job 'Equalizing' everything ;) regards!
resetting seems a necessity to meet custom design specifications, especially on complex, non-boilerplate type design projects. It sounds as though normalizing is a good way to proceed with purely web programming in mind, but oftentimes websites are a marriage between web programming and UI/UX design rules.
94,674
I have been in contact with a **supplier** for a project. We are the client. Things have been going OK up to a point, then I received a rude and mildly abusive email from one of the people (Bob) I've been in contact with. His manager (Alice) is aware, and will deal with it when Bob is back from a work trip. Hence I wasn't planning to respond to it yet. However I need to send Bob and Alice an email with some more technical information in it. Should I ignore Bob's last email and just carry on, or try to answer the points raised? Ignoring Bob's email would be rude, trying to answer will just open a can of worms, but I need to send this information over to Bob. Any advice? (We are all UK based). --- EDIT: as many comments have questioned the points raised by Bob I should be clear; they are *not* about technical features, nor about performance, they are complaining about some of our requests, which are all within the contract we have with this supplier.
2017/07/10
[ "https://workplace.stackexchange.com/questions/94674", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/70250/" ]
This is a fairly simple one I would have thought; > > Good Afternoon Alice, Bob, > > > I hope you're both well. > > > It's come to my attention that there are some further technical documents you need for the current project, which you'll find attached. > > > If you have any questions please let me know, > > > Thanks, > > > Puffafish > > > Send the email to both Alice and Bob, with both their emails in the "To" field (ie - don't CC it to one, treat them both with equal importance). Make no reference to the previous email - as far as you're concerned you've dealt with it with his manager, and you no longer need to be involved. *Oh, and probably use your real name at the end too...*
Beware, you are facing serious dangers! It is not about your personal anger (which is reasonable), there is a contact between two companies, both are important to your bosses and you can't see all of the circumstances! For example, it is possible that your company mis-uses currently an old company relation on a way, that it causes trouble to the employer of your supplier company with it your are in contact! But this Bob doesn't know who are you inside your company, but he is angry to the company. But there are a nearly infinite possibilities here. You don't know all details, but you know that you won't interfere with them. Your primary goal is to *avoid anything what could worsen the relation between your employer and the supplier!* And, of course, to protect your ass. And, to show your bosses that you are wanting to solve the problems and relations. *If the bosses start to investigate, who insulted who, you have to make sure that nobody will find that also you made an offense.* Furthermore, Bob surely committed now a mistake. Particularly in the UK, where the customs are very polite. But you can see here also in the SE, full with people from anglo-saxon culture, that you can politely, indirectly f\*off nearly everybody into the hell (and get the same back), but in the moment that you use any bad word, you will be the only badass in the whole picture on the spot. So, what you should do: 1. Simply ignore any insulting part of Bob's mail. 2. React to the constructive part on your best. 3. Not only try to defend yourself, *try to really make Bob more friendly*. 4. If he repeats the offense, it will more clear that he is the bad man. 5. If he doesn't repeat, then a later investigation will find that you solved an intra-company problem. If the event doesn't repeat, it is a good thing to *not* mentioning the case upwardly. Maybe only as a nuance, and only verbally. ("Heyy, this Bob wasn't very happy, he wrote something that we are again late with the payment, but finally we could agree that the pallets will be delivered to the Liverpool garage until next Wednesday"). *In general, a cooperative person hesites to transmit negative communication, tries to avoid it, while he is eager to transmit positive things.* And you want to be a cooperative person, with high social skills. Particularly if you want to be useful for your employer in the communication and organizing tasks with partner companies. --- Your goal shouldn't be to let exterminate Bob by Alice, your goal should be to take care to the good contact between the companies. And you want to show that you can solve communication clashes alone with good results. Btw, if Bob doesn't do this repeatedly, then you should really look over it. Everybody can have a bad day, it is not a reason to conspire against him.
101,270
So throughout *Infinity War* and in the current *Endgame*, the Time Stone was never touched with bare hands, it seemed to be surrounded by a certain aura and gets transferred from person to person untouched. Is there a special reason behind it? [![enter image description here](https://i.stack.imgur.com/WSDCN.jpg)](https://i.stack.imgur.com/WSDCN.jpg)
2019/05/28
[ "https://movies.stackexchange.com/questions/101270", "https://movies.stackexchange.com", "https://movies.stackexchange.com/users/64925/" ]
There are no official sources for this, just some theories and speculations: One speculation says **it can be touched**, but just like the power stone, you will suffer the effects of touching an infinity stone (Maybe it kills you, vaporizes you, etc). And that's why the [Eye of Agamotto](https://marvelcinematicuniverse.fandom.com/wiki/Eye_of_Agamotto) was created: > > The Eye was created by Agamotto, using the Time Stone as a component to allow the user to safely wield it without directly touching it and suffering the adverse effects of touching an infinity stone. The container was created in the shape of an eye, hence its name. The mystical properties of the relic, as well as the spells and gestures necessary to use it > > > One other theory that I really like is that the stone represents **Time**, and time isn't really a physical thing that you can touch it.
Not all the Infinity Stones are harmful to human touch. As seen on screen only the power, reality and space stones have been shown to be damaging to touch. And the space stone is only harmful when taken out of working machinery while it was being actively used. With that said its possible that the time stone has the magical aura since we see it primarily handled by wizards when they take it or pass it, as Dr.Strange giving it to Thanos. The Eye then could be thought of as device to control and channel its powers. Like the Tesseract which housed the space stone, the power stone which requires a container separating it from organic matter to prevent it from setting off uncontrollably whenever it comes into contact, the Aether requiring a live host to thrive and function. So putting the Time Stone into contact with a living being could have some unforeseen effect.
31,870,063
I have a Rabbit struct, and CrazyRabbit struct that inherits it. When I execute this code: ``` #include <iostream> using namespace std; struct Rabbit { virtual void sayCry() { cout << "..." << endl; } }; struct CrazyRabbit : Rabbit { void sayCry() { cout <<"Moo"<< endl; } }; void foo(Rabbit r, Rabbit* pr, Rabbit& rr) { r.sayCry(); pr->sayCry(); rr.sayCry(); } int main(int argc, char *argv[]) { Rabbit *pr = new CrazyRabbit(); foo(*pr, pr, *pr); } ``` I have the results: ``` ... Moo Moo ``` Why the first case executes the method in super class? Is there any rule for execution defined in C++?
2015/08/07
[ "https://Stackoverflow.com/questions/31870063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
When I store data: 1. User preference data: Settings,Accounts... - **NSUserDefaults** 2. Security data:passwords - **KeyChain** 3. Small amount of data that do not need complex query - **Plist,Archiver** 4. Big amount of data which need Structured Query - **Coredata/SQLite(FMDB)**.
If you want to use operations of a database like `adding, deleting or updating` data later on then its recommended to use database libraries like `CoreData Or Sqlite` Otherwise if your data is not that big and it is mostly static then it is totally fine to use `NSUserDefaults` .
20,256,062
How to make my computer as a server so I run the application on IDE and be accessible by other computers on same network via their browsers?
2013/11/28
[ "https://Stackoverflow.com/questions/20256062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2209477/" ]
Each subdomain is generally treated as a separate site and requires their own robots.txt file.
If your test folder is configured as a virtual host, you need robots.txt in your test folder as well. (This is the most common usage). But if you move your web traffic from subdomain via `.htaccess` file, you could modify it to always use robots.txt from the root of your main domain. Anyway - from my experience it's better to be safe than sorry and put (especially declining access) files robots.txt in all domains you need to protect. And double-check if you're getting the right file when accessing: ``` http://yourrootdomain.com/robots.txt http://subdomain.yourrootdomain.com/robots.txt ```
174,345
I'd like to directly control custom properties of my empties and bones in Animation Nodes tree, to avoid location, scale and rotation manipulation. "Object Attribute Input" doesn't work, even after using copy data path. My workaround is to create empty with scale controlled by custom properties, and this scale attribute is used in Animation Nodes tree, but I hope, I can do it .
2020/04/13
[ "https://blender.stackexchange.com/questions/174345", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/53826/" ]
You can use expression node to control property of object. Use `ctrl`+`shift`+`alt`+`c` on a property to get code. use that code inside expression node to get or set the data. For example an object Empty has two custom properties `A` and `B`. We can get value of `A` using `bpy.data.objects["Empty"]["A"]`. Similarly we can set value to `B` using `bpy.data.objects["Empty"]["B"]=x` where x is the data we provide. [![enter image description here](https://i.stack.imgur.com/bt05T.gif)](https://i.stack.imgur.com/bt05T.gif) Or you can replace the object name and property name by, [![enter image description here](https://i.stack.imgur.com/y614n.png)](https://i.stack.imgur.com/y614n.png)
the default Animation Nodes do not have 'Bone' sockets, [ClockMender](https://clockmender.uk/blender/animation-nodes/) wrote some nodes that would be useful for that.
3,185
In other words does it make a difference in the event that a recipe calls for a Red wine you use a Merlot, Cabernet, Shiraz ect..?
2010/07/25
[ "https://cooking.stackexchange.com/questions/3185", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/177/" ]
I tend to disagree a little bit on this. Cooking removes almost all of the subtlety from a wine, especially long cooking like in a reduction-based sauce. I'd like to see a double-blind taste of several reduced red varietals to see if you could tell much of a difference.
I am not a wine connoisseur. I actively *dislike* most red wines; I'm not a fan of tannins. So if a recipe calls for red wine as an important ingredient (Beef Bourguignon, for example), I simply won't make the recipe. Sometimes though, like in a risotto or a Chinese sauce, a bit of wine is a lovely touch. Sauvignon Blanc is a common white wine for cooking, but unless I use the whole bottle in the recipe, I end up throwing most of it away. Even vacuum sealed, non-fortified wines have a short life-span once opened. So, I keep two fortified wines in my fridge. They serve me well, I never find the need to buy any wines other than Dry Sherry and Dry Vermouth. If a recipe called for it, I might buy a Marsala. In the fridge, fortified wines like these last for months after being opened. For what it's worth, Gallo topped America's Test Kitchen taste testing of Dry Vermouth.
3,026,059
I'd like to have Ant automatically include or import resources matching a particular pattern, but I'm really struggling with the syntax. Here's what I've tried: ``` <import> <fileset dir="${basedir}" includes="*-graph.xml" /> </import> ``` However, I just get the error message ``` import requires file attribute or at least one nested resource ``` The documentation for import (and include) both say that you can use a nested resource collection, and the documentation for resource collections says <fileset> is a resource collection. I've Googled and can't find any useful examples at all. I'm using Ant 1.8.1 (verified with ant -version) EDIT Found the problem. Firstly, SOMETHING has to match the expression. With no files that match, it blows up - even with optional=true, which is odd! Secondly, the matching files have be valid Ant file (even if they just contain <project/> - simply creating an empty file wasn't good enough). Better error messages, please Apache! :-)
2010/06/11
[ "https://Stackoverflow.com/questions/3026059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361319/" ]
There are numerous Open Source licenses, but the ones I'd recommend are either BSD-style or the GPL. You'll have to decide which you like. Should people be able to take what you've done and wrap them into proprietary software and sell it, without necessarily giving back their changes? Up to you. A BSD-type license might get you more users, and a GPL-type license might get you more development help. If you're thinking of dual-licensing, with an open source and a commercial license, you almost certainly want to go GPL for the open source license, since BSD-style doesn't leave you with enough extra rights to sell. You keep the copyright on everything you do that's not for hire, unless you explicitly give it away. If you start getting help from other people, you need to decide what to do. You can ask for the copyright to be transferred to you, which will keep your complete copyright control at the expense of discouraging outside developers. You can trademark your software, to keep the branding, and this is independent of who owns what copyright. I'd advise talking to a lawyer about that, as trademark law isn't as clean as copyright law, and can vary from state to state. If you live in the US, you can probably get a lawyer referral from your local bar association, and it shouldn't cost much for an initial consultation. As Jonathan said, check the OSI for information on possible licenses. Pick one from there. They'll all work, more or less, unlike a license you might write up (unless you know what you're doing). Some sites, like Sourceforge, don't allow projects that are not under an OSI-approved license, so you'll get more options with an OSI license. Moreover, lots of people are already familiar with the standard licenses, and you won't have to explain your license to them.
[TL;DR Legal](http://www.tldrlegal.com "TL;DRLegal") allows you to look up open source software licenses and get a summary, in plain English, of what you Can, Can't and Must do with the software. It also allows you to see the affects of combining two licenses, although that option is misleadingly called "Compare Licenses."
39,411,108
In the interface I have an abstract method ``` Server launchInstance( Instance instance, String name, Set<String> network, String userData) throws Exception; ``` Now in my class that implements the previous interface, I am overriding this method but I do not need all the parameters because that will cause a lot of unnecessary tasks. In my implemented class I want to do something like- ``` @override Server launchInstance(Instance instance, String name) throws Exception; ``` How can I remove some unnecessary parameters in my implemented(from Interface) class while overriding?
2016/09/09
[ "https://Stackoverflow.com/questions/39411108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4508310/" ]
That's not possible with Java. An interface defines method that all implementing classes must support, in order to have a *unifying* API. One purpose is to be able to *exchange* implementations. I see a couple of options: * Add a second method to the interface with fewer parameters. But this requires, of course, that all implementations support this. This may therefore not be viable for you. * Implement an additional second interface, which defines the method with two parameters. ``` if (x instanceof Server2) // short-cut: do not need to compute network and userData ((Server2) x).launchInstance(instance, name) else { Set<String> network = …; x.launchInstance(instance, name, network, userData) } ``` * Simply ignore the additional parameters. * If you desperately need a unified interface and want to avoid computation costs of the additional arguments, wrap the optional arguments of type `T` using lazy evaluation (e.g. in a `Callable<T>`). If you do not need the values, simply never call the Callable.
nope, you just can break the compromisse behind the override... you will need to redesign the method signature for something a little bit more abstract...
10,396,404
I want to create a 2D Binary (Bit) Array in Python in a space and time efficient way as my 2D bitarray would be around 1 Million(rows) \* 50000(columns of 0's or 1's) and also I would be performing bitwise operations over these huge elements. My array would look something like: ``` 0 1 0 1 1 1 1 0 1 0 0 0 ... ``` In C++ most efficient way (space) for me would be to create a kind of array of integers where each element represents 32 bits and then I can use the shift operators coupled with bit-wise operators to carry operations. Now I know that there is a bitarray module in python. But I am unable to create a 2D structure using list of bit-arrays. How can I do this? Another way I know in C++ would be to create a map something like `map<id, vector<int> >` where then I can manipulate the vector as I have mentioned above. Should I use the dictionary equivalent in python? Even if you suggest me some way out to use bit array for this task it will be great If I can get to know whether I can have multiple threads operate on a splice of bitarray so that I can make it multithreaded. Thanks for the help!! EDIT: I can even go on creating my own data structure for this if the need be. However just wanted to check before reinventing the wheel.
2012/05/01
[ "https://Stackoverflow.com/questions/10396404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/741442/" ]
As per my comment, you may be able to use sets ``` 0 1 0 1 1 1 1 0 1 0 0 0 ``` can be represented as ``` set([(1,0), (3,0), (0,1), (1,1), (2, 1), (0,2)]) ``` or ``` {(1,0), (3,0), (0,1), (1,1), (2, 1), (0,2)} ``` an AND is equivalent to an intersection of 2 sets OR is the union of the 2 sets
How about the following: ``` In [11]: from bitarray import bitarray In [12]: arr = [bitarray(50) for i in xrange(10)] ``` This creates a 10x50 bit array, which you can access as follows: ``` In [15]: arr[0][1] = True In [16]: arr[0][1] Out[16]: True ``` Bear in mind that a 1Mx50K array would require about 6GB of memory (and a 64-bit build of Python on a 64-bit OS). > > whether I can have multiple threads operate on a splice of bitarray so that I can make it multithreaded > > > That shouldn't be a problem, with the usual caveats. Bear in mind that due to the [GIL](http://en.wikipedia.org/wiki/Global_Interpreter_Lock) you are unlikely to achieve performance improvements through multithreading.
47,712,102
I have an micro SD card, that was in a Galaxy J5 with Android 7, and all the files are messed up now. (jpg, pdf, mp3) Following characters can be found in the beginning in all of the files, with minor changes in each one. > > <ŕ’Ż4i“µŢî Ś- `6Sĺş§uť?ŃÖ0Ü]@Î.0€Ň(QlüŚíď¦îRíb\_CONSOLE sżăm:Ń .. > > > .. and then a lot of NULLs following. The `_CONSOLE` part is there in every file. That's why I think that all files were manipulated with the same method. I am looking for somebody who has seen this kind of files.
2017/12/08
[ "https://Stackoverflow.com/questions/47712102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3442907/" ]
I have seen it several times, it appears file based encryption. It is not limited to Android Linux, some NAS devices use it (- eCryptFS file-level encryption). [![enter image description here](https://i.stack.imgur.com/5ZGMy.png)](https://i.stack.imgur.com/5ZGMy.png)
Seems the OS has written something along the lines of a table into the start of file/a way to read them. I am pretty sure the data is still there, just not visible. Try opening them via a hex editor and check if the NULL's are really null bytes or unreadable data
17,083,790
In my script, I am taking a text file and going through the file line by line and replacing the string "test" with "true", then redirect it to a new file. Here's my code: ``` cat $FILENAME | while read LINE do echo "$LINE" | sed -e `s/test/true/g` > $NEWFILE done ``` However when I execute the script I get the following errors: ``` /home/deploy/KScript/scripts/Stack.sh: line 46: s/test/true/g: No such file or directory sed: option requires an argument -- e Usage: sed [OPTION]... {script-only-if-no-other-script} [input-file]... -n, --quiet, --silent suppress automatic printing of pattern space -e script, --expression=script add the script to the commands to be executed -f script-file, --file=script-file add the contents of script-file to the commands to be executed -i[SUFFIX], --in-place[=SUFFIX] edit files in place (makes backup if extension supplied) -c, --copy use copy instead of rename when shuffling files in -i mode (avoids change of input file ownership) -l N, --line-length=N specify the desired line-wrap length for the `l' command --posix disable all GNU extensions. -r, --regexp-extended use extended regular expressions in the script. -s, --separate consider files as separate rather than as a single continuous long stream. -u, --unbuffered load minimal amounts of data from the input files and flush the output buffers more often --help display this help and exit --version output version information and exit ``` Can you please help me find what I am doing wrong ?
2013/06/13
[ "https://Stackoverflow.com/questions/17083790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1557816/" ]
For errors like this, put `set -x` in the line before `echo "$LINE" | sed -e 's/test/true/g' > $NEWFILE` ``` set +x echo "$LINE" | sed -e `s/test/true/g` > $NEWFILE ``` Bash will then print the command line before it executes it, quoting the arguments. This should give you an idea why it fails. Make sure you use the correct quote characters. ` (backtick) and ' (single quote) are different things. The first one will try to execute the command `s/test/true/g` and pass the result of this command to `sed`
When using sed, you should quote replacement parameters in single or double quotes. For example, this should work: ``` echo "$LINE" | sed -e "s/test/true/g" > $NEWFILE ```
7,211
What was the first home computer and file system that allowed users to choose freely between 3rd party applications? I was under the impression that early PC (manufacturer) bundled their own applications (like word processor or spreadsheet program) without any means to have another application be used instead. Was this the case? If so, what was the nature of the change toward allowing users to grant third party applications the same privileges?
2018/08/07
[ "https://retrocomputing.stackexchange.com/questions/7211", "https://retrocomputing.stackexchange.com", "https://retrocomputing.stackexchange.com/users/10296/" ]
> > which allowed the user to choose freely between 3rd party applications in opening data files. > > > and (from a comment) > > I was under the impression that early PCs bundled their own applications (like word processor or spreadsheet program) without any means to have another application be used in its place (or documented means?). Was this the case? If so, what was the nature of the change toward allowing users to grant third party applications the same privileges? Thanks > > > The Answer is simply **every OS** and **every PC**. Back in *ye good ol' days* OSes were way too primitive to even try something like a closed system. They where merely loaders to start some application. Early microcomputers were complete open systems. Home computers and later PCs even more so. The first such were bare hardware, delivered without an OS. If at all, only a monitor program was supplied – sometimes as small as 256 Bytes, offering nothing more than a chance to examine and change memory locations. The Altair for example was delivered completely without anything. Programs had to be entered bit by bit via switches. Not too much of a hassle considering that the main memory was just 256 bytes. Any OS would have to be either user written, or bought in addition. Even more so applications. While home computers like PET, TRS-80 or Apple II became soon more lavish, they still only supplied some frugal (by today's standards) monitor and BASIC as high level language and OS. OSes more like today only became available after disk drives where sold. Still manufacturers did only offer a DOS and, if at all, a very limited selection of software, mostly restricted to languages and tools. Or in case of home computers like Atari 800 maybe some games. The majority of applications where third party. Similar there where OSes for each of these machines by third party suppliers. Usually due the fact that the original DOS was rather limited (\*1). The market was quite open, and maybe except for some strange people no one could imagine what a closed system would be good for. In fact, even the idea of bundling was not much thought about. The first (successful) machine with an application package included was the (professional) [Osborne 1](https://en.wikipedia.org/wiki/Osborne_1) of 1981. Here [wordprocessor](https://en.wikipedia.org/wiki/WordStar), [spreadsheet](https://en.wikipedia.org/wiki/SuperCalc), [database](https://en.wikipedia.org/wiki/DBase) and [BASIC](https://en.wikipedia.org/wiki/CBASIC) was bundled with an OS. Still, the OS was [CP/M](https://en.wikipedia.org/wiki/CP/M), an open, manufacturer independent OS, open to any kind of third party application. Another kind fitting your idea would be early handheld LCD portables like the [Kyotronic 85](https://en.wikipedia.org/wiki/TRS-80_Model_100) family (Tandy M100, Olivetti M-10, NEC PC-8201, NEC PC-8300). They came with applications preinstalled in ROM - much like todays phones. Again, it wasn't about convenience, but the convenience of instant on usability. They could as well install third party applications in RAM - some even got user accessible ROM slots to install third party ROM based applications. Without being open to third party software, computers might not have been the success they are at all. --- \*1 - Check for example [NewDOS](https://en.wikipedia.org/wiki/NewDos/80) for the TRS-80
While there were a few systems that associated data closely to integrated applications, they were few and far between, and generally speaking were, for the most part, not what you'd usually consider a "home computer". The best known, I suspect, was the [Xerox Star](https://en.wikipedia.org/wiki/Xerox_Star). The Star was the first truly commercial system to be built with what we'd recognise today as a standard GUI (it was the successor of Xerox's research system, the Alto, which was [never sold commercially in anything other than a half-hearted way](https://retrocomputing.stackexchange.com/questions/5114/why-would-xerox-not-try-to-market-the-alto-to-the-public)). It had many, many innovative new ideas (including a WYSIWYG word processor, a system for embedding objects produced by one application inside a document managed by another, a "desktop" interface, icons, and so on). It also had a file system that tracked the creator of each file, so that if you clicked on the file's icon it would open it in the application that created it. It was also designed to be supplied with a set of standard applications and not be end-user extendable, so it does exactly match the kind of interface you're looking for. The only thing is, you wouldn't really call it a home computer: Xerox never really marketed it other than to large businesses, so they never became popular enough that individuals wanted to buy them. They also cost well in excess of an average person's annual salary. In the year the IBM PC went on the market at $1,600, they sold for $16,000. The Alto and the Star had, however, inspired a number of other people to produce similar systems. The most popular of these was the Apple Mac, which used the same system of associating a file with its creator in order to allow it to be automatically opened when the file's icon was clicked. The Mac was much closer to what you'd call a home system, but didn't have the closed ecosystem: it allowed (and in fact Apple encouraged the development of) new applications, and as any application could register the types of data it could work with, the system would allow the user to change what application would be used for any particular file just by selecting them from a list. Other systems followed Apple's lead: Microsoft Windows switched from application-based interface to document-based in version 3 (IIRC), using file extensions to associate applications via a list stored in the win.ini file (which was, of course, easily modified to add new applications, but didn't provide any easy way of supporting a file type that could work with multiple applications), and other systems like the Commodore Amiga or Acorn's RiscOS also implemented similar mechanisms. Another common type of system where data was associated directly with applications was in portable/"palmtop" computers, e.g. the [Psion Organiser](https://en.wikipedia.org/wiki/Psion_Organiser), which (at least in early versions) either didn't support additional applications or were difficult to develop for so few applications became available. Such systems only really became truly flexible in the 90s, with systems like the PalmPilot (which directly copied many parts of the Apple Mac user interface and API, including its use of 4-character codes to identify data types) and Microsoft's Windows CE being among the first to have many third party applications.
115,664
> > I exist just before your eyes but you can't touch me > > You can be anywhere but I will be nowhere > > I can be bought but no one truly owns me > > People buy me but I don't truly exist > > I am 3 on a 2 > > Some consider me an investment some consider me nothing > > Some say I am the future, some say I am just a trend with an end > > > Hint > > I have 9 letters > > > Hint 2 > > "I am 3 on a 2" you are looking at this. > > > Hint 3 > > I am a type of NFT > > >
2022/04/07
[ "https://puzzling.stackexchange.com/questions/115664", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/78801/" ]
Are you > > Bitcoin? > > > *I exist just before your eyes but you can't touch me* *You can be anywhere but I will be nowhere* > > You can see it on a screen anywhere, but it doesn't truly 'exist'. > > > *I can be bought but no one truly owns me* *People buy me but I don't truly exist* > > People can by bitcoin but it doesn't give them something physical to own. > > > *I am 3 on a 2* > > This could be talking about how bitcoin changes price and so it can be worth 3, on the second day maybe? > > > *Some consider me an investment some consider me nothing* > > Some people invest in bitcoin while others don't care/ know about it. > > > *Some say I am the future, some say I am just a trend with an end* > > Some people say bitcoin is the future of currency. > > >
Answer: > > Zuck Bucks > > > I exist just before your eyes but you can't touch me > > zuck bucks are virtual > > > You can be anywhere but I will be nowhere > > you can take zuck bucks anywhere but they're nowhere > > > I can be bought but no one truly owns me > > you can buy zuck bucks but don't really own them > > > People buy me but I don't truly exist > > you can buy zuck bucks but it doesn't really exist, it's virtual > > > I am 3 on a 2 > > Under Section 3(a)(2), a "bank" is defined broadly to mean any national bank, or any banking institution organized under the law. Zuck bucks is like this > > > Some consider me an investment some consider me nothing > > some think zuck bucks could be an investment, others think it's worth nothing > > > Some say I am the future, some say I am just a trend with an end > > some say zuck bucks are the future (i.e. Facebook), some say it will go away > > > Hint > > *I have 9 letters* > > 9 letters in "zuck bucks" > > > Hint 2 > > *"I am 3 on a 2" you are looking at this.* > > Under Section 3(a)(2), a "bank" is defined broadly to mean any national bank, or any banking institution organized under the law. Zuck Bucks is like this > > > Hint 3 > > I am a type of NFT > > Zuck Bucks is an NFT > > >
47,460,613
It is crazy but the following code: ```js import { Component, Inject } from '@angular/core'; import { MatDialog, MatDialogRef, MatDialogConfig, MAT_DIALOG_DATA } from '@angular/material'; @Component({ selector: 'decline', templateUrl: './decline.component.html', styleUrls: ['../../../styles/main.css'] }) export class DeclineComponent { animal: string; name: string; config: MatDialogConfig = { disableClose: false, hasBackdrop: true, backdropClass: '', width: '250px', height: '', position: { top: '', bottom: '', left: '', right: '' } }; constructor(public dialog: MatDialog) { } openDialog(): void { let dialogRef = this.dialog.open(DialogOverviewExampleDialog, this.config); } } @Component({ selector: 'dialog-overview-example-dialog', template: ` This is nothing ` }) export class DialogOverviewExampleDialog { constructor( public dialogRef: MatDialogRef<DialogOverviewExampleDialog>) { } } ``` does not center (horizontally and vertically) the modal window whereas **in all examples** I have seen so far, it is nicely centered. I cannot find the problem... I have to say that I am using `'~@angular/material/prebuilt-themes/indigo-pink.css"`. Apart from that, I tried to center it manually by adjusting the **position object** inside config. However it does not accept something like `left: '50%-125px'`. Any good ideas, please?
2017/11/23
[ "https://Stackoverflow.com/questions/47460613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1642344/" ]
**Step 4 of Angular Material getting started.** ``` // Add this line to style.css of your app. @import "~@angular/material/prebuilt-themes/indigo-pink.css"; ``` [Step 4](https://i.stack.imgur.com/mEZ49.png) Be sure that you made all steps before. [Angular Material - Getting started](https://material.angular.io/guide/getting-started) P.S. It's helped me.
Define your config as follows: ```js config: MatDialogConfig = { disableClose: false, hasBackdrop: true, backdropClass: '', width: '250px', height: '', position: { top: '50vh', left: '50vw' }, panelClass:'makeItMiddle', //Class Name that can be defined in styles.css as follows: }; ``` In styles.css file: ```js .makeItMiddle{ transform: translate(-50%, -50%); } ```
42,933,704
I want to create a global shortToast and longToast method to use it dynamically in all other activities I have, so I don't have to define the Toast method in every activity. I've tried this, but Android Studio tells me that this is a memory leak: ``` public static Activity thisActivity = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); thisActivity = this; } public static void shortToast() { Toast.makeText(thisActivity, "message" , Toast.LENGTH_SHORT).show(); } public static void longToast() { Toast.makeText(thisActivity, "message" , Toast.LENGTH_LONG).show(); } ``` What can I do instead to achieve this goal having a global toast method (without memory leak)?
2017/03/21
[ "https://Stackoverflow.com/questions/42933704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2829128/" ]
Create a Utils class: ``` public class Utils { public static void showToast(String msg, Context ctx) { Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show(); } } ``` use it from Activity: ``` Utils.showToast("Message", this); ``` From Fragment: ``` Utils.showToast("Message", getActivity()); ```
Pass the `Activity` as a parameter to `shortToast()` and `longToast()`. Or, put these methods in a subclass of `Activity`, and have all your activities inherit from it. Then, you can get rid of the `static` keyword from the methods and the `thisActivity` field, and simply use `this`.
34,635,740
*(I originally asked this question in [this comment](https://stackoverflow.com/questions/7905110/logging-aspect-oriented-programming-and-dependency-injection-trying-to-make?lq=1#comment56990956_7906547), but Mark Seemann asked me to create a new question instead.)* I'm starting a new app (.NET Core, if that matters), and right now I'm trying to decide how exactly to do logging. The general consensus seems to be that logging is a cross-cutting concern, so the logger shouldn't be injected directly into the class that is supposed to log. Often, there's an example like the following class how **not** to do it: ``` public class BadExample : IExample { private readonly ILogger logger; public BadExample(ILogger logger) { this.logger = logger; } public void DoStuff() { try { // do the important stuff here } catch (Exception e) { this.logger.Error(e.ToString()); } } } ``` Instead, the class with the business logic shouldn't know about the logger ([SRP](https://en.wikipedia.org/wiki/Single_responsibility_principle)) and there should be a separate class which does the logging: ``` public class BetterExample : IExample { public void DoStuff() { // do the important stuff here } } public class LoggingBetterExample : IExample { private readonly IExample betterExample; private readonly ILogger logger; public LoggingBetterExample(IExample betterExample, ILogger logger) { this.betterExample = betterExample; this.logger = logger; } public void DoStuff() { try { this.betterExample.DoStuff(); } catch (Exception e) { this.logger.Error(e.ToString()); } } } ``` Whenever an `IExample` is needed, the DI container returns an instance of `LoggingBetterExample`, which uses `BetterExample` (which contains the actual business logic) under the hood. ### Some sources for this approach: Blog posts by [Mark Seemann](https://stackoverflow.com/users/126014/mark-seemann): * [Instrumentation with Decorators and Interceptors](http://blog.ploeh.dk/2010/09/20/InstrumentationwithDecoratorsandInterceptors/) * [Dependency Injection is Loose Coupling](http://blog.ploeh.dk/2010/04/07/DependencyInjectionisLooseCoupling/) Blog post and SO answer by [Steven](https://stackoverflow.com/users/264697/steven): * [Meanwhile... on the command side of my architecture](https://cuttingedge.it/blogs/steven/pivot/entry.php?id=91) * [Windsor - pulling Transient objects from the container](https://stackoverflow.com/a/9915056/6884) --- My question: ============ Obviously, the `LoggingBetterExample` approach only works as long as the logging can be done outside the actual class. (like in the example above: catch any exceptions thrown by `BetterExample` from outside) My problem is that I'd like to log other things inside the actual class. Mark Seemann [suspected here](https://stackoverflow.com/questions/7905110/logging-aspect-oriented-programming-and-dependency-injection-trying-to-make?lq=1#comment42283040_7906547) that if someone needs to do this, maybe the method in question is doing too much. As I said before, I'm in the planning phase for a new application, so I don't have much code to show, but the use case I'm thinking right now is something like this: My app will have a config file with some optional values. The user may decide to omit the optional values, but it's an important decision to do this. So I'd like to log a warning when some of the optional values are missing, just in case it happened by error. *(omitting the values is perfectly fine though, so I can't just throw an exception and stop)* This means that I will have a class which reads config values and needs to do something like this (pseudocode): ``` var config = ReadConfigValues("path/to/config.file"); if (config.OptionalValue == null) { logger.Warn("Optional value not set!"); } ``` No matter if `ReadConfigValues` is in this class or a different one, I don't think this class would violate the SRP. ### When I'm not able to log outside the actual class by using a decorator, is there a better solution than to inject the logger? I know I could read the config file in the inner class, but check the values (and log the warning) in the decorator. But IMO checking the value is business logic and not infrastructure, so to me it belongs in the same class where the config file is read.
2016/01/06
[ "https://Stackoverflow.com/questions/34635740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6884/" ]
> > checking the value is business logic and not intfastructure, so to me it belongs in the same class where the config file is read. > > > Obviously, I don't know your domain well enough to dispute the truth of that assertion, but that *logging* is part of the domain model sounds strange to me. Anyway, for the sake of argument, let's assume that this is the case. What ought *not* to be the case, though, is that *reading a configuration file* is domain logic. While reading and manipulating the *data* from a file could easily be domain logic, reading a file is I/O. The [most common approach to Inversion of Control in application architecture is to employ the Ports & Adapters architecture](http://blog.ploeh.dk/2013/12/03/layers-onions-ports-adapters-its-all-the-same). The entire point of such an architecture is to decouple the domain model from I/O, and other sources of non-determinism. The poster example is to show how to decouple the domain model from its database access, but file access falls squarely in that category as well. What this ought to imply in this particular case is that you're going to need some `IConfigurationReader` interface anyway. This means that you can apply a Decorator: ``` public class ValidatingConfigurationReader : IConfigurationReader { private readonly IConfigurationReader reader; private readonly ILogger logger; public ValidatingConfigurationReader(IConfigurationReader reader, ILogger logger) { this.reader = reader; this.logger = logger; } public MyConfiguration ReadConfigValues(string filePath) { var config = this.reader.ReadConfigValues(filePath); if (config.OptionalValue == null) { this.logger.Warn("Optional value not set!"); } return config; } } ``` This `ValidatingConfigurationReader` class can be implemented in the domain model, even if the underlying, file-reading `IConfigurationReader` implementation belongs in some I/O layer.
Don't take SRP so seriously, otherwise you'll end up with functional programming. If you afraid of getting your class cluttered by putting log statements inside it, then you have two options. The first one you already mentioned which is using a Decorator class but you can't access/log the private stuff. The second option is using partial classes and putting the logging statements in a separate class.
7,277,296
I have a fullCalendar page that I am using qTip (v2) on. The problem is that the qTip tip is REALLY slow and sometime does seem to get the mouseover event so that I have to re-mouseover and then it fire. I have an ajax call in that I thought might be slowing it down but when I removed the ajax call there was no difference. The code below is the eventMouseover from fullcalendar. I didn't include all of the calendar code as I don't believe it is the problem. ``` eventMouseover: function(calEvent) { // start MouseOver if (typeof calEvent.TeamDetailID != 'undefined'){ //start undefined $(this).qtip({ content: { title: { text: calEvent.title }, text: 'Loading...', ajax: { url: '/inc/_runcfc.cfm', type: 'post', data: {cfc:'Display' , cfcMethod:'TeamDetail_popUpDetail' , TeamDetailID: calEvent.TeamDetailID }, success: function(data, status) { this.set('content.text', data); } } }, show: { delay: 0} }); // (this).qtip } //end if undefined } // end mouseOver ``` I would think that even with the ajax call the tip should pop quickly with the content of "loading...." regardless of the amount of time that it takes the ajax to replace the content. The code above "works" on every other mouseover but still slowly. Is there something wrong in how I am doing this?
2011/09/01
[ "https://Stackoverflow.com/questions/7277296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/886591/" ]
You mean like this? ``` foreach ( $_POST as $key => $value ) { echo "$key : $value <br>"; } ``` you can also use [`array_keys`](http://php.net/manual/en/function.array-keys.php) if you just want an array of the keys to iterate over. You can also use [`array_walk`](http://www.php.net/manual/en/function.array-walk.php) if you want to use a callback to iterate: ``` function test_walk( &$value, $key ) { ...do stuff... } array_walk( $arr, 'test_walk' ); ```
For just the keys: > > $array = array\_keys($\_POST); > > > Output them with: > > var\_dump($array); > > > -or- > > print\_r($array); > > >
9,517
When I was in school in Romania I remember my history teacher saying that historically Romania has seen a lot of invaders (referring mainly from the middle ages-present) because it used to have a lot of natural resources. To what extent is this true? I know that Hitler used to get a part of his oil from a city in Romania called Constanta, and right now there is a controversy in Romania because a Canadian firm wants to purchase the rights to a very large gold mine. But historically was Romania invaded for its natural resources? If not, then for what reasons? (I realize that this last question is VERY general, so I don't mind a VERY general answer, such as "usually to expand territory") Thanks.
2013/07/12
[ "https://history.stackexchange.com/questions/9517", "https://history.stackexchange.com", "https://history.stackexchange.com/users/2332/" ]
A full answer would have to do a detailed comparison of resources and relative numbers of invasions across time and territories, which is a bit much, or else track down the motivations of leaders for each particular war, which someone might offer here. **Let me get at your question in two ways: 1) What resources were there, and how were they exploited by various states that controlled the territory 2) Why might your teacher have used that particular explanation, and put this into the context of a particular historiography.** For this, let me focus on two sources, cited below in form [Source:Page Number]: 1. Vlad Georgescu, *The Romanians: a History* 2. Lucian Boia, *History and Myth in Romanian Consciousness* Since it is best to be careful when we transport modern nation-states into the distant past where they did not exist, by "Romania," let us clarify this to refer to the various kingdoms, provinces, and other territories in history which had some form of political control that overlaps with the current borders of that state. These include the Dacian provinces in the Roman Empire, and at various times, Hungary, Transylvania, Wallachia, Moldavia, the Ottoman Empire, Austria, Russia, etc. **The Important Resources** Under Roman control, the resources of the region were "skillfully exploited" [1:7] by the empire. It was an important producer of grain, the gold mines of the Bihor mountains were particularly important, along with lead, copper, silver, iron and salt mines. Grain, that is, the agricultural wealth of the region continues to be important, but with the many conflicts, the plains of Wallachia and Moldavia were depopulated and did not return to intensive agriculture until after 1829. [1:21] The agricultural sector suffers in general under many conflicts, the power structure that prevents the development of agriculture, and poor harvests in general. [1:82] Instead, animal husbandry, especially cattle and hide exports, become important in Wallachia and Moldavia in particular and dominate from the 15th to 18th centuries. Oil comes into play in the 15th century in Moldavia and 16th century in Wallachia [1:24] but is not really a major part of the economy until the 20th century (when, as you mentioned, it is a key resource during WWII), though increases significantly after 1859. [1:125] When Ottoman pressures come to bear on the region, especially on Wallachia and Moldavia, the major extraction from the region is not resources but paid tribute, and later, when they are more fully incorporated into the empire, and during the "Phanariot" period in the 18th century, through direct taxation, make serious and important contributions to the Ottoman war machine. Beyond tributes, the Ottomans extracted other resources, especially grain, cattle, lumber, and saltpeter. [1:77] Mining doesn't come up that often though, and in 18th century, some efforts to take advantage of copper, mercury and gold mining are abandoned and mining "usually limited to salt" [1:82] After the establishment of an independent Romania in mid-19th century, however, it grows again to be an important bread basket and by 1913 is the 4th largest wheat exporter in the world [1:125] and in the interwar period up to 1940 becomes the 5th largest agricultural exporter in the world. [1:198] Overall, the early importance in mining for the Romans, and the importance in grain supplies for both Romans and later rulers were likely a draw, but, as with any territory invaded, the extraction of surpluses in the form of taxation would have been significant, but it would require a much more detailed comparison with other states to determine the relative attractiveness of these territories. Of course, besides the obvious tribute/taxation and resources, the region is also probably invaded as much as it was, because it happened to be on the way to something more important, especially in the context of the major Habsburg vs. Ottoman and Russia vs. Ottoman conflicts. In fact, Moldavia and Wallachia both actively tried to pursue their own autonomy by portraying themselves, in diplomatic communications to various neighbors, as useful buffer states in 1774, 1783, 1787, 1791, 1807, and 1829. [1:76] **The Historical Narrative** The portrayal of a Romania that is a frequently invaded territory is common to many, but not all nationalist historiographies but the "natural resources" argument may have something to do with preemptively foreclosing other explanations and passing on the idea of stable set of territory which "naturally" belongs to the Romanian nation. Since Romanian nationalism predominantly is based on an ethno-linguistic conception of a language and ethnic group with a common origin (except for some occasional "greater Romania" narratives that pop up over the past 150 years) this means that legitimate claim on territory is predominantly based on a people, language, religion, etc. wherever they are. Perhaps the most interesting recent thing I have seen written on this is: Holly Case, *Between States: The Transylvanian Question and the European Idea During World War II* Which looks at the way the "lost" territory of Transylvania plays between Hungarian and Romanian nationalism in the context of two allies of Germany in WWII. There is a fascinating "battle of the maps," for example, where the predominant map feature is not resources or historical claims, but colorful depictions of demographics. By focusing on claims of where the Romanian *people* are and how that is to be defined, the claims to territory move beyond historical legitimacy to claims or some other measure, which is true for a lot of 20th century struggles over territorial control, especially around or immediately after WWI. Since Hungary etc. can't justify, your teacher might argue, the argument on the basis on people (though they indeed did, as Case's book shows), they must have just been after the natural resources of the mountainous territories of Transylvania - for example. Lucian Boia suggests another hint, but it depends on when your teacher was telling you this. Pre-1989? Or after? Boia suggests that around 1993, with publication of *The Plot Against Romania* (focusing on 1940-1947) and Dan Zamfirescu's *War Against the Romanian People* there is an increasing theme in historiography to describe "plots" against Romania throughout its history where Romania's neighbors were, Poland-partition style, trying to tear the nation apart and gobble up its various parts. [2:175-178] Perhaps your teacher, if we are talking 1990s here, was influenced by this trend.
I believe Romania's chief misfortune during the Middle Ages was to be right next to Eurasian Steppe, in an era when settled communities really had no military answer to the expert horse archers that steppe country naturally incubated. ![enter image description here](https://i.stack.imgur.com/0N7K6.png) Another view (for as long as the link lasts) ![enter image description here](https://i.stack.imgur.com/2KQXW.gif) To make matters worse, right on the other side of Romania is [the Hungarian Plain](http://en.wikipedia.org/wiki/Great_Hungarian_Plain) (or Alföld), which was also perfect territory for those same pastoralists. One can imagine that in the middle in their way was not a fun place to be. So in a way, yes Romania did contain valuable "resources", if you count good pasture land as a resource where militarily potent pastoralists are concerned.
53,940,373
I have created a common ajax call function for my application for optimizing code. the problem is while I call the function its freeze page. Please check below JS: ``` $(fuction(){ $('.btn').click(function(){ var data = getData('myaction/getinfo', []); }) }); function getData(url, data) { var result = ""; $.ajax({ url: url, type: 'POST', async: false, data: data, error: function () { console.log('error'); $('.custom-loader').fadeOut("slow"); }, beforeSend: function () { $('.custom-loader').fadeIn("slow"); }, complete: function () { $('.custom-loader').fadeOut("slow"); }, success: function (res, status) { result = res; $('.custom-loader').fadeOut("slow"); } }); return result; } ``` While I click a button, ajax request working pretty well but loader not showing until ajax return response (unable to click until response return). If I on async with `async: true` this will continue execution code which breaks functionality (Next execution depend on ajax response). Can anyone help me with this? Thanks an advance!
2018/12/27
[ "https://Stackoverflow.com/questions/53940373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5961782/" ]
```js var arr = [1,2,3,4,5]; console.log(arr.map((e)=> e + 2)) ```
You can always use the `.map()` operator to modify element values. For example, ``` let increaseByTwo = [1,2,3,4,5]; increaseByTwo = increaseByTwo.map(num=>num+2); console.log(increaseByTwo); ``` Or, if you really want to use a `for` loop, you can use this: ``` let increaseByTwo = [1,2,3,4,5]; for(let i = 0;i<increaseByTwo.length;++i){ increaseByTwo[i]+=2; } console.log(increaseByTwo); ``` This should both work.
664,189
I am working on finding the general solution to a disc colliding with a thin spinning rod in two dimensions floating in free space. The collision is perfectly elastic. The width of the rod is negligible. Shown below is the situation and known variables. Omega is the angular velocity of the rod spinning about its center. Theta is the orientation of the rod with respect to horizontal. l is the length of the rod and d is the diameter of the disc. r is the coordinate for the center of mass of each object.[![Picture](https://i.stack.imgur.com/XKb7Q.png)](https://i.stack.imgur.com/XKb7Q.png) There are 5 variables that change after the instantaneous collision: Vx1, Vy1, Vx2, Vy2, and omega, so there must be 5 equations to completely determine the final state. I can only think of 4: 1) conservation of energy, 2) conservation of linear momentum x and 3) y, and 4) conservation of angular momentum. I think the 5th equation has to do with the orientation of the ball and rod like how far the ball strikes from the rod's center and what the rod's current angle is, but I cannot think of it. What is the 5th equation to make it generally solvable? Am I missing something somewhere else? Context: I am working on a computer simulation and need to solve the equation generally to work with any conditions. I am fully aware that the equations will be disgusting.
2021/09/04
[ "https://physics.stackexchange.com/questions/664189", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/274939/" ]
[![enter image description here](https://i.stack.imgur.com/8hJSz.png)](https://i.stack.imgur.com/8hJSz.png) here are the equations : $$m\_1\left(v\_{1xf}-v\_{1xi}\right)=p\,\sin(\alpha)$$ $$m\_1\left(v\_{1yf}-v\_{1yi}\right)=-p\,\cos(\alpha)$$ $$m\_2\left(v\_{2xf}-v\_{2xi}\right)=-p\,\sin(\alpha)$$ $$m\_2\left(v\_{2yf}-v\_{2yi}\right)=p\,\cos(\alpha)$$ $$ I\,\left(\omega\_f-\omega\_i\right)=-p\,r $$ The velocity towards the normal vector $$\sin(\alpha)\left(v\_{2xf}-v\_{1xf}\right)+\omega\_f\,r-\cos(\alpha)\left(v\_{2yf}-v\_{1yf}\right)+\\ \sin(\alpha)\left(v\_{2xi}-v\_{1xi}\right)+\omega\_i\,r-\cos(\alpha)\left(v\_{2yi}-v\_{1yi}\right) =0$$ 6 equations for 6 unknowns $~v\_{1xf}~,v\_{1yf} ~,v\_{2xf}~,v\_{2yf} ~,\omega\_f~,p$ * $v~$ velocity * $\omega~$ angular velocity * $p~$ linear momentum * $ I=\frac 12 m\_2\,l^2~$ moment of intertia * index f final * index i initial **Edit** you start with the equation of motion at the collision time $$ m\,\frac{dv\_x}{dt}=f\_c\,\sin(\alpha)\\ m\,\frac{dv\_y}{dt}=-f\_c\,\cos(\alpha)$$ where $f\_c ~$ is the constraint force. multiply with dt and integrating you obtain $$ m\,(v\_{xf}-v\_{xi})=\underbrace{\int f\_c\,dt}\_{=p}\,\sin(\alpha)\\ m\,(v\_{yf}-v\_{yi})=-\int f\_c\,dt\,\cos(\alpha)$$ analog writing the equation of motion for the rotation . **energy conservation** $$\frac 12 m\_1\, \vec v\_{i1}\cdot \vec v\_{i1} + \frac 12 m\_2\, \vec v\_{i2}\cdot \vec v\_{i2}+ \frac 12 I\,\omega\_i^2 =\frac 12 m\_1\,\vec v\_{f1}\cdot \vec v\_{f1}+ \frac 12 m\_2\,\vec v\_{f2}\cdot \vec v\_{f2}+ \frac 12 I\,\omega\_f^2$$ **linear momentum conservation** $$m\_1\left(v\_{1xf}+v\_{1yf}\right)+ m\_2\left(v\_{2xf}+v\_{2yf}\right)= m\_1\left(v\_{1xi}+v\_{1yi}\right)+ m\_2\left(v\_{2xi}+v\_{2yi}\right)$$
In a complex collision, you frequently need to know something about the conditions after the collision. That reduces the number of unknowns, and appears to the case in this situation. In this case, you might make the (questionable) assumption that the angle of reflection for the disk is the same as the angle of incidence. But then again, if a disk undergoes a collision at an angle, it is likely to come away with a spin (and that would change the angle and introduce another unknown).
2,968,289
I'd like to ensure that certain maintenance tasks are executed "eventually". For example, after I detect that some resources might no longer be used in a cache, I might call: [self performSelector:@selector(cleanupCache) withObject:nil afterDelay:0.5]; However, there might be numerous places where I detect this, and I don't want to be calling cleanupCache continuously. I'd like to consolidate multiple calls to cleanupCache so that we only periodically get ONE call to cleanupCache. Here's what I've come up with do to this-- is this the best way? [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(cleanupCache) object:nil]; [self performSelector:@selector(cleanupCache) withObject:nil afterDelay:0.5];
2010/06/03
[ "https://Stackoverflow.com/questions/2968289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51503/" ]
The sequence of columns is really irrelevant in a strict (functional) sense, in any RDBMS - it's just a "nicety" to have for documentation or humans to look at. SQL Server doesn't support any T-SQL commands to order the columns in any way. So there is no syntax in T-SQL to accomplish this. The only way to change that is to use the visual table designer in SSMS, which really recreates the whole table from scratch, when you move around columns or insert columns in the middle of a table.
This is a *safe* work around without using temp table. After you add the column towards the end, simply go to SQL Sever Management Studio. Click on the table, select -> Design (or Modify) **and drag the last column to where ever position you want**. This way you do not have to worry about loosing data and indexes. The only other option is to recreate the table which can be problematic if you have large data. This answer is for helping other people and not intended to be accepted as answer.
45,976,463
I know it allows a third party to have access to the user's data of the another website. If I just want to make an e-commerce website with Facebook login, and it'll only be used by my customer, is it an overkill to use OAuth?
2017/08/31
[ "https://Stackoverflow.com/questions/45976463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5241511/" ]
Disabling *auto* update is not required, and is actually *counter productive*. Keep in mind that people have legitimate reasons to continue using JREs or JDKs for Java 8 (probably *several* years into the future). It is very much the same as with previous major releases of Java: ideally you *plan* about moving forward at some time - but there is absolutely no side *forcing* you when to make that move. We *started* using Java 8 for production like 12 months ago - and we still have products out in the field that run on Java 6. In that sense: * you educate yourself about the changes that Java9 is offering * you mainly identify a "path forward" for your deliveries around the new module system * you start experimenting with Java9 at some point ... and then, when you decide "we are ready" - then you move forward.
I believe no, as JAVA 9 has SO BIG change caused by its jigsaw(the change is so huge and make java 9 delay again and again ), such big chance has potential to break your current java application. BTW: java 9 will finally release in this month.
4,486
Say I've got two 1-dimensional lists ``` A = {1,2,3} B = {a,b,c} ``` How do I 1. create a list of all pairs from list `A` such that the result looks like `{{1,2},{1,3},{2,3}}`? 2. create a list of all pairs from lists `A` and `B` such that the result looks like `{{1,a},{1,b},{1,c},{2,a},{2,b},{2,c},{3,a},{3,b},{3,c}}`? I would also need both options, one with no duplicates as above and one with duplicates, e.g. one where the result from case 1 also includes `{{2,1},{3,1},{3,2}}`.
2012/04/19
[ "https://mathematica.stackexchange.com/questions/4486", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1044/" ]
**Ad. 1** ordering not valid: ``` Subsets[A, {2}] ``` > > > ``` > {{1, 2}, {1, 3}, {2, 3}} > > ``` > > or with ordering ``` Permutations[A, {2}] ``` **Ad. 2** ``` Outer[List, A, B] ``` > > > ``` > {{{1, a}, {1, b}, {1, c}}, {{2, a}, {2, b}, {2, c}}, {{3, a}, {3, b}, {3, c}}} > > ``` > > or exactly ``` Outer[List, A, B] // Flatten[#, 1] & ``` > > > ``` > {{1, a}, {1, b}, {1, c}, {2, a}, {2, b}, {2, c}, {3, a}, {3, b}, {3, c}} > > ``` > >
Here's an answer for a variant of question #2 for those who were looking for something slightly different, as I was. The original question #2 is asking for a generalized outer product (matching up every element of the first list with every element of the second list), which is why Artes correctly gives `Outer[List, A, B]` as the solution. Here `List` is the operator to perform on each pair of elements. This lead me to solve my own problem, which was to create a generalized inner product list (matching up the i-th element of the first list with the i-th element of the second list), which looks like `{{1,a},{2,b},{3,c}}`. ``` Inner[List, A, B, List] ``` gives ``` {{1, a}, {2, b}, {3, c}} ``` Here, `List` replaces both the multiplication and addition functions in the usual inner product. This is useful if you have two lists for separate 1D histograms that you want to combine into a 2D histogram with `Histogram3D`.
63,746,006
I am developing an app for iOS and also using Mac Catalyst to run on my Mac. The app runs fine on my iPhone but always shows an error on Catalyst. The code used to run fine before updating to Big Sur Beta 6 from Beta 5. Here's a screenshot of the error: [![Here's a screenshot of the error](https://i.stack.imgur.com/hz0UM.png)](https://i.stack.imgur.com/hz0UM.png). Also the error in code blocks for anybody who wants to copy it. ``` The operation couldn’t be completed. (OSStatus error -10670.) Domain: NSOSStatusErrorDomain Code: -10670 User Info: { "_LSFunction" = "_LSOpenStuffCallLocal"; "_LSLine" = 3664; } -- System Information macOS Version 11.0 (Build 20A5364e) Xcode 12.0 (17210.1) ``` <https://github.com/MysteryCoder456/VegieMato/tree/backend> is the GitHub Repo if anybody wants to reproduce this (i.
2020/09/04
[ "https://Stackoverflow.com/questions/63746006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11396448/" ]
Faced same issue after upgrading to macOS 11 Beta 6. Reported bug to Apple but meanwhile found workaround - Select Product in Xcode, select 'Show in Finder'. Launch it from Finder. Additional step, hopefully Apple will look into it.
I also had the same problem. (I say had, I guess I still do, however I have a workaround) My App had been developed as iOS / iPadOS with Mac support. All has been working great throughout macOS 11 beta builds. Until today that is, when I, as you, updated to Beta 6. Upon attempting to run for macOS target I get the same error as you have posted. After some googling I found <https://www.virusbulletin.com/uploads/pdf/conference_slides/2015/Wardle-VB2015.pdf> and had a go at simply opening the app directly from the build folder. Hey presto, it opened without any problems, I even cleaned out the build folder and built it again to make sure. This would appear to be a problem that the next version of Xcode beta should fix. Until then, unless anybody can suggest a better fix, this will have to suffice for me at least :-( Sam
11,959,110
Ok, so I have an array: ``` numbers = ["2", "3", "4", "5"] ``` and I need to split the array into two arrays with a conditional ``` numbers.reject!{|x| x > 4 } ``` and what i need is one array `numbers` to contain `numbers = ["5"]` and another array with the rejects `rejects = ["2", "3", "4"]` How do I do this? ...It seems so easy with a loop but is there a way to do this in a one liner?
2012/08/14
[ "https://Stackoverflow.com/questions/11959110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/223367/" ]
Check out [`Enumerable#partition`](http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-partition) ``` arr = ["2", "3", "4", "5"] numbers, rejects = arr.partition{ |x| x.to_i > 4 } # numbers = ["5"] # rejects = ["2", "3", "4"] ```
``` numbers = [2, 3, 4, 5] n_gt_four = numbers.select{|n| n > 4} n_all_else = numbers - n_gt_four puts "Original array: " + numbers.join(", ") puts "Numbers > 4: " + n_gt_four.join(", ") puts "All else: " + n_all_else.join(", ") ``` Outputs: ``` Original array: 2, 3, 4, 5 Numbers > 4: 5 All else: 2, 3, 4 ```
13,821,314
I am trying to find a regular expression that will recognize files with the pattern as az.4.0.0.119.tgz. I have tried the regular expression below: ``` ([a-z]+)[.][0-9]{0,3}[.][0-9]{0,3}[.][0-9]{0,3}[.]tgz ``` But, no luck. Can anyone please point me in the right direction. Regards, Shreyas
2012/12/11
[ "https://Stackoverflow.com/questions/13821314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1308500/" ]
Better to use a simple regex like this: ``` ^([a-z]+)\.(?:[0-9]+\.)+tgz$ ```
Your pattern has 4 chiffers group, your regexp only 3.
66,644,472
Anyone could explain why the console logs below produce different output while I expected them to be exactly the same? ``` 'use strict'; const objectSelected = document.querySelector('.message'); console.log(`${objectSelected}`); console.log(objectSelected); ```
2021/03/15
[ "https://Stackoverflow.com/questions/66644472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15402917/" ]
The console will log any type of value: objects, arrays, functions, booleans, numbers, etc. Any time you put a non-string inside a string or concatenate a non-string with a string, JavaScript will call `.toString()` on the the thing which is not a string: ``` var obj = { foo: 'bar' } console.log(obj) //-> { foo: "bar" } console.log(obj.toString()). //-> "[object Object]" console.log('' + obj). //-> "[object Object]" console.log(`${obj}`). //-> "[object Object]" ```
When passing an object in a string template, it will be converted to a string. That's why the first statement will result in `[object <something>]`. The second will print the value as is (as an object). When passing an object to console.log, it will be printed as the full object.
46,767,885
it is easy to read the first value in the array below - but how to read the last value without deleting or looping with e.g. foreach? ``` $message_rate_array[0]['messages'] ``` sample array (real size is not foreseeable): ``` Array ( [0] => Array ( [messages] => 30584709 [time] => 1508147394 ) [1] => Array ( [messages] => 30585992 [time] => 1508147395 ) [2] => Array ( [messages] => 30587416 [time] => 1508147396.1 ) [3] => Array ( [messages] => 30588721 [time] => 1508147397.1 ) ) ```
2017/10/16
[ "https://Stackoverflow.com/questions/46767885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8613418/" ]
Using `end()` you can get the last value of array. **Working Demo: <https://eval.in/880691>** ``` <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); echo end($people); ?> ``` **Output:** `Cleveland`
Refer from <http://php.net/manual/en/function.end.php> you can do this as the easy and clear way. ``` $ArrayList = array(); echo end($ArrayList); ```
31,851,416
I have a string like this: ``` mystring = "A:\"" + var1 + var2 + var3 + "\""; ``` var1 var2 and var3 sometimes get null, sometimes getting string. When variables getting string, mystring returning like this: ``` A:"var1valuevar2valuevar3value" ``` I need to show like this: ``` A:"var1value var2value var3value" ``` I tried like this: ``` mystring = "A:\"" + var1 + " " + var2 + " " + var3 + "\""; ``` It's working but when variables get null, its returning like this: ``` A:" var2value var3value" ``` How can I remove unnecessary spaces? If a variable gets null, I don't need to have spaces between two variables or first character.
2015/08/06
[ "https://Stackoverflow.com/questions/31851416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4124087/" ]
You could use LINQ to filter out the empties, and use `string.Join` to concatenate them: ``` string s = string.Join( " " , new string [] {var1, var2, var3} .Where(x => !string.IsNullOrEmpty(x)) ) ```
Use below ``` string mystring = "A:\"" + AddSpace(var1) + AddSpace(var2) + var3 + "\""; public string AddSpace(String var) { return var == null ? "" : var + " "; } ```