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
1,412,442
here is the current complex query given below. ``` SELECT DISTINCT Evaluation.ETCode, Training.TTitle, Training.Tcomponent, Training.TImpliment_Partner, Training.TVenue, Training.TStartDate, Training.TEndDate, Evaluation.EDate, Answer.QCode, Answer.Answer, Count(Answer.Answer) AS [Count], Questions.SL, Questions.Question FROM ((Evaluation INNER JOIN Training ON Evaluation.ETCode=Training.TCode) INNER JOIN Answer ON Evaluation.ECode=Answer.ECode) INNER JOIN Questions ON Answer.QCode=Questions.QCode GROUP BY Evaluation.ETCode, Answer.QCode, Training.TTitle, Training.Tcomponent, Training.TImpliment_Partner, Training.Tvenue, Answer.Answer, Questions.Question, Training.TStartDate, Training.TEndDate, Evaluation.EDate, Questions.SL ORDER BY Answer.QCode, Answer.Answer; ``` There is an another column Training.TCode. I need to count distinct Training.TCode, can anybody help me? If you need more information please let me know
2009/09/11
[ "https://Stackoverflow.com/questions/1412442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169965/" ]
try ``` select ..., count(distinct Training.Tcode) as ..., ... ``` **EDIT - please now look at this...** Take the following SQL code. The first select is how SQL server would do this and the second query should be access compliant... ``` declare @t table (eCode int, tcode int) insert into @t values(1,1) insert into @t values(1,1) insert into @t values(1,2) insert into @t values(1,3) insert into @t values(2,2) insert into @t values(2,3) insert into @t values(3,1) select ecode, count(distinct tCode) countof from @t group by ecode select ecode, count(*) from (select distinct tcode, ecode from @t group by tcode, ecode) t group by ecode ``` It returns the following: ``` ecode tcode 1 3 (there are 3 distinct tcode for ecode of 1) 2 2 (there are 2 distinct tcode for ecode of 2) 3 1 (there is 1 distinct tcode for ecode of 3) ```
I managed to do a count distinct value in Access by doing the following: ``` select Job,sum(pp) as number_distinct_fruits from (select Job, Fruit, 1 as pp from Jobtable group by Job, Fruit) t group by Job ``` You have to be careful as if there is a blank/null field (in my code fruit field) the group by will count that as a record. A Where clause in the inner select will ignore those though. I've put this on my blog, but am concerned that I've discovered the answer too easily - others here seem to think that you need two sub queries to make this work. Is my solution viable? [Distinct groupings in Access](http://markfightscode.blogspot.com/2010/04/writing-count-distinct-query-in-ms.html)
40,132,831
I have a program to calculate tax payable on an income. The first method taxPayable() calculates the amount of tax that would be paid on this income and the second one incomeRemaining() should calculate the income remaining after the tax has been deducted but the variable tax is changing back to its first assignment of 0. How can i change my code so that it carries over to the next method? ``` public class TaxCalculator { static double tax = 0; public static void taxPayable(int income) { if (0 <= income && income <= 100) { double tax = 0; System.out.print("Tax payable on this income is equal to " + tax); } else if (101 <= income && income <= 150) { double tax = 0 + (income-100)*0.1; System.out.print("Tax payable on this income is equal to " + tax); } else if (151 <= income && income <= 200) { double tax = 0 + 50*0.1 + (income-150)*0.2; System.out.print("Tax payable on this income is equal to " + tax); } else if (201 <= income && income <= 300) { double tax = 0 + 50*0.1 + 50*0.2 + (income-200)*0.4; System.out.print("Tax payable on this income is equal to " + tax); } else if (301 <= income && income <= 400) { double tax = 0 + 50*0.1 + 50*0.2 + 100*0.4 + (income-300)*0.6; System.out.print("Tax payable on this income is equal to " + tax); } else { double tax = 0 + 50*0.1 + 50*0.2 + 100*0.4 + 100*0.6 + (income-400)*1.2; System.out.print("Tax payable on this income is equal to " + tax); } } public static void incomeRemaining(int income) { TaxCalculator.taxPayable(income); double $$ = income - tax; System.out.println("\nIncome remaining after tax is equal to " + $$); } public static void main(String[] args) { TaxCalculator.incomeRemaining(400); } ``` }
2016/10/19
[ "https://Stackoverflow.com/questions/40132831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7042553/" ]
``` double $$ = income - tax;//here tax is using your class static variable tax, which is never changed from 0. ``` To debug.. change your class variable to 1000 instead of 0 as a default value. In your taxPayable() method dont declare double tax again. Just use the variable without declaring it
because you are re-declaring variable `tax` - please read about [scopes](http://www.java2s.com/Tutorial/Java/0020__Language/VariableScope.htm). change each `double tax = ...` in your method `taxPayable(int income)` to just `tax`.
14,111,951
How do you mix the concepts of ASP.NET MVC and entityframework in a elegant and robust way when it comes to retrieving stuff from the database and visualizing it via the controller and view? The example below will throw Dispose exceptions because the View will be displayed after the using statement is closed. ``` // code in controller using (var usersDb = new UsersDb(new WebSecurityWrapper())) { var user = usersDb.GetUser(User.Identity.Name); return View(user); } // code in usersDb model -- GetUser method public User GetUser(string name) { var id = _webSecurity.GetUserId(name); var user = Users.FirstOrDefault(usr => usr.Id == id); return user; } ``` Pretty obvious, but the only alternative I can think of is "cloning" the user object so that the View can display it independently. That doesn't feel right. So what's the appropriate way of doing this?
2013/01/01
[ "https://Stackoverflow.com/questions/14111951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1470327/" ]
I think you are using navigation properties of the User object in the view. These are probably evaluated in a lazy way. The User object is created before you exit the method. Somehow you are requesting extra info which is queried in the view. But since the dispose already happended, this results in the exception. One option is to use [Include](https://stackoverflow.com/questions/3356541/entity-framework-linq-query-include-multiple-children-entities) to immediately query the extra necessary data.
``` User user; using (var usersDb = new UsersDb(new WebSecurityWrapper())) { user = usersDb.GetUser(User.Identity.Name); } return View(user); ```
6,586,886
Which technique is better: ``` <span onclick="dothis();">check</span> ``` or: ``` <span class="bla">check</span> <script type="text/javascript"> $('.bla').click(function(e) {} ); </script> ``` Are there any differences according to usability, performance etc.? Thank you!
2011/07/05
[ "https://Stackoverflow.com/questions/6586886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/830209/" ]
The second is better from a code quality standpoint since it is considered to be [unobtrusive](http://en.wikipedia.org/wiki/Unobtrusive_JavaScript). I am not certain if either approach has measurable performance benefits. My advice is to stick to the unobtrusive approach - it will save you a lot of time when you are doing maintenance down the road.
Technique 1 is intrusive or obstrusive JavaScript: Your markup is intermixed with your JavaScript calls, which can be really messy and is not a separation of concerns. Technique 2 is [unobstrusive](http://en.wikipedia.org/wiki/Unobtrusive_JavaScript): Your JavaScript is kept separate from the markup, keeping both clean but adds a lot of boilerplate code. Neither is better, although Technique 2 works better for larger projects for me, but always requires looking in two places and can introduce bugs by changing the markup but not the JavaScript.
11,781,358
Very strange error indeed. I have an item that clones itself every month, setting the next object to have a `scheduled_on` date, `+ 1.months` in the future. But then this happened : ``` Sun, 01 Apr 2012 16:00:00 PDT -07:00 Tue, 01 May 2012 16:00:00 PDT -07:00 Fri, 01 Jun 2012 16:00:00 PDT -07:00 Sun, 01 Jul 2012 16:00:00 PDT -07:00 Wed, 01 Aug 2012 16:00:00 PDT -07:00 Fri, 31 Aug 2012 17:00:00 PDT -07:00 # <--- What in the.. ``` The code : ``` def clone_object objects = [] Time.zone = account.timezone Chronic.time_class = Time.zone now = last_scheduled_on.to_time # <- this would have been Wed, 01 Aug 2012 16:00:00 PDT -07:00 new_date = now + 1.months new_schedule = Time.zone.parse new_date.strftime('%Y-%m-%d' + ' ' + original_scheduled_on.strftime('%H:%M:%S')) objects << clone!(:scheduled_on => new_schedule, :recurring_job_id => id) end ``` That is a very truncated version of the actual code. But it includes all the parts that I are reasonably affecting this issue. So the question is.. how could that error could have possibly occurred? **Update** I'm pretty sure this is timezone related. Here's the Dates in UTC: ``` In UTC : Sun, 01 Apr 2012 23:00:00 UTC +00:00 Tue, 01 May 2012 23:00:00 UTC +00:00 Fri, 01 Jun 2012 23:00:00 UTC +00:00 Sun, 01 Jul 2012 23:00:00 UTC +00:00 Wed, 01 Aug 2012 23:00:00 UTC +00:00 Sat, 01 Sep 2012 00:00:00 UTC +00:00 Sun, 30 Sep 2012 23:00:00 UTC +00:00 ``` Here they are converted to Pacific : ``` In Pacific Sun, 01 Apr 2012 16:00:00 PDT -07:00 Tue, 01 May 2012 16:00:00 PDT -07:00 Fri, 01 Jun 2012 16:00:00 PDT -07:00 Sun, 01 Jul 2012 16:00:00 PDT -07:00 Wed, 01 Aug 2012 16:00:00 PDT -07:00 Fri, 31 Aug 2012 17:00:00 PDT -07:00 Sun, 30 Sep 2012 16:00:00 PDT -07:00 ``` I also noted that the code I put here in not accurate to my server. The server has the Time.zone set to the last job and **not the account's timezone**. This means ( or at least I think it means ), that the timezone is then floating and dynamic. But that bothers me also because Daylight savings time in California does not switch over until November, not September.
2012/08/02
[ "https://Stackoverflow.com/questions/11781358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93311/" ]
have you tried .next\_month ? <http://api.rubyonrails.org/classes/Time.html#method-i-months_since>
Time calculations are always problematic. 1.month might be 30 days, 31 days, 28 days, or anything in between. It depends on the month being added, what you're adding to it, and so on. So errors like this are unfortunately and annoyingly common-place when doing date arithmetic. To correct this code, I would always ensure it selects the beginning of the month for the month you're in, like so: ``` new_date = (now + 1.months).beginning_of_month ``` That will always be the 1st of the month.
26,854,301
I was playing around with [JavaFX's `Tooltip`](https://docs.oracle.com/javafx/2/api/javafx/scene/control/Tooltip.html). I realized that for me personally the delay between hovering over something and the tooltip actually appearing is too long. A look in the API reveals: > > Typically, the tooltip is "activated" when the mouse moves over a Control. There is usually some delay between when the Tooltip becomes "activated" and when it is actually shown. The details (such as the amount of delay, etc) is left to the Skin implementation. > > > After some further investigation, I was not able to find any possibility to control the delay. The [JavaFX CSS Reference](https://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html) has no information about delay time and a runtime-evaluation of `getCssMetaData()` did not help either. I know that there is a way to control the tooltips manually via `onMouseEntered(...)` and `onMouseExited(...)`, but is there really no other way? Or am I missing an obvious solution?
2014/11/10
[ "https://Stackoverflow.com/questions/26854301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4216641/" ]
There is an existing feature request for this: [JDK-8090477 Customizable visibility timing for Tooltip](https://bugs.openjdk.java.net/browse/JDK-8090477). The feature request is currently scheduled for integration into Java 9. Attached to the issue I linked is a patch you can apply to allow you to get this functionality in earlier Java versions. Your other option is just to create your own popup control using one of the techniques in: * [JavaFX 2 custom popup pane](https://stackoverflow.com/questions/12717969/javafx-2-custom-popup-pane)
I find that with the above implementation there's still a delay sometimes that I cannot explain. The following has worked for me and removed the delay entirely: ``` public static void bindTooltip(final Node node, final Tooltip tooltip){ node.setOnMouseMoved(new EventHandler<MouseEvent>(){ @Override public void handle(MouseEvent event) { // +15 moves the tooltip 15 pixels below the mouse cursor; // if you don't change the y coordinate of the tooltip, you // will see constant screen flicker tooltip.show(node, event.getScreenX(), event.getScreenY() + 15); } }); node.setOnMouseExited(new EventHandler<MouseEvent>(){ @Override public void handle(MouseEvent event){ tooltip.hide(); } }); } ```
15,657,115
We have one function called `.any` in Prototype. I want the same like in Jquery. My Prototype code is: ``` if (item_name == '' || $R(1,ind).any(function(i){return($F("bill_details_"+i+"_narration") == item_name)})) { alert("This item already added."); } ``` I want to perform the Equivalent function using Jquery. Please help me to achieve the desired output. Thanks in Advance..
2013/03/27
[ "https://Stackoverflow.com/questions/15657115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1968826/" ]
JQuery has [.is()](https://api.jquery.com/is/) method, from documentation: `Check the current matched set of elements against a selector, element, or jQuery object and return *true* if at least one of these elements matches the given arguments`. Thus an equivalent code is: ``` if (item_name == '' || $([1,ind]).is(function(i) { return $('#bill_details_'+i+'_narration').attr('name') == item_name; })) { alert("This item already added."); } ```
According to JQuery's documentation if you return a false in the callback function it will break the loop: > > We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration. > > > Taken from: <http://api.jquery.com/jquery.each/>
55,816
I enjoy my road bike, but recently my children have become old enough to ride, but still very slowly. I'd like to be able to ride with them on all or mostly flat pavement, but the road bike just isn't pleasant for slow riding as it takes more effort to balance and isn't that comfortable. What type(s) of bike is well-suited for very slow comfortable riding like this?
2018/07/13
[ "https://bicycles.stackexchange.com/questions/55816", "https://bicycles.stackexchange.com", "https://bicycles.stackexchange.com/users/2313/" ]
You might want to consider a fat-bike. They're naturally slower, because they're meant for really rough terrain, so they have low gearing, high frame mass to be sturdy and higher rolling resistance due to the fat wheels. The fat wheels also make them pretty stable. Plus, if you're so inclined, after you don't need it for going slow anymore, you can keep on using it to do completely different kind of biking than your existing road bike: rough off-road.
I have a foldable bike which is quite comfy at low speeds (especially so probably due to the low CG). With the added advantage that you can transport it easily to kid friendly bike paths.
68,415,104
In Java, if I want to associated one value with an other I would simply do the following: ``` static final Map<String, String> VALUES_BY_NAME; static { final Map<String, String> valuesByName = new HashMap<>(); valuesByName.put("fruit", "apple"); valuesByName.put("drink", "Coke"); VALUES_BY_NAME = Collections.unmodifiableMap(valuesByName); } ``` And call this Hashmap using the following to return apple for example: ``` VALUES_BY_NAME.get("fruit") ``` Is there something similar with groovy for Jenkins?
2021/07/16
[ "https://Stackoverflow.com/questions/68415104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15856421/" ]
In Groovy you could do ``` def myMap = [fruit: 'apple', drink: 'coke'].asUnmodifiable() ```
> > I would simply > > > That isn't simple at all, though. Try this: ``` static final Map<String, String> VALUES_BY_NAME = Map.of( "fruit", "apple", "drink", "Coke"); ``` > > Is there something similar with groovy for Jenkins? > > > Groovy is a different language but uses the same java runtime library under the hood. You can invoke the exact same `Map.of` method from groovy as well.
7,320,443
I would like to minimize w'Hw, with respect to w, where w is a vector, and H is matrix. And with the following constraint, |w1|+|w2|+|w3| < 3, ie. the l1 norm of the weights vector is less that 3. How can I do this in matlab? Thanks
2011/09/06
[ "https://Stackoverflow.com/questions/7320443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/914738/" ]
you need to use the optimization toolbox, specifically [fmincon](http://www.mathworks.com/help/toolbox/optim/ug/fmincon.html): use fun to establish w'Hw, and you want `c(eq) = (|w1|+|w2|+|w3| - 3)` <0 which you set with nonlcon (in the documentation).
I'd suggest you look at the fminsearch function in the matlab documentation.
69,621,626
**Comment**: While I understand some concerns about the 'accuracy' of the data, I think it is really immaterial to the question. The data is what it is. Assuming so, would be interested in a possible solution. **---------** I need to read a file containing lines that have unicode characters. The lines contain multiple columns, each that starts at a fixed position. Here is an example (I have put the hyphens to indicate where an individual column ends, the hyphens are actually not part of the string). `0004-1235957-A CORU¥A -ABC` In the example above column 1 occupies the first 4 positions, column 2 occupies the next 7 positions, column 3 occupies the next 15 positions and column 4 occupies the next 3 positions and so on. I am using the following code to parse this line: ``` line = '00041235957A CORU¥A ABC\n' formats = ('4s 7s 15s 3s') st = struct.Struct(formats) fields = tuple(s.decode() for s in st.unpack_from(line.encode())) print(fields) ``` And this is the output I get: ``` ('0004', '1235957', 'A CORU¥A ', ' AB') ``` If you look at the last column, it is actually getting read incorrectly. The reason is that in unicode, the character '¥' takes up two bytes which leads to only the first 14 characters (and 15 bytes) getting read and column 4 being read from the following position. What I want is a way to read 15 **characters** for column 3 and not 15 **bytes** independent of the encoding present in the data. Even I try substring methods on the line, I get the same behavior. Could the experts provide some guidance on this please? Thank you.
2021/10/18
[ "https://Stackoverflow.com/questions/69621626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11731250/" ]
When you `line.encode()` the default encoding is `utf-8`. As you can see below, the `¥` symbol becomes two bytes `\xc2\xa5` throwing off your count: ``` >>> line = '00041235957A CORU¥A ABC\n' >>> line.encode() b'00041235957A CORU\xc2\xa5A ABC\n' ``` As the comments mentioned, you are likely mis-reading the file in the first place as a yen symbol isn't likely in the middle of what looks like a Spanish word. Be sure you know what the original encoding of the file is so you read the file correctly. Consider reading the file in binary e.g. `open(filename,'rb')` and posting the raw bytes of the line in question as a sample. Below are two "solutions": ``` import struct line = '00041235957A CORU¥A ABC\n' st = struct.Struct('4s7s15s3s') # encode with a single-byte encoding so the length doesn't change. fields = tuple(s.decode('latin1') for s in struct.unpack_from(line.encode('latin1'))) print(fields) # slice the string directly (RECOMMENDED) fields = line[:4],line[4:11],line[11:26],line[26:29] print(fields) ``` Output: ``` ('0004', '1235957', 'A CORU¥A ', 'ABC') ('0004', '1235957', 'A CORU¥A ', 'ABC') ```
Is you want to divide the line character-wise in a readable, repeatable way you can use [slice](https://docs.python.org/3/library/functions.html#slice) objects. ``` >>> s1 = slice(0, 4) >>> s2 = slice(4, 11) >>> s3 = slice(11, 26) >>> s4 = slice(26, 29) >>> slices = line[s1], line[s2], line[s3], line[s4] >>> slices ('0004', '1235957', 'A CORU¥A ', 'ABC') ``` Slice objects are functionally the same as taking a slice from a string or list, for example `s1 = line[0:4]`, but they are independent of the sequence being sliced. --- As pointed out in the comments and the other answer, it looks as if the data may not have be decoded correctly. It may help to know that the byte `b'\xa5'` is mapped to "¥" in the encodings cp1252, cp1253, cp1254, cp1255, cp1256, cp1258, iso8859\_15, iso8859\_8, iso8859\_9, latin\_1, palmos, but is mapped to "Ñ‎" in the encodings cp437, cp850, cp857, cp858, cp860, cp862, cp865 ([source](https://tripleee.github.io/8bit/#a5)).
40,534,687
I need to retrieve a list of Distribution groups with their x400 and x500 addresses. I have determined the attributes are proxyaddresses and TextEncodedORAddress. We are running Exchange 2013. When I look at a high level searchbase like "OU=Exchange,OU=company,DC=company,DC=com" and use Get-ADUser it returns the user accounts, however I need Distribution Groups. Using the following returns the users with the attributes I need, but I need distribution groups, not users. ``` Get-ADUser -SearchBase "OU=Exchange,OU=company,DC=company,DC=com" ` -Filter * -Properties * | Select * | FT CN,distinguishedName,proxyaddresses,textEncodedORAddress ``` I tried Get-Mailbox, Get-DistributionGroup, but I get an error saying it's not a cmdlet. I also tried using the attribute groupType to filter, but it didn't work. I'm not sure if I'm able to use Get-ADObject as I'm not quite sure how I'd use that cmdlet. Any help would be appreciated.
2016/11/10
[ "https://Stackoverflow.com/questions/40534687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6901837/" ]
It's important to note that this system referenced in question was built from source code and supported nginx was replaced with Apache (not officially supported by gitlab). Here is the deal - in the standard nginx config on my system I can see this ``` upstream gitlab-workhorse { server unix:/var/opt/gitlab/gitlab-workhorse/socket; } proxy_pass http://gitlab-workhorse; ``` Which means - it's using socket. Not a network port. If I try to see if the workhorse even listening on network - I will see that it's not. ``` ps -ef|grep -i workhorse lsof -p pid ``` Would not show any network ports open by workhorse pid. So perhaps apache config is incorrect? It should be using socket instead of port?
First, double-check your [gitlab workhorse](https://gitlab.com/gitlab-org/gitlab-workhorse) version and if it is compatible with your current GitLab installation. Of all the GitLab issues you reference, the comments on [22484](https://gitlab.com/gitlab-org/gitlab-ce/issues/22484#note_16594090) seem the most promising: > > In my case, workhorse's logs showed an error accessing `./.gitlab_workhorse_secret` > > > After some digging, the fix was to add the following to the workhorse startup command line in `/etc/systemd/system/gitlab-workhorse.service`: > > > ``` -secretPath /home/git/gitlab/.gitlab_workhorse_secret ``` > > For reference, the full `ExecStart` is now: > > > ``` ExecStart=/home/git/gitlab/bin/daemon_with_pidfile /home/git/gitlab/tmp/pids/gitlab-workhorse.pid \ /home/git/gitlab-workhorse/gitlab-workhorse -listenUmask 0 -listenNetwork unix \ -listenAddr /home/git/gitlab/tmp/sockets/gitlab-workhorse.socket \ -authBackend http://127.0.0.1:8080 -authSocket /home/git/gitlab/tmp/sockets/gitlab.socket \ -documentRoot /home/git/gitlab/public -secretPath /home/git/gitlab/.gitlab_workhorse_secret \ >> /home/git/gitlab/log/gitlab-workhorse.log 2>&1 ``` --- The other possibility is: > > In my case 500 error was caused by bad nginx configuration in `/etc/gitlab/gitlab.rb`. > > > In case where I had something "before" the nginx, like in my case haproxy. I overlooked this fact. It is described in [NGiNX settings](https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/doc/settings/nginx.md). > > In my case in haproxy sends backend to 8081 where is listening nginx now (originally I setted 8080 - default unicorn service) - > > I was not able configure gitlab only with haproxy, without nginx layer. > > > So in my configuration was important ``` nginx['listen_port'] = 8081 nginx['listen_https'] = false ``` Note that both issues are for NGiNX (there is [one when Apache2 is used](https://gitlab.com/gitlab-org/gitlab-ce/issues/23133)) --- There is also a mention about 403 (permission denied) errors: > > We were able to resolve the 403 issue by enabling both HTTPS and SSH cloning; we only had SSH cloning enabled which seemed to be causing the problem. This can be changed by going to `https:///admin/application_settings` and double checking `Enabled Git access protocols` > > > --- Those conclusions are summarized in [merge request 6843](https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/6843/diffs) But there is more: > > Looking at the default files, it looks like there is some sort of confusion with upgrades and what the defaults should be. > > With the default configuration file examples (`init.d` and `nginx`), `gitlab-workhorse` will listen on a Unix socket and not an IP:port. > > The Nginx example config file does have some lines for Unix sockets, but the proxy pass goes to an address. > > > I thought setting gitlab up for the first time I needed point my nginx config to the Unicorn port bind as it was the only port I was seeing in netstat get setup when I started the gitlab services. > > If you send the `git clone` request to Unicorn you will get the 500 error. > > **What I had to do is change gitlab-workhorse to listen to my lookback address and point Nginx there. That cleared up my HTTP 500 error with cloning**. > > See more with [A Brief History of GitLab Workhorse](https://about.gitlab.com/2016/04/12/a-brief-history-of-gitlab-workhorse/) > > >
27,999,030
I need to install my app only on some devices and does not allow installation on another devices. I thought that maybe I can pair a unique ID to install apps. **I can do this?** **How I can block the installation of a single application on some devices?**
2015/01/17
[ "https://Stackoverflow.com/questions/27999030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3626214/" ]
You cannot control app installation based on Device Id (IMEI) either by google play store or direct install... However you can check at the start of the launcher activity, you can check that the Device Id (or Imei) is in the list of imei you are allowing... Then allow user to use the apk... ELSE finish() the launcher activity... You can also give message to user stating "Unauthorized access" or something similar...
> > I thought that maybe I can pair a unique ID to install app > > > There's no platform provided, reliable uniquie ID of the device. > > How I can block the installation of a single application on some devices? > > > You cannot block installation on device - as long as device meets your manifest requirements (screen, libs, platform version etc) user will be able to install your app.
235,928
Gravitational wave is produced by change in gravitational field, [source](http://stuver.blogspot.com/2012/05/q-what-is-gravitational-wave.html). If something is moving away from me at constant speed, its gravitational field will vary. But why only accelerating bodies produce GW?
2016/02/13
[ "https://physics.stackexchange.com/questions/235928", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/76520/" ]
Because radiation from such a body undergoing inertial motion would gainsay Galileo's postulate of relativity, *i.e.* that there is no measurement one can make within an inertial frame that could detect that frame's motion relative to another inertial frame. Gravitational radiation would bear energy away from the body, and in principle (at least from the classical paradigm that holds in special and general relativity) this energy loss could be measured from within the frame. If you think about it, the proposition that bodies emit radiation when in uniform motion relative to your own inertial frame is a tacit assumption that your own frame is privileged. If you are looking for an answer with more "technology" applied, then, as user Danu comments, the lack of radiation from uniformly moving bodies is not special to gravitation: there is an approximation to GR called [Gravitoelectromagnetism](https://en.wikipedia.org/wiki/Gravitoelectromagnetism) which is almost exactly like Maxwellian electrodynamics and can be derived from assuming a delay, propagating at speed $c$, in gravitational effects. It's kind of like Coulomb's electrostatic law modified to heed the locality requirements of special relativity. In this picture, the gravitational field lines of a moving body are distorted in a relatively uniformly moving frame, but their shape does not change and the whole solution (essential like that described the [Liénard-Weichert Potential](https://en.wikipedia.org/wiki/Li%C3%A9nard%E2%80%93Wiechert_potential) for zero acceleration) is a field of constant shape translating uniformly with the body. One can easily see from this picture that only accelerating bodies can radiate energy: a field of constant shape whose only change is uniform, rigid translation with the body producing it must have a constant energy and there can be no radiation. One should be warned, however, that the gravitoelectromagentic approach grossly overestimates gravitational radiation power radiated from accelerating bodies by using the analogue of Larmor's formula / Liénard-Weichert Potential. Such an approach gives several gigawatts radiation from the Earth, whereas full GR calculates around about 200W. (Incidentally, the several gigawatt figure is also too small to measure for something Earth-sized).
Gravitational wave is a concept predicted by General Relativity by Albert Einstein. The very first point to look is that how a theory extended from explaining the symmetry of physical laws in inertial frames to include accelerated frames become a theory of gravitation. This is the starting point of General Relativity. It's known as equivalence principle. It says that gravity is an acceleration effect that determines the geometry of spacetime. You cannot distinguish, if put in a sealed container, that if you are in some gravitational field or whether the container is accelerating upwards. You cannot distinguish your inertial mass and gravitational mass. So, with the aid of this, Einstein said that what massive substances can do on spacetime, the accelerating bodies can also do. Gravitational waves are the gravitational potential energy radiated by a changing gravitational field source. As we say that electromagnetic fields can be produced by charges moving at uniform velocity, electromagnetic radiation requires the charge to accelerate, same is for gravitational waves. A gravitational field can be created by mass and energy distribution. But, to cause ripples in spacetime, the field should be fluctuated rapidly (think of the ripples you can make on water). As a simple case, the massive object should vibrate. This means, the body is accelerating. So to see any effect of gravity, you must see an acceleration. Then what's so special about GW?
33,299,265
This one is tricky! I've spent hours and hours on this, can't find anything similar on Stackoverflow, probably because I'm not sure what to search for. **The issue:** 1. In a container I have 3 boxes that each have an open/close toggle button — that toggles them individually — **it works fine.** 2. I have one Open-Close All button outside of the container, that should be able to open the remaining boxes `(if 1 or 2 are already open)` OR if all / or none are open, it should open / close them all. My code almost does everything that I need `(if 1 or 2 boxes are open and you click Open-Close All, the remainder opens)` and if all boxes are closed, Open-Close opens them all at once. **Only thing that doesn't work is if ALL boxes are open, I want to be able to close them all at once by clicking Open-Close All.** <http://codepen.io/StrengthandFreedom/pen/ZbrvOO> ``` $('.small-box-button').on('click', function(){ event.preventDefault(); $(this).next('.small-box').toggleClass('is-visible'); }); // Open / Close all / remainders $('.open-close-all-button').on('click', function(){ event.preventDefault(); if ($('.small-box').is(':visible')) { // then open the small boxes that are not open yet (the remainders) $('.small-box').siblings().addClass('is-visible'); // $(this).next('.small-box').toggleClass('is-visible'); } //not sure what to do here... else ($('.small-box').not(':visible')) $('.small-box').siblings().addClass('is-visible'); }); ``` I think I need to use some more if else conditions and check for values `(like if isVisible >= 1 || 2 )` but not sure how to write it. I have a feeling this could be written much simpler. Would really appreciate some guidance, I did my best to make the example as easy to look at as possible. Thank you! :-)
2015/10/23
[ "https://Stackoverflow.com/questions/33299265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4218116/" ]
I think your solution is very easy. Basically what you have to do is check the number of items are you showing when the user click de main button out site the box. Take a look below: // Open/close all boxes $('.open-close-all-button').on('click', function(){ event.preventDefault(); ``` var numOfItems = $('.is-visible').length; if(numOfItems > 1){ //Add the case you need //Remove all the .is-visible }else{ //Add to all the boxes .is-visible } ``` }); Also I recommend you encapsulate your code: ``` $(document).ready(function(){ // Toggle individual boxes when clicking on buttons inside container $('.small-box-button').on('click', function(){ event.preventDefault(); $(this).next('.small-box').toggleClass('is-visible'); }); // Open/close all boxes $('.open-close-all-button').on('click', function(){ event.preventDefault(); var numOfItems = $('.is-visible').length; if(numOfItems > 1){ //Add the case you need //Remove all the .is-visible }else{ //Add to all the boxes .is-visible } }); }); ```
I guess you are looking for `:hidden` selector: ``` $('.open-close-all-button').on('click', function(){ event.preventDefault(); $('.small-box:hidden').addClass('is-visible'); }); ```
41,302,132
What I want to accomplish is this: I have created button component based on TouchableOpacity. In my app I have 3 types of differently looking buttons, they all share some styles and have something specific as well. Below is how my Button.js looks like: ``` import React, { Component } from 'react'; import { Text, TouchableOpacity } from 'react-native'; class Button extends Component { render() { const { children, onPress, style } = this.props; const { buttonStyle, textStyle } = styles; return ( <TouchableOpacity onPress={onPress} style={[buttonStyle]}> <Text style={[textStyle]}> {children} </Text> </TouchableOpacity> ); } } //Commonly shared button styles const styles = { textStyle: { alignSelf: 'center', fontSize: 17, paddingTop: 15, paddingBottom: 15 }, buttonStyle: { alignSelf: 'stretch', marginLeft: 15, marginRight: 15 } }; //Below are specific appearance styles const black = { container: { backgroundColor: '#000' }, text: { color: '#FFF' } }; const white = { container: { backgroundColor: '#FFF' }, text: { color: '#000' } }; ``` It would be great if I could use this button something like this: ``` <Button onPress={} style='black'>PLAY</Button> <Button onPress={} style='white'>CANCEL</Button> ``` I.e. default buttonStyle and textStyle are applied from styles object. And I just want to pass a single word ('black', 'white') to reference additional style objects described in Button component. I know I can create a helper method with switch, but I think there is a shorter way to do this. Is there? Thanks a lot!
2016/12/23
[ "https://Stackoverflow.com/questions/41302132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5018179/" ]
I think this would be the shortest and cleanest way ``` import React, { PropTypes } from 'react'; import { Text, TouchableOpacity } from 'react-native'; const Button = ({ children, onPress, type }) => ( <TouchableOpacity onPress={onPress} style={[styles.defaultButton, styles[type].button]}> <Text style={[styles.defaultText, styles[type].text]}> {children} </Text> </TouchableOpacity> ); Button.propTypes = { children: PropTypes.node.isRequired, onPress: PropTypes.func.isRequired, type: PropTypes.oneOf(['white', 'black']).isRequired, }; const styles = { defaultButton: { alignSelf: 'stretch', marginLeft: 15, marginRight: 15 }, defaultText: { alignSelf: 'center', fontSize: 17, paddingTop: 15, paddingBottom: 15 }, white: { button: { backgroundColor: '#FFF' }, text: { color: '#000' } }, black: { button: { backgroundColor: '#000' }, text: { color: '#FFF' } }, }; export default Button; ``` Add `type && style[type].button` if type is not required prop. Like this: ``` const Button = ({ children, onPress, type }) => ( <TouchableOpacity onPress={onPress} style={[styles.defaultButton, type && styles[type].button]}> <Text style={[styles.defaultText, type && styles[type].text]}> {children} </Text> </TouchableOpacity> ); Button.propTypes = { children: PropTypes.node.isRequired, onPress: PropTypes.func.isRequired, type: PropTypes.oneOf(['white', 'black']), }; ```
You could do something like this: ``` import React, { PropTypes } from 'react'; import { StyleSheet, Text, TouchableOpacity } from 'react-native'; // Commonly shared button styles const defaultStyle = StyleSheet.create({ textStyle: { alignSelf: 'center', fontSize: 17, paddingTop: 15, paddingBottom: 15, }, buttonStyle: { alignSelf: 'stretch', marginLeft: 15, marginRight: 15, }, }); // Below are specific appearance styles const black = StyleSheet.create({ container: { backgroundColor: '#000', }, text: { color: '#FFF', }, }); const white = StyleSheet.create({ container: { backgroundColor: '#FFF', }, text: { color: '#000', }, }); const themes = { black, white, }; function Button({ children, onPress, theme }) { const buttonStyles = [defaultStyle.buttonStyle]; const textStyles = [defaultStyle.textStyle]; if (theme) { buttonStyles.push(themes[theme].container); textStyles.push(themes[theme].text); } return ( <TouchableOpacity onPress={onPress} style={buttonStyles}> <Text style={textStyles}> {children} </Text> </TouchableOpacity> ); } Button.propTypes = { onPress: PropTypes.func.isRequired, theme: PropTypes.string, children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]), }; export default Button; ```
2,392,238
I am currently Developing application in MVC2 I have want to used mutiple form tags in My application In My View I have Created a table which has Delete option which i am doing through Post for Individual Delete so i have Create form tag for each button. i also want user to give option to delete mutiple records so i am providing them with checkboxes.This form should have all the values of checkboxes and all. so form gets render Like this for Each delete button ``` <form action="/Home/MutipleDelete" method="post"> <input class="button " name="Compare" type="submit" value="Mutipledelete" style="margin-right:132px;" /> <input id="chk1" name="chk1" type="checkbox" value="true" /> <form action="/Home/Delete" method="post"> <input type="submit" class="submitLink" value="member1" /> <input type="hidden" name="hfmem1" id="hfmem1" value="1" /> </form> <input id="chk2" name="chk2" type="checkbox" value="true" /> <form action="/Home/Delete" method="post"> <input type="submit" class="submitLink" value="member2" /> <input type="hidden" name="hfmem2" id="hfmem2" value="2" /> </form> </form> ``` The following is not working . but IF i write my code that form renders in this way ``` <form action="/Home/MutipleDelete" method="post"> <input class="button " name="Compare" type="submit" value="Mutipledelete" style="margin-right:132px;" /> </form> <input id="chk1" name="chk1" type="checkbox" value="true" /> <form action="/Home/Delete" method="post"> <input type="submit" class="submitLink" value="member1" /> <input type="hidden" name="hfmem1" id="hfmem1" value="1" /> </form> <input id="chk2" name="chk2" type="checkbox" value="true" /> <form action="/Home/Delete" method="post"> <input type="submit" class="submitLink" value="member2" /> <input type="hidden" name="hfmem2" id="hfmem2" value="2" /> </form> ``` it is working in Mozilla but not in IE.I have debug and Checked values in formcollection In contoller.What to do.?
2010/03/06
[ "https://Stackoverflow.com/questions/2392238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/280448/" ]
Conceptually, a form within a form doesn't really make sense. Can you not use Action Links in place of the buttons on the inner forms? You can still style them to look like buttons.
I think this will not be possible using post. Since using post we can find which submit button was clicked but will not able to find the value of submit button if we want to display some value to show the user and other value which we want to submit to database. in this case my submit button is generated Dynamically ``` <input type="submit" name="submitbutton" id="<%= Html.Encode(item.ideletevalue) %>" class="submitLink" value=" <%= Html.Encode(item.deleteitemname)%>"/> ```
64,696,233
**Environment:** Python 3.7.7 Flask 1.1.2 Werkzeug 1.0.1 **Introduction:** I made a FLask application where my users can add some "Platform" and edit them. Each platform has a category. For example : the platform "Facebook" is in the Category "Social Network". the platform "Instagram" is in the Category "Social Network". the platform "Google" is in Category "Search Engine". The New "Platform" and Edit "Platform" use the same form and same template. In this form, there is a QuerySelectField which loads the categories values from a DB query. When the user wants to edit a "Platform", he opens the "Platform" form where the values of the "Platform" are filled in the fields. This is a typical form that you can found everywhere on internet. The New "Platform" form works fine. The Edit "Platform" form is bugging with the QuerySelectField. I successfully managed to fill the values of "Platform" in the text fields of the "Platform" form, but I have an issue with the QuerySelectField (categories). It doesn't want to preselect the value of the category of the platform. **Code:** My forms.py ``` def GetCategories(): """ This function is to fill the selectdropdown field of the form NewPlatformForm :return: """ return Category.query class NewPlatformForm(FlaskForm): name = StringField('Name', validators=[DataRequired(), Length(min=2, max=20)]) category = QuerySelectField('Category', validators=[DataRequired()], query_factory=GetCategories, get_label='name') image = StringField('Image',validators=[DataRequired(), Length(min=4, max=100)]) description = TextAreaField('Description',render_kw={'rows':20},validators=[DataRequired(), Length(min=2, max=1200)]) icon_blue = StringField('Icon blue') icon_black = StringField('Icon black') icon_white = StringField('Icon white') submit = SubmitField('Save') ``` My routes.py ``` @app.route('/platform/<int:platform_id>/edit', methods=['GET', 'POST']) @login_required def edit_platform(platform_id): platform = Platform.query.get_or_404(platform_id) form = NewPlatformForm() platforms_categories = data = db_mysql.session.query(Platform, Category).join(Category).all() #IF USER ADD A NEW PLATFORM -------------------------------------------------------- if form.validate_on_submit(): platform.name = form.name.data platform.category_id = form.category.data platform.image = form.image.data platform.description = form.description.data platform.icon_blue_img = form.icon_blue.data platform.icon_white_img = form.icon_white.data platform.icon_black_img = form.icon_black.data db_mysql.session.commit() flash('Your platform has been updated', 'success') return redirect(url_for('platforms')) #IF USER EDIT AN EXISTING PLATFORM -------------------------------------------------------- elif request.method == 'GET': print(f"platform.id_category : {platform.id_category} - {type(platform.id_category)}") form.name.data = platform.name form.category.data = platform.id_category #Here is the Select field which needs to preselect the Category value of platform. form.image.data = platform.image form.description.data = platform.description form.icon_blue.data = platform.icon_blue_img form.icon_white.data = platform.icon_white_img form.icon_black.data = platform.icon_black_img return render_template('new_platform.html', title='Edit Platform', form=form, legend='Edit Platform',categories=platforms_categories) ``` **What I tried:** I tried form.category.default instead of form.category.data but it didn't change anything. Can anyone help me, please?
2020/11/05
[ "https://Stackoverflow.com/questions/64696233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10551444/" ]
```py def show_reservations(filename): reservations = [] with open(filename) as f: for line in f.readlines(): splitted_line = line.replace(',', '').split() status = splitted_line[2] if status == "CONFIRMED": time = splitted_line[1] name = splitted_line[0] reservations.append({"time":time, "name":name}) return sorted(reservations, key=lambda k: k['time']) for reservation in show_reservations("reservations.txt"): print(reservation["name"] + ",", reservation["time"]) ```
Instead of directly printing, `append` the entries to a list of tuples `(time, name)`. Then after the list, sort it (`li.sort()`), and loop through it again, this time printing.
10,568,732
For some reason I can't get this batch file to run in my .NET 4.0 MVC3 project. I am using server 2008R2 64 bit - does cmd.exe operate differently? ``` System.Diagnostics.Process process1; process1 = new System.Diagnostics.Process(); process1.EnableRaisingEvents = false; string strCmdLine = "d:\audioTemp\test.bat"; System.Diagnostics.Process.Start("CMD.exe", strCmdLine); process1.Close(); ```
2012/05/13
[ "https://Stackoverflow.com/questions/10568732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547794/" ]
``` System.Diagnostics.Process.Start("cmd.exe", @"/c d:\audioTemp\test.bat") ```
Your string contains a tab character `\t`. Either escape the backslashes: ``` strCmdLine = "d:\\audioTemp\\test.bat"; ``` Or use a [verbatim string literal](http://msdn.microsoft.com/en-us/library/aa691090%28v=vs.71%29.aspx): ``` strCmdLine = @"d:\audioTemp\test.bat"; ```
6,244,578
I am trying to post an image file to a server. Initially I tested my script without proxy at my home and it worked fine. But when I used the same script in my college it is throwing some error. The function for uploading images is as below ``` function upload($filepath,$dir) { $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_VERBOSE, 0); curl_setopt($ch, CURLOPT_PROXY, 'localhost:7777'); curl_setopt($ch, CURLOPT_PROXYUSERPWD, 'ae07b026:kpack'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)"); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_URL, 'http://finalytics.in/sites/scrap/uploader.php' ); $post_array = array( "my_file"=>"@".$filepath, "upload"=>"Upload", "dir"=>$dir ); print_r($post_array); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_array); $response = curl_exec($ch); echo $response; } ``` and uploader.php is a normal file which just saves the image. The error which I am getting is like this ``` ERROR The requested URL could not be retrieved While trying to process the request: POST /sites/scrap/uploader.php HTTP/1.1 Proxy-Authorization: Basic YWUwN2IwMjY6a3BhY2s= User-Agent: Mozilla/4.0 (compatible;) Host: finalytics.in Accept: */* Proxy-Connection: Keep-Alive Content-Length: 87022 Expect: 100-continue Content-Type: multipart/form-data; boundary=----------------------------07ae68105e71 The following error was encountered: Invalid Request Some aspect of the HTTP Request is invalid. Possible problems: Missing or unknown request method Missing URL Missing HTTP Identifier (HTTP/1.0) Request is too large Content-Length missing for POST or PUT requests Illegal character in hostname; underscores are not allowed Your cache administrator is webmaster. Generated Sun, 05 Jun 2011 17:26:33 GMT by proxy1.iitm.ac.in (squid/2.7.STABLE7) ```
2011/06/05
[ "https://Stackoverflow.com/questions/6244578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/784583/" ]
The problem is the proxy our institute using is "SQUID". And Squid doesn't support Expect: 100-continue. So finally added this to my options ``` curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); ``` and its all working fine.
We had a similar error where adding the header `Expect:` fixed our proxy error. However, the problem was a problem with curl itself. Versions <= 7.68 didn't work and versions >= 7.70 worked fine.
16,039,911
I am getting an exception in this program. I have tried to do some changes but its still not working. I am trying to write data from demo.txt to demo1.txt but its giving a `NullPointerException`. What am I doing wrong here? ``` import java.io.*; class CopyFile{ public static void main(String[] args){ String str = null ; try { File f = new File("/home/newlabuser/workspace/CopyFileDemo/src/demo.txt"); if(f.exists()) { if(f.canRead()) { FileInputStream fin = new FileInputStream(f); BufferedInputStream bin = new BufferedInputStream(fin); DataInputStream din = new DataInputStream(bin); while((str=din.readLine())!=null) System.out.println(str); writeTextFile("/home/newlabuser/workspace/CopyFileDemo/src/demo1.txt",str); din.close(); } } } catch (Exception e) { e.printStackTrace(); } } public static void writeTextFile(String fileName, String s) { FileWriter output; try { output = new FileWriter("/home/newlabuser/workspace/CopyFileDemo/src/demo1.txt"); BufferedWriter writer = new BufferedWriter(output); writer.write(s); writer.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` > > java.lang.NullPointerException > > > at java.io.Writer.write(Writer.java:140) > > > at CopyFile.writeTextFile(CopyFile.java:37) > > > at CopyFile.main(CopyFile.java:21) > > >
2013/04/16
[ "https://Stackoverflow.com/questions/16039911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2229178/" ]
Don't underestimate the use of curly braces with loops. Here's your code: ``` while((str=din.readLine())!=null) System.out.println(str); writeTextFile("/home/newlabuser/workspace/CopyFileDemo/src/demo1.txt",str); din.close(); ``` Here, only `System.out.println(str)` will be running in a loop, and the next line will be executed after the loop exits, and obviously str here will be `null`. So when you pass `null` to the `BufferedWriter's` `write()` method - you get a `NullPointerException`. Fix your code to be: ``` while((str=din.readLine())!=null) { System.out.println(str); writeTextFile("/home/newlabuser/workspace/CopyFileDemo/src/demo1.txt",str); } din.close(); ``` and you should be fine.
Try this: ``` File fdir = new File("/home/newlabuser/workspace/CopyFileDemo/src"); FileWriter file = new FileWriter(new File(fdir,"demo1.txt")); file.write(new Scanner(new File(fdir,"demo.txt")).useDelimiter("\\Z").next()); file.close(); ```
46,311,673
I don't even know how to change the network security group of an Azure VM via the portal... I hardly found anything useful from the official doc.
2017/09/20
[ "https://Stackoverflow.com/questions/46311673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8637292/" ]
For the **Invalid VCS root mapping error** you can fix it by deleting the `vcs.xml` file located in the `.idea` folder of your project and then rebuild your project.
all you need is to delete the vcs.xml file inside an .idea folder this works!
16,716,851
I'm creating a basic game, and I can load images fine. Now, I'm trying to load sounds but I keep getting **NullPointerExceptions**. I'm 100% sure the path is correct, I've tried loading more then one sounds and I always get this error. I've only been able to use it once. Here is my sound bank: ``` public class SoundBank { public static Audio oggEffect; public SoundBank () { try { oggEffect = AudioLoader.getAudio("OGG", ResourceLoader.getResourceAsStream("Res/ping_pong_8bit_plop.ogg")); } catch (IOException e) { e.printStackTrace(); } } } ``` And my execution code: ``` else if (Keyboard.isKeyDown(Keyboard.KEY_8)) { SoundBank.oggEffect.playAsSoundEffect(1.0f, 1.0f, true); } ```
2013/05/23
[ "https://Stackoverflow.com/questions/16716851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1580953/" ]
`usleep(50000)` blocks the thread Use `NSTimer` instead to updated the progressView. ``` [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(updateProgressView) userInfo:nil repeats:YES]; duration = 0; ... - (void)updateProgressView { // Update the progress } } ... ```
Both your `drawRect:` and your `progressView:…` methods will be called on the main thread. `setNeedsDisplay:` doesn't immediately call `drawRect:`; it queues it up to be called the next time your application's main thread passes through its run loop. Use an `NSTimer` or read up on CoreAnimation to see if it provides something more directly applicable: your current solution will eat up a lot of CPU time and will not take advantage of the GPU.
11,364,111
I am writing a particle based game that is mainly built by drawing lots of colored shapes. **Question 1)** For most of the enemy units I am drawing 4 layered rectangles by setting the paint and then drawing the rectangle through the canvas. I was wondering if it is better to draw using bitmaps, or to draw using the canvas drawing tools? I could easily make a single image of the enemy unit that I wish to draw. **Question 2)** For the images that I have to draw to the screen, I was wondering how I need to load them? Right now I have tons of .png images loaded like this: `direction1 = BitmapFactory.decodeStream(assetMgr.open("direction1.png"));` I've read that RGB565 is the fasted image type to draw to the screen. Microsoft Paint has some saving options, but for the most part programs only save as a bitmap, not a type of bitmap. If I was to start using that new format would I: 1. Make new images and use the same loading code. 2. Use the same images and add something like `Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);` to convert from the initial loaded format to the RGB565 format. 3. Make new images and change my loading code. Thanks for any help! It is very appreciated.
2012/07/06
[ "https://Stackoverflow.com/questions/11364111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/831913/" ]
I'm facing the same issues. I recently found this: ``` document.addEventListener('touchmove', function(event){ if(event.touches.length >=2) { event.stopPropagation(); event.preventDefault(); } }); ``` But if the users acts really fast it still works. This is really annoying in a kiosk setting where a user does a pinch zoom on accident and has no idea what happened so the kiosk is just broken. I'll keep posting if I find a solution
easy, use an applet to prevent zoom, java rulez.
24,067
I want perform demand forecast for particular item based on attributes.Did I need to train the model with unsold items ? **by maintaining sales Quantity as zero** or go with only items sold in training period.
2017/10/25
[ "https://datascience.stackexchange.com/questions/24067", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/37626/" ]
> > Has anyone done any benchmarks? > > > Yes, [the 2014's benchmark in question](https://github.com/Rdatatable/data.table/wiki/Benchmarks-%3A-Grouping) has turned into foundation for [db-benchmark](https://h2oai.github.io/db-benchmark) project. Initial step was to reproduce 2014's benchmark on recent version of software, then to make it a continuous benchmark, so it runs routinely and automatically upgrades software before each run. Over time many things have been added. Below is high level diff of the 2014's benchmark comparing to [db-benchmark](https://github.com/h2oai/db-benchmark) project. New: * continuous benchmark: runs routinely, upgrades software, re-run benchmarking script * more software solutions: spark, python datatable, cuda dataframes, julia dataframes, clickhouse, dask * more data cases + two new smaller data sizes: 0.5GB (1e7 rows) and 5GB (1e8 rows) + two more cardinality factors: unbalanced, heavily unbalanced + sortedness + data having NA * advanced `groupby` questions + `median`, `sd` + range v1-v2: `max(v1)-min(v2)` + top 2 rows: `order(.); head(.,2)` + regression: `cor(v1, v2)^2` + `count` and grouping by 6 columns * benchmark task: `join` Changes (see `groupby2014` task for 2014 fully compliant benchmark script): * [using categorical/factor instead of character](https://github.com/h2oai/db-benchmark/issues/20) * [cardinality of `v2` and `v3` measures increased](https://github.com/h2oai/db-benchmark/issues/93) * [function calls are NA-aware](https://github.com/h2oai/db-benchmark/issues/40) * aggregated columns are named * order of groups is irrelevant whenever possible * extra call to `dim()`/`.shape` is included in timings to force lazy evaluation * machine that runs benchmark has 128GB mem (not 244GB mem) * no 100GB (2e9 rows) data size We are planning to add even more software solutions and benchmark tasks in future. Feedback is very welcome, feel invited to our issue tracker at <https://github.com/h2oai/db-benchmark/issues>. --- > > Is pandas now faster than data.table? > > > According the our results pandas is not faster than data.table. I am pasting medium size data 5GB (1e8 rows) groupby benchmark plot taken from the report at [h2oai.github.io/db-benchmark](https://h2oai.github.io/db-benchmark) as of 20210312. Consult the [h2oai.github.io/db-benchmark#explore-more-data-cases](https://h2oai.github.io/db-benchmark/#explore-more-data-cases) for other data sizes (1e7, 1e9), data cases (cardinality, NAs, sorted), questions groups (advanced), or tasks (join). For up-to-date timings please visit <https://h2oai.github.io/db-benchmark>. [![groupby_1e8_1e2_0_0_basic](https://i.stack.imgur.com/WyxZS.png)](https://i.stack.imgur.com/WyxZS.png)
A colleague and I have conducted some preliminary studies on the performance differences between pandas and data.table. You can find the study (which was split into two parts) on our [Blog](https://www.statworx.com/de/blog/pandas-vs-data-table-a-study-of-data-frames/) (You can find part two [here](https://www.statworx.com/de/blog/pandas-vs-data-table-a-study-of-data-frames-part-2/)). We figured that there are some tasks where pandas clearly outperforms data.table, but also cases in which data.table is much faster. You can check it out yourself and let us know what you think of the results. EDIT: If you don't want to read the blogs in detail, here is a short summary of our setup and our findings: **Setup** We compared `pandas` and `data.table` on 12 different simulated data sets on the following operations (so far), which we called scenarios. * Data retrieval with a select-like operation * Data filtering with a conditional select operation * Data sort operations * Data aggregation operations The computations were performed on a machine with an Intel i7 2.2GHz with 4 physical cores, 16GB RAM and a SSD hard drive. Software Versions were OS X 10.13.3, Python 3.6.4 and R 3.4.2. The respective library versions used were 0.22 for pandas and 1.10.4-3 for data.table **Results in a nutshell** * `data.table`seems to be faster when selecting columns (`pandas`on average takes 50% more time) * `pandas` is faster at filtering rows (roughly 50% on average) * `data.table` seems to be considerably faster at sorting (`pandas` was sometimes 100 times slower) * adding a new column appears faster with `pandas` * aggregating results are completely mixed Please note that I tried to simplify the results as much as possible to not bore you to death. For a more complete visualization read the studies. If you cannot access our webpage, please send me a message and I will forward you our content. You can find the code for the complete study on [GitHub](https://github.com/STATWORX/blog/tree/master/pandas_vs_datatable). If you have ideas how to improve our study, please shoot us an e-mail. You can find our contacts on GitHub.
49,371,467
I am writing a Vue.js app with Bootstrap 4 and I can't loaded though I followed the documentation. Added to main.js `Vue.use(BootstrapVue);` Added to css file related to App.vue: ``` @import '../../node_modules/bootstrap/dist/css/bootstrap.css'; @import '../../node_modules/bootstrap-vue/dist/bootstrap-vue.css'; ``` Here is template: ``` <div class="main"> <div> <b-modal id="modal1" title="Something went wrong" v-if="!serverStatusOk"> <p class="my-4">{{msg}}</p> <p class="my-4">{{statusCode}}</p> </b-modal> </div> <div> <b-tab title="Players" active> <br>Players data </b-tab> <b-tab title="Tournaments" active> <br>Tournament data </b-tab> </div> ``` Result: no css rendered but in css file from dist dir I see Bootstrap What am I missing? The project created by vue-cli 3.0-beta
2018/03/19
[ "https://Stackoverflow.com/questions/49371467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2970627/" ]
Try importing the files using JavaScript. ``` import 'bootstrap/dist/css/bootstrap.css' import 'bootstrap-vue/dist/bootstrap-vue.css' ``` --- On closer inspection it looks like you're missing `<b-tabs>` also `<b-modal>` is controlled by `v-model` ``` <div class="main"> <div> <b-modal id="modal1" title="Something went wrong" v-model="errorModal"> <pre class="my-4">{{ msg }}</pre> <p class="my-4">{{ statusCode }}</p> </b-modal> </div> <!-- Make sure to wrap b-tab in b-tabs --> <b-tabs> <b-tab title="Players" active> <br>Players data </b-tab> <b-tab title="Tournaments"> <br>Tournament data </b-tab> </b-tabs> </div> ``` That should fix the styling of the tabs.
I had to do a combination/variation of some of the other answers. App.vue: ``` import { BootstrapVue, IconsPlugin } from 'bootstrap-vue' import Vue from 'vue' // Install BootstrapVue Vue.use(BootstrapVue) // Optionally install the BootstrapVue icon components plugin Vue.use(IconsPlugin) import 'bootstrap/dist/css/bootstrap.css' import 'bootstrap-vue/dist/bootstrap-vue.css' export default { name: 'App', components: { } } ``` Sources: <https://forum.vuejs.org/t/ui-library-styles-not-loading-in-web-components/77858/2> <https://bootstrap-vue.org/docs>
15,353
From a tester's point of view when do we say that a product is **stable**? Is the product still **stable** when it contains a known bug?
2015/10/28
[ "https://sqa.stackexchange.com/questions/15353", "https://sqa.stackexchange.com", "https://sqa.stackexchange.com/users/13179/" ]
I would call a software that runs consistently without crashing as stable. To answer the second question, yes a 100% bug free software is a myth (if i may). There still can be numerous bugs which are hidden and to name a few : * Bugs of implementation. * Bugs of unclear specification. * Bugs of poor documentation. * Bugs of misunderstood requirements. * Bugs of portability * Bugs of testing So that's a reason why we have bug trackers, reports and subsequent releases.
I would say that a product is stable when it is obsolete - cynical but often true (40 years of experience as a software engineer / architect).
2,037,745
I am referring to the [solution for the Singleton Pattern by Bill Pugh](https://en.wikipedia.org/wiki/Singleton_pattern#Initialization-on-demand_holder_idiom) on Wikipedia: ``` public class Singleton { // Private constructor prevents instantiation from other classes private Singleton() {} /** * SingletonHolder is loaded on the first execution of Singleton.getInstance() * or the first access to SingletonHolder.INSTANCE, not before. */ private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.INSTANCE; } } ``` Here they have mentioned: > > The inner class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that `getInstance()` is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. `volatile` or `synchronized`). > > > However, isn't there a possibility that 2 threads would call `getInstance()` at the same time, which would lead to two instances of singleton being created? Isn't it safe to use `synchronized` here? If yes, where should it be used in the code?
2010/01/10
[ "https://Stackoverflow.com/questions/2037745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206450/" ]
Here is the explanation from Wikipedia on this phenomenon (emphasis mine): > > When the class Something is loaded by > the JVM, the class goes through > initialization. Since the class does > not have any static variables to > initialize, the initialization > completes trivially. **The static class > definition LazyHolder within it is not > initialized until the JVM determines > that LazyHolder must be executed.** The > static class LazyHolder is only > executed when the static method > getInstance is invoked on the class > Something, and the first time this > happens the JVM will load and > initialize the LazyHolder class. The > initialization of the LazyHolder class > results in static variable something > being initialized by executing the > (private) constructor for the outer > class Something. **Since the class > initialization phase is guaranteed by > the JLS to be serial, i.e., > non-concurrent, no further > synchronization is required in the > static getInstance method during > loading and initialization.** And since > the initialization phase writes the > static variable something in a serial > operation, all subsequent concurrent > invocations of the getInstance will > return the same correctly initialized > something without incurring any > additional synchronization overhead. > > > So in your example, `Singleton` is "LazyHolder" and `SingletonHolder` is "Something". Calling `getInstance()` twice will not cause a race condition due to the JLS guarantees.
There are two differences here that need to be noted. The first is the Singleton design pattern and the other is a singleton instance. The Singleton design pattern is problematic due to the fact that the design pattern represents a singleton instance as is implemented using static state (which is a bad thing for a variety of reasons - especially with unit testing). The second is an instance for which there is only one instance, no matter what (like the JVM singleton implemented as an enum). The enum version is definitely superior, when compared to the Singleton pattern. If you don't want to implement all instances as `enum` instances, then you should think about using Dependency Injection (frameworks such as [Google Guice](http://code.google.com/p/google-guice)) to manage the singleton instances for the application.
1,860,292
I'm returning results from the following query which is taking too long when running. I'm not sure how to eliminate the where parameters when they are not used in SSRS. All the @variables are strings ``` select S.SBSB_ID, LTRIM(RTRIM(M.MEME_FIRST_NAME)) + ' ' + LTRIM(RTRIM(M.MEME_LAST_NAME)) AS Names, (CASE M.MEME_REL WHEN 'M' THEN 'Subscriber' WHEN 'S' THEN 'Son' WHEN 'D' THEN 'Daughter' WHEN 'W' THEN 'Wife' WHEN 'H' THEN 'Husband' WHEN 'O' THEN 'Other' ELSE M.MEME_REL END) AS Relation, (CASE A.PRPR_ID WHEN 'NONASSIGNED' THEN A.CLCL_PA_ACCT_NO ELSE LTRIM(P.PRPR_NAME) END) AS ProvName, LTRIM(RTRIM(L.CDDL_CUR_STS)) AS Status FROM CMC_SBSB_SUBSC S INNER JOIN CMC_MEME_MEMBER M ON S.SBSB_CK = M.SBSB_CK INNER JOIN CMC_CDDL_CL_LINE L ON L.MEME_CK = M.MEME_CK INNER JOIN CMC_PRPR_PROV P ON P.PRPR_ID = L.PRPR_ID INNER JOIN CMC_CLCL_CLAIM A ON A.CLCL_ID = L.CLCL_ID WHERE S.SBSB_ID LIKE (CASE @subscriberID WHEN '' THEN '%' ELSE @subscriberID END) AND M.MEME_REL IN (@Relation) AND UPPER(M.MEME_FIRST_NAME) LIKE '%' + UPPER(CASE @firstName WHEN '' THEN '%' ELSE @firstName END) + '%' AND UPPER(M.MEME_LAST_NAME) LIKE '%' + UPPER(CASE @lastName WHEN '' THEN '%' ELSE @lastName END) + '%' AND (L.CGCG_ID IN (@Category) OR L.CGCG_ID = '') AND (CASE WHEN (@Tooth) = '' THEN L.CDDL_TOOTH_BEG WHEN ISNUMERIC(@Tooth) = 0 THEN UPPER(@Tooth) WHEN LEN(@Tooth) = 1 THEN '0' + @Tooth ELSE @Tooth END) >= L.CDDL_TOOTH_BEG AND (CASE WHEN (@Tooth) = '' THEN L.CDDL_TOOTH_BEG WHEN ISNUMERIC(@Tooth) = 0 THEN UPPER(@Tooth) WHEN LEN(@Tooth) = 1 THEN '0' + @Tooth ELSE @Tooth END) <= L.CDDL_TOOTH_END AND S.SBSB_CK IN (select SBSB_CK FROM CMC_MEME_MEMBER WHERE MEME_SSN LIKE (CASE @SSN WHEN '' THEN '%' ELSE @SSN END)) AND M.MEME_BIRTH_DT LIKE (CASE WHEN @DOB IS NULL THEN '%' ELSE @DOB END) UNION select S.SBSB_ID, LTRIM(RTRIM(M.MEME_FIRST_NAME)) + ' ' + LTRIM(RTRIM(M.MEME_LAST_NAME)) AS Names, (CASE M.MEME_REL WHEN 'M' THEN 'Subscriber' WHEN 'S' THEN 'Son' WHEN 'D' THEN 'Daughter' WHEN 'W' THEN 'Wife' WHEN 'H' THEN 'Husband' WHEN 'O' THEN 'Other' ELSE M.MEME_REL END) AS Relation, RTRIM(LTRIM(P.PRPR_NAME)) AS ProvName, 'Purged - ' + H.CLDH_STS AS Status FROM CMC_SBSB_SUBSC S INNER JOIN CMC_MEME_MEMBER M ON S.SBSB_CK = M.SBSB_CK INNER JOIN CMC_CLDH_DEN_HIST H ON H.MEME_CK = M.MEME_CK INNER JOIN CMC_PRPR_PROV P ON P.PRPR_ID = H.PRPR_ID WHERE S.SBSB_ID LIKE (CASE @subscriberID WHEN '' THEN '%' ELSE @subscriberID END) AND M.MEME_REL IN (@Relation) AND UPPER(M.MEME_FIRST_NAME) LIKE '%' + UPPER(CASE @firstName WHEN '' THEN '%' ELSE @firstName END) + '%' AND UPPER(M.MEME_LAST_NAME) LIKE '%' + UPPER(CASE @lastName WHEN '' THEN '%' ELSE @lastName END) + '%' AND (H.CGCG_ID IN (@Category) OR H.CGCG_ID = '') AND (CASE WHEN (@Tooth) = '' THEN H.CLDH_TOOTH_BEG WHEN ISNUMERIC(@Tooth) = 0 THEN UPPER(@Tooth) WHEN LEN(@Tooth) = 1 THEN '0' + @Tooth ELSE @Tooth END) >= H.CLDH_TOOTH_BEG AND (CASE WHEN (@Tooth) = '' THEN H.CLDH_TOOTH_BEG WHEN ISNUMERIC(@Tooth) = 0 THEN UPPER(@Tooth) WHEN LEN(@Tooth) = 1 THEN '0' + @Tooth ELSE @Tooth END) <= H.CLDH_TOOTH_END AND S.SBSB_CK IN (select SBSB_CK FROM CMC_MEME_MEMBER WHERE MEME_SSN LIKE (CASE @SSN WHEN '' THEN '%' ELSE @SSN END)) AND M.MEME_BIRTH_DT LIKE (CASE WHEN @DOB IS NULL THEN '%' ELSE @DOB END) ``` I would rather have the query not executing blank fields with '%' but was not sure how to eliminate them conditionally from the query.
2009/12/07
[ "https://Stackoverflow.com/questions/1860292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5831/" ]
You can do something like this: ``` // Load the file contents string contents = File.ReadAllText("example.txt"); // Obtain the data using regular expressions string id = string id = Regex.Match( contents, @"CoreDBCaseID=(?<id>\d+)").Groups["id"].Value; string server = string.Empty; // Add regex here string security = string.Empty; // Add regex here string database = string.Empty; // Add regex here // Save the data in the new format string[] data = new string[] { String.Format("Table={0}", id), String.Format("Server={0}", server), String.Format("Security={0}", security), String.Format("Database={0}", database) }; File.WriteAllLines("output.txt", data); ``` And a quick way to learn those regular expressions: [Regular Expression Cheat Sheet](http://regexlib.com/CheatSheet.aspx) [Regular-Expressions.info](http://www.regular-expressions.info/) --- You can use a [positive lookahead](http://www.regular-expressions.info/lookaround.html) to stop matching at the (;) character. Something like this: @"Security=(?[\D]+)(?=;)"
Open the file and read it in one line at a time. You can use Regular Expressions [(cheat sheet)](http://www.mikesdotnetting.com/Article/46/CSharp-Regular-Expressions-Cheat-Sheet) to match and parse only the text you want to find.
5,713,825
My app uses ClickOnce tehcnology. Today I needed to run it as administrator. I modified the manifest file from ``` <requestedExecutionLevel level="asInvoker" uiAccess="false" /> ``` to ``` <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> ``` However VS cannot compile the project: > > Error 35 ClickOnce does not support the request execution level 'requireAdministrator'. > > > I think it's impossible to use them at once. Isn't it? I need to change the system time, can I do that in application level? Can I emulate it, so app. can do what I want. I change time +2 hours then put back for a second. I got a few dlls and they ask for time.
2011/04/19
[ "https://Stackoverflow.com/questions/5713825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/627193/" ]
``` private void Form1_Load(object sender, EventArgs e) { if (WindowsIdentity.GetCurrent().Owner == WindowsIdentity.GetCurrent().User) // Check for Admin privileges { try { this.Visible = false; ProcessStartInfo info = new ProcessStartInfo(Application.ExecutablePath); // my own .exe info.UseShellExecute = true; info.Verb = "runas"; // invoke UAC prompt Process.Start(info); } catch (Win32Exception ex) { if (ex.NativeErrorCode == 1223) //The operation was canceled by the user. { MessageBox.Show("Why did you not selected Yes?"); Application.Exit(); } else throw new Exception("Something went wrong :-("); } Application.Exit(); } else { // MessageBox.Show("I have admin privileges :-)"); } } ```
If you launching ClickOnce app from IE, to have Administrative privileges just run IE with Administrative privileges and your app will have it too.
46,729
We are installing the Windows Resource Kit, and that installs RoboCopy. We want to have access to a few windows scripts that uses RoboCopy so we can start from those to build something else. Any ideas on where I can find a few samples? NOTE 1: A bit of information. Every time we try to copy D drive to E drive (new drive) we get an error that says: > > ERROR 32 (0x000000020) Copying File d:\pagefile.sys The process cannot access the file because it is being used by another process. Waiting 30 seconds. > > > Just to help figure it out.
2009/07/27
[ "https://serverfault.com/questions/46729", "https://serverfault.com", "https://serverfault.com/users/4310/" ]
I used Robocopy to synchronize website content across 9 web servers. Here's a sample of the batch file that ran robocopy.exe. This batch file was scheduled to run every 5 or 10 minutes or could be run manually to push changes immediately. ``` robocopy.exe d:\inetpub\wwwroot\ \\webserver1\d$\inetpub\wwwroot\ *.* /E /PURGE /SEC /NP /NJH /NJS /XF keepalive_*.* /XD trigger /XD "D:\inetpub\wwwroot\Long Path Name" /R:5 /COPYALL /LOG:copy_to_webserver1.log ``` The previous command will copy the content of d:\inetpub\wwwroot and push it to the remote server's d:\inetpub\wwwroot. /E = copies all subdirectories including empty ones /PURGE = deletes destination files/folders that no longer exist in the source /SEC = copies the security permissions (ACL) of the files to the destination location /NP = turns off the copy progress bar; DEFINITELY do this if you are logging the results /NJH = don't log the job header /NJS = don't log the job summary /XF = exclude copying specific files (e.g. keepalive\_*.*) /XD = exclude copying specific folders (e.g. trigger) /R = specifies number of times to retry if the copy fails (e.g. 5) /COPYALL = copies everything: data, attributes, timestamps, security, ownership and auditing information; overkill really since I specified /SEC /LOG = log results to the specified log file (e.g. copy\_to\_webserver1.log) I hope that gets you started on Robocopy. I found it to be a highly reliable and very robust solution for keeping our content in sync.
To solve the second problem, (the locked file error and subsequent wait), use the switches `/r`, `/w` and `/reg`, for example: ``` robocopy D:\ E:\ /r:1 /w:1 /reg ``` This means **r**etry one time only after **w**aiting one second and make these settings default in the **reg**istry.
17,788,510
I have a simple select menu with some list items which are dynamically inserted when the page is loaded. ``` <select id="viewTasks" name="viewTasks" size=10 style="width: 100%;"> <option>Task 1</option> <option>Task 2</option> <option>Task 3</option> <option>Task 4</option> </select> ``` I would like to show the user a specific page whenever he/she **double-clicks** on any single list item. The page I want to show will be displayed according to the data in the list item string. How should I go about doing this?
2013/07/22
[ "https://Stackoverflow.com/questions/17788510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1954511/" ]
``` $('#viewTasks option').dblclick(function() { //do something }); ``` or raw: ``` <select id="viewTasks" name="viewTasks" size=10 style="width: 100%;"> <option ondblclick="someFunction(1);">Task 1</option> <option ondblclick="someFunction(2);">Task 2</option> <option ondblclick="someFunction(3);">Task 3</option> <option ondblclick="someFunction(4);">Task 4</option> </select> <script> function someFunction(item) { switch(item) { case 1: ... } } </scritp> ```
[Check out the MDN definition of the DOM event `ondblclick` here.](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.ondblclick) [Here is a working example jsFiddle from referencing that definition.](http://jsfiddle.net/R2Nrf/) jQuery was only used in this example to run the initialization event in jsFiddle, you could put it in the body `onLoad` handler like they show on the MDN reference page. Basically, you get the element that you want to handle the double click event for, and assign either a user-defined function, or an anonymous function to run when that event occurs. You do not absolutely need jQuery for this, but it is a perfect example of how jQuery can make things easier for you when it comes to handling events from DOM objects. ``` <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title> - jsFiddle demo</title> <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script> <link rel="stylesheet" type="text/css" href="/css/result-light.css"> <style type='text/css'> </style> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(function(){ initElement(); }); function initElement() { var p = document.getElementById("foo"); // NOTE: showAlert(); or showAlert(param); will NOT work here. // Must be a reference to a function name, not a function call. p.ondblclick = showAlert; }; function showAlert() { alert("ondblclick Event detected!") } });//]]> </script> </head> <body> <span id="foo">My Event Element</span> <p>double-click on the above element.</p> </body> </html> ```
64,723,778
I have been using VSCode with the Microsoft Python extension for a couple of months now. However just today I found that the green button I had in the top right that executed my code is gone. I have tried uninstalling the python extension and reinstalling, I have deleted and redownloaded VSCode, I have tried installing code runner. None of these have fixed the issue. This is the image of my VSCode, which may help to solve the issue: [![This is the image of my VSCode, which may help to solve the issue.](https://i.stack.imgur.com/VElW9.png)](https://i.stack.imgur.com/VElW9.png) When I tried to select the Python: select interpreter I got an error in the bottom right that says, > > "Command 'Python: Select Interpreter' resulted in an error (command 'python.setInterpreter' not found)" > > > I have never experienced an issue like this before so any help is greatly appreciated. Thank you! [Image of the plugin I have installed.](https://i.stack.imgur.com/pYmAk.png)
2020/11/07
[ "https://Stackoverflow.com/questions/64723778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14593690/" ]
It may also come from the restricted mode. Please make sure you're in a trusted window.
Kindly install the Python interpreter from the following site: <https://www.python.org/downloads/> Then vs code will ask for permission to run the interpreter. and then its done
2,057,137
I'm building a simple dropdown where I'd like to add a class to parent if UL exists: HTML: ``` <ul id="menu"> <li><a href="#">Parent 1</a></li> <li><a href="#">Parent 2</a> <ul> <li><a href="#">Sub 2.1</a></li> <li><a href="#">Sub 2.2</a></li> </ul> </li> </ul> ``` So I'd like to: * hide all nested (`ul#menu > li > ul`) ul's initially * show/hide nested `ul` on hover * addClass "dropdown" to parents that have nested ul's This isn't quite working, not sure why: ``` $(function () { $("ul#menu li").hover(function () { $(this).addClass("hover"); $('ul:first', this).css('visibility', 'visible'); }, function () { $(this).removeClass("hover"); $('ul:first', this).css('visibility', 'hidden'); }); $("ul#menu li ul li:has(ul)").find("a:first").addClass("dropdown"); }); ``` Many thanks for your help!
2010/01/13
[ "https://Stackoverflow.com/questions/2057137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172637/" ]
You wrote: ``` $("ul#menu li ul li:has(ul)") ``` Given your HTML structure, shouldn't this be: ``` $("ul#menu li:has(ul)") ```
This *should* do the trick (untested): ``` $('ul#menu > li > ul').each(function() { var list = $(this); list.hide(); list.parent().hover(list.hide, list.show); list.parent().parent().addClass('dropdown'); }); ```
25,988,258
``` Array ( [0] => Array ( [questionID] => 47 [surveyID] => 51 [userID] => 31 [question_Title] => Choose Any One? [question_Type] => Dropdown [response] => 1.Android 2.Windows 3.Blackberry [required] => 0 [add_time] => 0 ) [1] => Array ( [questionID] => 48 [surveyID] => 51 [userID] => 31 [question_Title] => Is it? [question_Type] => Bigbox [response] => Yes No [required] => 1 [add_time] => 0 ) [2] => Array ( [questionID] => 129 [surveyID] => 51 [userID] => 31 [question_Title] => sELECT [question_Type] => Single [response] => DFG HBK GHCK HK [required] => 0 [add_time] => 0 ) ) ``` this is my multidimensional Now i want to initially check array contains [required] => 1 or [required] => 0 i don't want to traversing array
2014/09/23
[ "https://Stackoverflow.com/questions/25988258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3928821/" ]
``` if($yourArr[0]['required']==0) //Just check for first element in your array echo "Zero"; else echo "One"; ```
This is probably the most hackish solution I'll come up with all this morning, but if you are shooting for a quick one-liner, this should do: ``` if(in_array(1, array_column($myArray, 'required'))) echo 'required'; ``` *Edit: This assumes you've got PHP 5.5+ at hand* **Update:** After a closer look at the documentation of [`in_array()`](http://php.net/in_array), this should be possible: ``` if(in_array(array('required' => 1), $myArray)) echo 'required'; ```
49,277,583
My current Android application allows users to search for content remotely. e.g. The user is presented with an `EditText` which accepts their search strings and triggers a remote API call that returns results that match the entered text. Worse case is that I simply add a `TextWatcher` and trigger an API call each time `onTextChanged` is called. This could be improved by forcing the user to enter at least N characters to search for before making the first API call. The "Perfect" solution would have the following features:- Once the user starts entering search string(s) Periodically (every M milliseconds) consume the entire string(s) entered. Trigger an API call each time the period expires and the current user input is different to the previous user input. [Is it possible to have a dynamic timeout related to the entered texts length? e.g while the text is "short" the API response size will be large and take longer to return and parse; As the search text gets longer the API response size will reduce along with "inflight" and parsing time] When the user restarts typing into the EditText field restart the Periodic consumption of text. Whenever the user presses the ENTER key trigger "final" API call, and stop monitoring user input into the EditText field. Set a minimum length of text the user has to enter before an API call is triggered but combine this minimum length with an overriding Timeout value so that when the user wishes to search for a "short" text string they can. I am sure that RxJava and or RxBindings can support the above requirements however so far I have failed to realise a workable solution. My attempts include ``` private PublishSubject<String> publishSubject; publishSubject = PublishSubject.create(); publishSubject.filter(text -> text.length() > 2) .debounce(300, TimeUnit.MILLISECONDS) .toFlowable(BackpressureStrategy.LATEST) .subscribe(new Consumer<String>() { @Override public void accept(final String s) throws Exception { Log.d(TAG, "accept() called with: s = [" + s + "]"); } }); mEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) { } @Override public void onTextChanged(final CharSequence s, final int start, final int before, final int count) { publishSubject.onNext(s.toString()); } @Override public void afterTextChanged(final Editable s) { } }); ``` And this with RxBinding ``` RxTextView.textChanges(mEditText) .debounce(500, TimeUnit.MILLISECONDS) .subscribe(new Consumer<CharSequence>(){ @Override public void accept(final CharSequence charSequence) throws Exception { Log.d(TAG, "accept() called with: charSequence = [" + charSequence + "]"); } }); ``` Neither of which give me a conditional filter that combines entered text length and a Timeout value. I've also replaced debounce with throttleLast and sample neither of which furnished the required solution. Is it possible to achieve my required functionality? **DYNAMIC TIMEOUT** An acceptable solution would cope with the following three scenarios i). The user wishes to search for the any word beginning with "P" ii). The user wishes to search for any word beginning with "Pneumo" iii). The user wishes to search for the word "Pneumonoultramicroscopicsilicovolcanoconiosis" In all three scenarios as soon as the user types the letter "P" I will display a progress spinner (however no API call will be executed at this point). I would like to balance the need to give the user search feedback within a responsive UI against making "wasted" API calls over the network. If I could rely on the user entering their search text then clicking the "Done" (or "Enter") key I could initiate the final API call immediately. *Scenario One* As the text entered by the user is short in length (e.g. 1 character long) My timeout value will be at its maximum value, This gives the user the opportunity to enter additional characters and saves "wasted API calls". As the user wishes to search for the letter "P" alone, once the Max Timeout expires I will execute the API call and display the results. This scenario gives the user the worst user experience as they have to wait for my Dynamic Timeout to expire and then wait for a Large API response to be returned and displayed. They will not see any intermediary search results. *Scenario Two* This scenario combines scenario one as I have no idea what the user is going to search for (or the search strings final length) if they type all 6 characters "quickly" I can execute one API call, however the slower they are entering the 6 characters will increase the chance of executing wasted API calls. This scenario gives the user an improved user experience as they have to wait for my Dynamic Timeout to expire however they do have a chance of seeing intermediary search results. The API responses will be smaller than scenario one. *Scenario Three* This scenario combines scenario one and two as I have no idea what the user is going to search for (or the search strings final length) if they type all 45 characters "quickly" I can execute one API call (maybe!), however the slower they type the 45 characters will increase the chance of executing wasted API calls. I'am not tied to any technology that delivers my desired solution. I believe Rx is the best approach I've identified so far.
2018/03/14
[ "https://Stackoverflow.com/questions/49277583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/423199/" ]
your query can be easily solved by using RxJava2 methods, before i post code i will add the steps of what i am doing. 1. add an PublishSubject that will take your inputs and add a filter to it which will check if the input is greater than two or not. 2. add debounce method so that all input events that are fired before 300ms are ignored and the final query which is fired after 300ms is taken into consideration. 3. now add a switchmap and add your network request event into it, 4. Subscribe you event. The code is as follows : ``` subject = PublishSubject.create(); //add this inside your oncreate getCompositeDisposable().add(subject .doOnEach(stringNotification -> { if(stringNotification.getValue().length() < 3) { getMvpView().hideEditLoading(); getMvpView().onFieldError("minimum 3 characters required"); } }) .debounce(300, TimeUnit.MILLISECONDS) .filter(s -> s.length() >= 3) .switchMap(s -> getDataManager().getHosts( getDataManager().getDeviceToken(), s).subscribeOn(Schedulers.io())) .observeOn(AndroidSchedulers.mainThread()) .subscribe(hostResponses -> { getMvpView().hideEditLoading(); if (hostResponses.size() != 0) { if (this.hostResponses != null) this.hostResponses.clear(); this.hostResponses = hostResponses; getMvpView().setHostView(getHosts(hostResponses)); } else { getMvpView().onFieldError("No host found"); } }, throwable -> { getMvpView().hideEditLoading(); if (throwable instanceof HttpException) { HttpException exception = (HttpException) throwable; if (exception.code() == 401) { getMvpView().onError(R.string.code_expired, BaseUtils.TOKEN_EXPIRY_TAG); } } }) ); ``` this will be your textwatcher: ``` searchView.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { subject.onNext(charSequence.toString()); } @Override public void afterTextChanged(Editable editable) { } }); ``` P.S. This is working for me!!
You might find what you need in the [`as`](http://reactivex.io/RxJava/javadoc/io/reactivex/Observable.html#as-io.reactivex.ObservableConverter-) operator. It takes an `ObservableConverter` which allows you to convert your source `Observable` into an arbitrary object. That object can be another `Observable` with arbitrarily complex behavior. ``` public class MyConverter implements ObservableConverter<Foo, Observable<Bar>> { Observable<Bar> apply(Observable<Foo> upstream) { final PublishSubject<Bar> downstream = PublishSubject.create(); // subscribe to upstream // subscriber publishes to downstream according to your rules return downstream; } } ``` Then use it like this: ``` someObservableOfFoo.as(new MyConverter())... // more operators ``` **Edit:** I think [`compose`](http://reactivex.io/RxJava/javadoc/) may be more paradigmatic. It's a less powerful version of `as` specifically for producing an `Observable` instead of any object. Usage is essentially the same. See this [tutorial](http://blog.danlew.net/2015/03/02/dont-break-the-chain/).
40,545,533
I would be interested in making an app Android that starts functions with vocal commands (example: instead of clicking on the button, use a voice command). My idea was to use speech recognition to store a result in a variable, and if the result corresponds to a keyword set, the function is started. The questions I have are two: * How to start within an app speech recognition using a voice command? * How to make to use the speech recognition result for my purposes? Thanks for your help
2016/11/11
[ "https://Stackoverflow.com/questions/40545533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7145451/" ]
Don't use a regular expression for this; they are not really designed for verifying numeric *values*. Instead, parse the `String` into an integral type (`num`, say), reject if any exception is thrown, then use `num % 2 == 0` as your test for evenness. If, for some reason, you absolutely *must* use a regular expression, then use something on the lines of `[0-9]*[02468]`. It drops out surprisingly simply for a test of divisibility by 2, as would 5 and 10. But try working out a regular expression to test divisibility by 3, let alone 7. Finally, if I have completely the wrong end of the stick here and all you want to do is check if the length of `s` is even then again, don't use a regular expression, but `s.length() % 2 == 0` as the check.
Change your regex to below for checking if the string length is even. ``` Pattern p5 = Pattern.compile("^(..)*$"); ``` It matches zero or more sets of two characters, all of which is anchored to the start and end of the string
45,309,173
I have the following stored procedure: ``` @offset INT, @fetch INT SELECT col1 AS col FROM tab1 UNION SELECT col1 FROM tab2 ORDER BY col OFFSET @offset ROWS FETCH NEXT @fetch ROWS ONLY ``` Now I want to add a third table as UNION, after the offset and fetch has been executed. Is that possible? ``` UNION SELECT TOP 1 col1 FROM tab3 ORDER BY NEWID() ```
2017/07/25
[ "https://Stackoverflow.com/questions/45309173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2822465/" ]
``` @offset INT, @fetch INT WITH CTE1 AS (SELECT TOP 100 PERCENT col1 AS col FROM tab1 UNION SELECT TOP 100 PERCENT col1 FROM tab2 ORDER BY col OFFSET @offset ROWS FETCH NEXT @fetch ROWS ONLY) SELECT * FROM CTE1 UNION SELECT TOP 1 col1 FROM tab3 ORDER BY NEWID() ```
use derived table ``` Select col from ( SELECT col1 AS col FROM tab1 UNION SELECT col1 FROM tab2 ORDER BY col OFFSET @offset ROWS FETCH NEXT @fetch ROWS ONLY ) a UNION SELECT TOP 1 col1 FROM tab3 ORDER BY NEWID() ``` **Note :** You can replace `UNION` with `UNION ALL` if you aren't looking for removing duplicates in result.
107,409
After seeing [this answer](https://physics.stackexchange.com/questions/106808/why-is-jumping-into-water-from-high-altitude-fatal/106814#106814) claiming that displacing matter "In a very short time", "no matter whether the matter is solid, liquid, or gas" (even though he concludes that falling from a high altitude is fatal, independent of this). I wondered why then is the jump itself not fatal, considering that there is a significant amount of "gas", that does need to be displaced before even hitting water. Is it because there isn't enough mass per square inch to be fatal? And if so, at what speed would it be fatal? Or is there something else I or the guy who answered that question is missing?
2014/04/08
[ "https://physics.stackexchange.com/questions/107409", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/42491/" ]
It's not the falling that's fatal, it's the deceleration at the end that kills you. Something like water or concrete does this on a sub-meter distance (which requires extremely high forces). On the other hand a gas is much less dense, so it cannot decelerate a falling object nearly as quick. Sometimes [inflatable cushions](http://www.vetter.de/vetter_emergency_media/03_Medien_Produkte_Rettung/02_produktbilder_rettung/153001_SP_60-width-566-height-398.jpg) are used as safety nets (think: stunts/someone jumping off a building scenario). If it is too inflated then the deceleration distance won't be great enough and it can still cause injury or even death. [It seems that a sudden deceleration of ~100g is fatal](http://hypertextbook.com/facts/2004/YuriyRafailov.shtml); that's about 80kN for an average male (80kg). We need the [drag formula](http://en.wikipedia.org/wiki/Drag_%28physics%29): $F\_d = \frac{1}{2}\rho v^2C\_dA$. **Plugging in typical values:** $F\_d = 80\*10^3N$ as asserted above, The density of air humans experience is typically $\rho = 1 \frac{kg}{m^3}$. $A$, the frontal surface of a human seems to be hidden behind pay walls; let's go with $A = 0.5 m^2$ $C\_d$, the [drag coefficient](http://en.wikipedia.org/wiki/Drag_coefficient), is not so straightforward, but we'll go with $1.3$ (man,ski jumper example given on the Wikipedia drag coefficient page). $80\*10^3N=\frac{1}{2}\*1\*v^2\*1.3\*0.5 $... ...results in a speed of about $500 m/s$, or 1800 km/h. This does **not** mean that falling at that speed is lethal. This scenario assumes you suddenly transition form no resistance into dense air.
I don't have exact statistics for any of this. The fall is not what kills you, it is the sudden deceleration at the end. The only thing that can cause a change in speed is another force being applied to you. During the fall, the 2 forces of air resistance and gravity are acting on you constantly in opposite directions, with gravity causing more and more acceleration until you reach terminal velocity, at which the air resistance cancels the gravity out & you fall at the same speed the rest of the way. The air you fall through, while offering resistance, lets you pass through it (almost) as easily as if you were falling through nothingness. However, the ground is not as much of a pushover; it does not let you pass through it as the molecules are too packed together. This means that, once you reach the ground, unless you break it & fall through the floor, you go from moving at tens or hundreds of miles (or km) per hour to essentially 0 in a second or 2. Because of inertia, your body does not want to slow down that fast, so it puts up a lot of resistance. What ends up happening is that some of your body continues falling while the rest of it has already stopped, and so your hands end up hitting the ground, too, your head ends up by your feet, and, if you were falling fast enough, your lungs end up hitting your kneecaps. You pretty much die by being squished to death. The more tightly-packed the ground medium, the faster you will decelerate upon landing and the lower velocity you have to be at before you hit the ground to die. This is because a looser-packed medium lets you fall for a little longer before you stop moving, although it also means you can die before you stop moving, seemingly invalidating the premise of this answer that it's "not the fall that kills you". Even a split second of extra falling time could mean the difference between life & death. For water or lower-pressure ground, such as an airbag or loosely-packed dirt, you have to be moving at a much higher speed to die. Of course, this also depends on things like your height and how tightly-packed *your* insides are. A younger person would usually have to land at a higher speed to die. Another note is that, under certain conditions not usually found on Earth, the fall *can* kill you before you hit the ground. If you have a sudden change in acceleration, such as going from a high-pressure air system to a sufficiently lower-pressure one or vice-versa, you could end up being squished & die. The change in speed, again, determines whether you die.
616,097
Is it possible?
2009/03/05
[ "https://Stackoverflow.com/questions/616097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15884/" ]
See here: [How to install perl modules using CPAN without root](http://sial.org/howto/perl/life-with-cpan/non-root/) I have just set this up on a server without root access and CPAN does everything automatically. But if you *really* wanna install a module without CPAN and you don't have root (assuming this since you don't wanna use CPAN), you can do it as follows ``` perl Makefile.PL PREFIX=$HOME make make install ``` You're gonna have to hunt down dependencies yourself so it's better to use CPAN.
If you are using Red Hat (Fedora, CentOS), you should use RPM for Perl dependencies wherever possible. Perl packages are *almost always* named perl-Module-Name, e.g. perl-DBI, perl-Spreadsheet-WriteExcel, etc. On Ubuntu the naming scheme is libmodule-name-perl.
54,771,214
i have a query which looks like this ``` select max(mytime), type, id from my table where id = 1 group by id, type ``` This gives me results similar to ``` time type id 2018-01-01 green 1 2017-01-03 blue 1 2017-03-03 red 1 ``` I want the type to be on the same based on the max value. So it will take the max time of all similar id's in this case '1' and copy that type for all entries. It should look like ``` time type id 2018-01-01 green 1 2017-01-03 green 1 2017-03-03 green 1 ```
2019/02/19
[ "https://Stackoverflow.com/questions/54771214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8150454/" ]
You most likely have no `Sessions` or `members` arrays in your state before the network request is complete. You could add default values of empty arrays to get around this. ``` class App extends React.Component { state = { Sessions: [], members: [] }; // ... } ```
You can also run the map function only when the sessions or members exists. For that you can do below check like: ``` {this.state.Sessions && this.state.Sessions.map(UsersSession ....... rest of the logic} ```
3,619,036
I'm using JDK1.6. When I implement an interface and in the implementing class, if I give `@override` before my function names, Eclipse throws an compilation error. i.e. below code is wrong according to Eclipse. ``` public class SomeListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent arg0) { // code } /* other overridden methods here */ } ``` If I remove `@Override` annotation, then the code compiles fine. Does it mean that JDK1.6 does not require us to prefix the `@override` annotation anymore?
2010/09/01
[ "https://Stackoverflow.com/questions/3619036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42372/" ]
@Override works on method implementation since java 1.6. --- **Resources :** * [Sun's forums - Java Programming - Should @Override apply to implementation of interface/abstract methods?](http://forums.sun.com/thread.jspa?threadID=5446210) * [dertompson.com - @Override specification changes in Java 6](http://dertompson.com/2008/01/25/override-specification-changes-in-java-6/) * [The Former Weblog of Peter Ahé - @Override snafu](http://blogs.oracle.com/ahe/entry/override_snafu) **On the same topic :** * [When do you use Java's @Override annotation and why?](https://stackoverflow.com/questions/94361/when-do-you-use-javas-override-annotation-and-why)
The @Override annotation changed in Java 1.6 version. In Java 1.5, the compiler didn't allow @Override annotation on implemented interface methods, from 1.6 it does. ![Java Compiler](https://i.stack.imgur.com/LAues.png) You must change java compiler version in properties project -> Java Compiler
14,521,585
I'm not 100% comfortable with a PHP class defined here: [mysqli](https://github.com/opencart/opencart/blob/master/upload/system/database/mysqli.php) I stripped out the guts to shorten it somewhat and get a parse error at runtime. ``` <?php function query($x) { if ($x > 8) { return 'greater than eight!'; } else { return true; } } else { exit(); } } print query(7); ``` It's the same construct (I think) as the original, isn't it? Apart from the signature and the body of the method of course. I haven't come across an if else else clause before and it somehow doesn't 'feel right' for me at least logically wise. Moreover my code won't compile. Maybe you can set me straight? Do you have any examples of how it may be used? Secondly, from the original class - where or how does the $resource variable come into it? In what context would the object get passed a $resource variable? My client code may be: ``` $db = new MySQLi; $db->query("SELECT * FROM my_table"); ``` but I don't see how $resource comes into play?
2013/01/25
[ "https://Stackoverflow.com/questions/14521585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1409731/" ]
The code provided may not reach one of the `return`s for any input `a,b` and that's what the compiler is complaining about. Actually in your case the `if-else` will be reached with the very first iteration - unfortunately something which the compiler cannot deduce. Therefore, it goes the save way and issues this error. *Comment:* Therefore, in your loop seems not to make much sense since it will not iterate at all but stop within the first iteration `i==0` and `h==0`. Did you meant to code something like that?
You don't have a return statement after the for loop but even then h++ is dead code becaue it will never get past the first iteration.
25,725,817
Sorry if this makes no sense, but I will try to give all the information needed! I would like to use rsync to copy a range of sequentially numbered files from one folder to another. I am archiving a DCDM (Its a film thing) and it contains in the order of 600,000 individually numbered, sequential .tif image files (~10mb ea.). I need to break this up to properly archive onto LTO6 tapes. And I would like to use rsync to prep the folders such that my simple bash .sh file can automate the various folders and files that I want to back up to tape. The command I normally use when running rsync is: ``` sudo rsync -rvhW --progress --size only <src> <dest> ``` I use `sudo` if needed, and I always test the outcome first with `--dry-run` The only way I’ve got anything to work (without kicking out errors) is by using the `*` wildcard. However, this only does files with the set pattern (eg. `01*` will only move files from the range `010000 - 019999`) and I would have to repeat for `02`, `03`, `04` etc.. I've looked on the internet, and am struggling to find an answer that works. This might not be possible, and with 600,000 .tif files, I can't write an exclude for each one! Any thoughts as to how (if at all) this could be done? Owen.
2014/09/08
[ "https://Stackoverflow.com/questions/25725817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4019417/" ]
Globing is the feature of the shell to expand a wildcard to a list of matching file names. You have already used it in your question. For the following explanations, I will assume we are in a directory with the following files: ```sh $ ls -l ``` ```none -rw-r----- 1 5gon12eder staff 0 Sep 8 17:26 file.txt -rw-r----- 1 5gon12eder staff 0 Sep 8 17:26 funny_cat.jpg -rw-r----- 1 5gon12eder staff 0 Sep 8 17:26 report_2013-1.pdf -rw-r----- 1 5gon12eder staff 0 Sep 8 17:26 report_2013-2.pdf -rw-r----- 1 5gon12eder staff 0 Sep 8 17:26 report_2013-3.pdf -rw-r----- 1 5gon12eder staff 0 Sep 8 17:26 report_2013-4.pdf -rw-r----- 1 5gon12eder staff 0 Sep 8 17:26 report_2014-1.pdf -rw-r----- 1 5gon12eder staff 0 Sep 8 17:26 report_2014-2.pdf ``` The most simple case is to match all files. The following makes for a poor man's `ls`. ```sh $ echo * ``` ```none file.txt funny_cat.jpg report_2013-1.pdf report_2013-2.pdf report_2013-3.pdf report_2013-4.pdf report_2014-1.pdf report_2014-2.pdf ``` If we want to match all reports from 2013, we can narrow the match: ```sh $ echo report_2013-*.pdf ``` ```none report_2013-1.pdf report_2013-2.pdf report_2013-3.pdf report_2013-4.pdf ``` We could, for example, have left out the `.pdf` part but I like to be as specific as possible. You have already come up with a solution to use this for selecting a range of numbered files. For example, we can match reports by quater: ```sh $ for q in 1 2 3 4; do echo "$q. quater: " report_*-$q.pdf; done ``` ```none 1. quater: report_2013-1.pdf report_2014-1.pdf 2. quater: report_2013-2.pdf report_2014-2.pdf 3. quater: report_2013-3.pdf 4. quater: report_2013-4.pdf ``` If we are to lazy to type `1 2 3 4`, we could have used `$(seq 4)` instead. This invokes the program `seq` with argument `4` and substitutes its output (`1 2 3 4` in this case). Now back to your problem: If you want chunk sizes that are a power of 10, you should be able to extend the above example to fit your needs.
You can check for the file name starting with a digit by using [pattern matching](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html): ``` for file in [0-9]*; do # do something to $file name that starts with digit done ``` Or, you could enable the `extglob` option and loop over all file names that contain only digits. This could eliminate any potential unwanted files that start with a digit but contain non-digits after the first character. ``` shopt -s extglob for file in +([0-9]); do # do something to $file name that contains only digits done ``` * `+([0-9])` expands to one or more occurrence of a digit Update: ------- Based on the file name pattern in your recent comment: ``` shopt -s extglob for file in legendary_dcdm_3d+([0-9]).tif; do # do something to $file done ```
12,642,991
I'm using Font Awesome to create icons on my site, and while they look fantastic on the iPod Touch with Retina display, on my iMac they looks a bit blurred and less defined. Here's an image to demonstrate: ![enter image description here](https://i.stack.imgur.com/CISge.png) As you can see, the font looks really nice and crispt on the Retina Display iPod Touch, but on the iMac, it's kind of crappy. What is causing this? Is this to do with **anti aliasing**? Is there something I can do about this?
2012/09/28
[ "https://Stackoverflow.com/questions/12642991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1261316/" ]
there's a strange trick that works sometime, try: ``` -webkit-transform:rotateZ(0); -moz-transform:rotateZ(0); -o-transform:rotateZ(0); transform:rotateZ(0); ``` if you have a block centered, try to check if left offset is an integer. You can use Javascript to check and fix it. I can help you if you want.
-webkit-perspective: 1000; Fixed it for me
186,082
I use Windows Vista 64-bit and I have 6GB of RAM. Today I installed a new harddrive, and started with moving 465GB of data from my old harddrive to the new one. This process is very slow, the speed is `10,5 MB per second` and I'm not doing anything else on the computer. The estimated time is 12h for this process. Why is it so slow?
2010/09/08
[ "https://superuser.com/questions/186082", "https://superuser.com", "https://superuser.com/users/27037/" ]
One of the main complain about Vista is the slow file copy or move operations. It seems that it is the new "Remote Differential Compression" who is the culprit. To turn it off go in Control Panel / Programs and features / Turn on or turn off Windows features and uncheck "Remote Differential Compression". EDIT: Alternatively, you can install the [Update for Windows Vista for x64-based Systems (KB938979)](http://www.microsoft.com/downloads/details.aspx?FamilyId=24EAD3A0-77F6-4196-8A3F-78C1470AC18E&displaylang=en) which Microsoft released to address the slow move/compression issue.
You shouldn't use Windows Explorer for large copies : It's the planet's slowest copier. Use any Explorer replacement that doesn't come up with Explorer's silly copying dialog. My own favorite is the free [Servant Salamander 1.52](http://www.altap.cz/download.html#salrel). If you have an antivirus, turn it off, since it will insist on checking every copied byte. And finally: If your 12 hours estimate is based on Explorer, be advised that its estimate is normally quite wrong.
9,013,127
I am using boost-thread in my application. When I deploy this application on a client machine (running Ubuntu 11.10), I need to make sure that libboost\_thread.so is available on the machine. However, when I run "apt-get install libboost-thread1.46," it seems to pull in the whole development enviornment (libgcc, libbost1.46-dev, etc.). This machine needs just the runtime environment, not the development environment. I am wondering if there is a better way to handle this.
2012/01/26
[ "https://Stackoverflow.com/questions/9013127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730194/" ]
No such package exception: The package "libboost-thread1.46" does not exist on Ubuntu, is treated by `apt-get` as a regular expression, and the development package *also* matches the expression. The two candidate packages are named `libboost-thread1.46-dev` and [libboost-thread1.46.1](http://packages.ubuntu.com/precise/libboost-thread1.46.1), where the latter is the package you want. It depends only on three libraries (libgcc, libc, libstdc++), *all of which you need to deploy anyway* because your program and libboost-thread link against them. So, deploy by installing `libboost-thread1.46.1` and everything should be fine.
You could link statically against boost.
1,142,405
In C++ a statement like this is valid: ``` &Variable; ``` IMO it doesn't make any sense, so my question is, if you do this, will it affect the compiled result in any way, or will the compiler optimize it away? Thanks!
2009/07/17
[ "https://Stackoverflow.com/questions/1142405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/97688/" ]
It's worth remembering that operator&() might be overloaded for the variable type, have some side effects and optimizing away such statement would change program behaviour. One example is a smart pointer used for controlling the non-C++ objects - [\_com\_ptr\_t](http://msdn.microsoft.com/en-us/library/417w8b3b(VS.80).aspx). It has an overloaded \_com\_ptr\_t::operator&() which checks whether the pointer inside already stores some non-null address. If it turns out that the stored address is non-null it means that the pointer is already attached to some object. If that happens the \_com\_ptr\_t::operator&() disconnects the object - calls IUnknown::Release() and sets the pointer to null. The side effect here is necessary because the typical usage is this: ``` _com_ptr_t<Interface> pointer; // some other code could be here CoCreateInstance( ..., &pointer, ...);// many irrelevant parameters here ``` [CoCreateInstance()](http://msdn.microsoft.com/en-us/library/ms686615(VS.85).aspx) or other object retrieval code has no idea about C++ and \_com\_ptr\_t so it simply overwrites the address passed into it. That's why the \_com\_ptr\_t::operator&() must first release the object the pointer is attached to if any. So for \_com\_ptr\_t this statement: ``` &variable; ``` will have the same effect as ``` variable = 0; ``` and optimizing it away would change program behaviour.
It seems you take a reference to a local variable on stack or register. The best way to find out what the compiler does at the moment is to view the Disassembly view in Visual Studio. [Disassembly view in Debugger (Visual Studio Orcas)](http://social.msdn.microsoft.com/Forums/en-US/vcplus2008prerelease/thread/b8412c3b-1d1c-4821-94f4-2073b81141c6)
34,432
A planet (as well as a dwarf planet) must, according to the IAU definition, have sufficient mass to assume **hydrostatic equilibrium** (a nearly round shape). Does it mean they would break apart or explode if gravity vanishes, unlike small bodies like comets or minor planets, whose integrity doesn't depend on gravity?
2019/12/21
[ "https://astronomy.stackexchange.com/questions/34432", "https://astronomy.stackexchange.com", "https://astronomy.stackexchange.com/users/25871/" ]
While, as far as we know, this is impossible, it is interesting to consider what would happen. Most likely the planet would break apart and possibly, depending on several factors, explode. Rotation speed of the planet, strength of the planet, and presence of liquids or gasses on the planet would all come into play. Here is how I would imagine it playing out on Earth. Without gravity binding the atmosphere to the Earth, it would fairly quickly expand out into the vacuum of space. The oceans would then boil away without atmospheric pressure holding them in place. Without the pressure compressing the magma inside the earth, it too would likely out gas and push the crust of the Earth apart. The centrifugal force from the rotation of the Earth (usually more than countered by gravity) would also aid in flinging the Earth apart. In the case of Earth, I would imagine this would be fairly explosive, and would be rather spectacular to watch from space. I do not know how fast it would explode, but it would almost certainly at least break apart, and probably explode. I would imagine that only the iron core would remain intact (if even that). A planet that is not rotating quickly, and that is solid all the way through might still hold together (e.g. possibly Mercury), but it may still break apart depending on how much gas (if any) is trapped inside. For Saturn, its rings would stop orbiting, and expand out into space. The gas would expand out into space as well, not being held by gravity. I believe this would happen very explosively, since the internal high pressure of the gas is now no longer resisted by gravity. It would likely completely explode into space, except for possibly a rocky core (which would also likely be blown apart by gasses trapped inside, and by the force of the explosion). Centrifugal force would also likely come into play, but I would imagine the explosiveness of the de-pressurized gas would be a much greater factor. This would definitely be interesting to watch from a distance!
A solid planet is kept on place and shape by electromagnetic forces, ie chemistry. Imagine a giant piece of rock. If you turn off gravity nothing change, the big rock would expand for a certain amount, and that is. Obviously this is oversimplified. If gravity was off it could have not formed depending on its history, or formed without acquiring a nearly spherical shape.
10,168,333
I use Dictionary in my code but my colleagues use Hashtable. MSDN says they work on Key Value pair & examples of Hashtable and dictionary are same on MSDN. Then how different are they from each other & which is the best of them or are they suited for difference occasions?
2012/04/16
[ "https://Stackoverflow.com/questions/10168333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1011959/" ]
`KeyValuePair` is the unit of data stored in a `Hashtable` (or `Dictionary`). They are not equivalent to each other. A key value pair contains a single key and a single value. A dictionary or hashtable contains a mapping of many keys to their associated values. `KeyValuePair` is useful when you want to store two related pieces of information as a single unit, especially when one is related to the other in an identifying way (for instance 1234 => "David Smith"). They are also what you get back when you iterate a dictionary. In .NET 4.0, these are really only meant for use internally in a Dictionary- the Tuple class has been introduced for general purpose use. The difference between `Hashtable` and `Dictionary` is that `Hashtable` is not a generic class- both it's keys and values are of type `Object`. `Dictionary` is generic, and should generally be used in favor of `Hashtable` in any new development.
One major difference is that `Hashtable` is thread-safe, while `Dictionary` is not. The [documentation](http://msdn.microsoft.com/en-us/library/system.collections.hashtable.aspx) says: > > `Hashtable` is thread safe for use by multiple reader threads and a single writing thread. It is thread safe for multi-thread use when only one of the threads perform write (update) operations, which allows for lock-free reads provided that the writers are serialized to the `Hashtable`. To support multiple writers all operations on the `Hashtable` must be done through the wrapper returned by the `Synchronized` method, provided that there are no threads reading the Hashtable object. > > > Contrast this with the [`Dictionary` documentation](http://msdn.microsoft.com/en-us/library/xfhwa508.aspx): > > A `Dictionary(Of TKey, TValue)` can support multiple readers concurrently, as long as the collection is not modified. > > >
36,765,577
First off, I saw it and [this other post](https://stackoverflow.com/questions/14831246/access-scalatest-test-name-from-inside-test) sounds exactly like what I need except for one thing, I can't use fixture.TestDataFixture because I can't extend fixture.FreeSpecLike, and I am sure that there must be *some* way to get the test name in a way that looks more like this (imagined code that doesn't compile) ``` class MySpec extends FlatSpecLike with fixture.TestDataFixture { "this technique" - { "should work" in { assert(testData.name == "this technique should work") } "should be easy" in { td => assert(testData.name == "this technique should be easy") } } } ``` Any ideas? I just can't believe something like this is not possible :D
2016/04/21
[ "https://Stackoverflow.com/questions/36765577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/162325/" ]
While you already came to basically this solution, here is a safer variation: ``` private val _currentTestName = new ThreadLocal[String] override def withFixture(test: NoArgTest) = { _currentTestName.set(test.name) val outcome = super.withFixture(test) _currentTestName.set(null) outcome } protected def currentTestName: String = { val testName = _currentTestName.get() assert(testName != null, "currentTestName should only be called in a test") testName } ``` Alternately, ``` protected def currentTestName = Option(_currentTestName.get()) ```
And found an answer(well a collegue did), not sure I like it but works: on the trait that other tests depend on ``` class MySpec extends FlatSpecLike { //... other stuff var testName = "UndefinedTestName" override def withFixture (test: NoArgTest) :Outcome= { testName = test.name super.withFixture(test) } } ``` simple solution but rather obscure, also I wonder if anyone sees any problems with it
4,705,331
Part 1 ====== What is the easiest way to create a text filter which outputs only text surrounded by two predefined marks. I don't mind using any standard tool: sed, awk, python, ... For example, i would like only the text surrounded by "Mark Begin" and "Mark End" to appear. ``` input: Text 1 Mark Begin Text 2 Mark End Text 3 Mark Begin Text 4 MarK End Text 4 output: Text 2 Text 4 ``` Part 2 ====== How can the solution be modified so that only the last occurrence will be written to output, so for the same input above, we get: ``` output: Text 4 ```
2011/01/16
[ "https://Stackoverflow.com/questions/4705331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/264250/" ]
``` $ awk '/Mark End/{f=0}/Mark Begin/{f=1;next}f' file Text 2 Text 4 $ awk '/Mark End/{f=0}/Mark Begin/{f=1;next}f{p=$0}END{print p}' file Text 4 ```
I found a good solution: ``` awk '/Mark End/, /Mark Begin/' file.lst ``` for second case, but it will require mark filtering after all.
38,599,504
So I'm pretty new to development world and I already know how to localize on XAML [just put a x:Uid, pretty easy]. But how can I do that on code? I already tried a few things, but with no success. Can someone help me? Here is the code I'm trying to assign: ``` private void OnShowLoadingChanged(Visibility newVisibility) { ui_progressRing.IsActive = newVisibility == Visibility.Visible; ui_progressRing.Visibility = Visibility.Visible; ui_textBlock.Text = "Loading Comments"; PlayAnimation(newVisibility); } ``` Obviously is the Loading Comments string, and I know that I have to use GetString, but I'm just not doing right...
2016/07/26
[ "https://Stackoverflow.com/questions/38599504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6641732/" ]
You need a resource loader, but you can get one and reuse it like this: ``` private ResourceLoader MyResourceLoader { get { if (_resourceLoader == null) _resourceLoader = new ResourceLoader(); return _resourceLoader; } } private ResourceLoader _resourceLoader { get; set; } ``` Then it's just ``` MyResourceLoader.GetString(key) ```
In the resource file, [tbImage.Text], [imgMain.Source] have been setted. You can use x:Uid in xaml. And in c# methods, to get resource according to the language, you can use this code snippet: ``` ResourceContext resourceContext = new ResourceContext(); resourceContext.Languages = new string[] { language }; ResourceMap resourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources"); string imageSource= resourceMap.GetValue("imgMain/Source", resourceContext).ValueAsString; this.imgMain.Source = new BitmapImage(new Uri(imageSource, UriKind.RelativeOrAbsolute)); this.tbImage.Text = resourceMap.GetValue("tbImage/Text", resourceContext).ValueAsString; ``` There's a sample about UWP localization in MSDN. <https://code.msdn.microsoft.com/how-to-create-a-localizatio-c61f4b37>
280,000
I have to calculate the determinant of this matrice. I want to use the rule of sarrus, but this does only work with a $3\times3$ matrice: $$ A= \begin{bmatrix} 1 & -2 & -6 & u \\ -3 & 1 & 2 & -5 \\ 4 & 0 & -4 & 3 \\ 6 & 0 & 1 & 8 \\ \end{bmatrix} $$ $|A|=35$ Any idea how to solve this?
2013/01/16
[ "https://math.stackexchange.com/questions/280000", "https://math.stackexchange.com", "https://math.stackexchange.com/users/36656/" ]
$$A=\begin{pmatrix}1 & -2 & -6 & u \\-3 & 1 & 2 & -5 \\4 & 0 & -4 & 3 \\6 & 0 & 1 & 8 \\\end{pmatrix}\stackrel{ 3R\_1+R\_2}{\stackrel{-4R\_1+R\_3}{\stackrel{-6R\_1+R\_4}\longrightarrow}}\begin{pmatrix}1 & -2 & \;\;-6 & \;\;\;u \\0 & -5 & -16 & \;\;\,3u-5 \\0 & \;\;\;8 & \;\;\;20 &-4u+ 3 \\0 & \;\,12 & \;\;\;37 & -6u+8 \\\end{pmatrix}$$ Now develop the above wrt the first column and you get a $\,3\times 3\,$ determinant. Compute now directly or repeat the above process.
Use [Leibniz formula](http://en.wikipedia.org/wiki/Leibniz_formula_for_determinants) or the [Laplace expansion](http://en.wikipedia.org/wiki/Laplace_expansion). For more an Laplace expansion see [youtube video](http://www.youtube.com/watch?v=louFpVlOhK8) .
4,000,713
If i have a loop such as ``` users.each do |u| #some code end ``` Where users is a hash of multiple users. What's the easiest conditional logic to see if you are on the last user in the users hash and only want to execute specific code for that last user so something like ``` users.each do |u| #code for everyone #conditional code for last user #code for the last user end end ```
2010/10/22
[ "https://Stackoverflow.com/questions/4000713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/94150/" ]
Another solution is to rescue from StopIteration: ``` user_list = users.each begin while true do user = user_list.next user.do_something end rescue StopIteration user.do_something end ```
There are no last method for hash for some versions of ruby ``` h = { :a => :aa, :b => :bb } last_key = h.keys.last h.each do |k,v| puts "Put last key #{k} and last value #{v}" if last_key == k end ```
472,312
My challenge ------------ We have Exchange servers at various sites, but also aboard ships. The ships are connected to our network through satellite links when at sea, but switch to WiFi bridges when in port. Due the high latency (500+ ms) and not-uncommon drop-outs (e.g. when the ships are turning), attempting to send any e-mails above a few megabytes while at sea, is likely to fail and be retried until the limit has been reached. The result: The email doesn't get delivered and each try consumes valuable bandwidth on the sat link. One "solution" is to limit the maximum e-mail size to say 5 MB, but that's hardly user friendly and an unnecessary restriction while in port. Rough idea ---------- What I'd rather do, is to queue all e-mails larger than a set limit for later delivery when at sea, while sending all small e-mails immediately. I was then thinking I'd ping the hub transport server in our datacenter regularly, when latency drops under ~400 ms, I'd start processing the large e-mails queue. When latency goes up over 400 ms, I'd plug the hole and let e-mails queue up again. Now, I haven't gotten my hands really dirty with Exchange since version 2003. Back then, you could schedule large e-mails for later delivery, so my idea was do something similar in Exchange 2010, then script a way to switch the delivery schedule for large e-mails between 'always' and 'never'. Obstacle -------- It shouldn't be too complicated to create a script like that, but then I read that the feature I'd rely on was removed with Exchange 2007: > > This was a feature present in Exchange 2003 but has been removed for > Exchange 2007. It was set on an SMTP Connector with the 'use different > delivery times for oversize messages'. > > > [TechCenter: Is it possible to schedule email delivery based on size in Exchange?](https://social.technet.microsoft.com/forums/en/exchangesvrsecuremessaginglegacy/thread/24709884-b8a0-4bf7-88f3-8f2d8cabae97 "Is it possible to schedule email delivery based on size in Exchange?") Questions --------- Is it true? - Is this feature no longer present in Exchange 2010, or has it merely transformed into something similar, I can use to accomplish my goal? If so, what? Is there another way to defer delivery of large e-mails on certain Exchange servers? It could be based on a schedule or maybe even requiring specific action - I'm fairly certain there will be some way to trigger the delivery through script, I just need large e-mails in a separate queue on ships. Your thoughts on this will be highly appreciated! :-) Edit #1: Refined Rough Idea --------------------------- I stumpled upon two PowerShell CmdLets I think can bring me pretty close to my goal: * [`Suspend-Message`](http://technet.microsoft.com/en-us/library/aa997457.aspx "Suspend-Message") * [`Resume-Message`](http://technet.microsoft.com/en-us/library/bb124421.aspx "Resume-Message") I toyed around with Get-Message for a while, to see what kind of messages the commands above would deal with. Most importantly, these commands accept a message size filter. This command will list queued messages,on the current server, larger than 5 MB (5,242,880 bytes): ``` get-message -Filter {Size -gt 5242880} ``` It seems `Get-Message` only returns messages from various remote delivery queues. But does messages flowing within the server, however briefly, show up in a queue that Get/Suspend/Resume-Message will mess with? If not, the solution could be as simple as a scheduled script every few minutes, along the lines of (in pseudo code): ``` if ping_rtt > 400 Then Suspend-Message -Filter {Size -gt 5242880} Else Resume-Message EndIf ``` **Concerns/follow-up questions:** *Mostly irrelvant now - see edit #2.* Will `Get-Message` only return messages from remote delivery queues - never messages for intra-server delivery? If not, does the identity name of remote delivery queues follow a certain pattern, that I can use for filtering? Could/should this be done via a custom Transport Agent (as suggested by @longneck) or an Event Sink (if this concept still exists in Exchange 2010)? Say I run the script every 5 minutes, that still means large messages being sent, can potentially cause problems for up to 5 minutes, before getting suspended. We'd still be better off than we are now, but it's not optimal. I could increase the frequency to every minute, but it wouldn't be the most elegant solution. Even if I only check round-trip time every 5 minutes (to save sat traffic), what Exchange mechanism would I need to setup, in order to check against the last recorded RTT, each time a message is submitted that goes to a remote delivery queue, and then take approriate action? Edit #2: Proposed Solutions --------------------------- Allow me to summarise the proposed solutions, and their pros and cons as I see it: **Custom Transport Agent** *Concept* * Periodically monitor latency, classify as high or low (threshold: 400 ms?) * Through a custom Transport Agent, suspend/resume all e-mails larger than a set threshold, when latency classification changes * Through the custom TA, immediately put subsequently submitted large messages in "suspend" mode, if latency is high *Strengths* * Large e-mails are never attempted delivered when latency is high *Weaknesses* * No development skills to make this in-house (note to self: source code should belong to my company as part of the contract with the external developer) * 3rd party software that ties into Exchange can cause problems when patching or updating * Some sort of support agreement necessary, in case something goes wrong (see above) **Moderate Large Messages** *Concept* * Periodically monitor latency, classify as high or low (threshold: 400 ms?) * Based on latency classification, configure Exchange Transport Rules through scripting, to either let all messages flow or forward large messages to moderator * Approve messages in moderator queue when ship's in port, possibly by a human *Strengths* * Large e-mails are never attempted delivered when latency is high * Messages are suspended using native native Exchange Transport Rules *Weaknesses* * By the looks of it, messages can not be approved programmatically when latency is low, hence human intervention is required each time ship's in port * Possibly privacy issues, if moderation is not handled programmatically *Questions* * *Can* messages be approved programmatically from moderator mailbox? How? **Scheduled PowerShell commands** *Concept* * Periodically monitor latency, classify as high or low (threshold: 400 ms?) * As long as latency is high, frequently (every minute?) suspend any large messages (`Suspend-Message -Filter {Size -gt 5242880}`) * When latency drops to low, resume all messages (`Resume-Message`) *Strengths* * Very simple to implement *Weaknesses* * Not the most elegant solution * Delivery of each new large message can be attempted for as long as the interval between `Suspend-Message` commands, possibly still wasting some bandwidth and create congestions (though very briefly compared to not doing anything) *Questions* * Any ideas on how to prevent attempts to deliver large messages, in-between `Suspend-Message` commands? * Will `Get-Message` only return messages from remote delivery queues - never messages for intra-server delivery? If not, does the identity name of remote delivery queues follow a certain pattern, that I can use for filtering? Edit #3: The Way Forward ------------------------ After bringing the proposed solutions up in my team (including the SMTP proxy, which I failed to include in edit #2), and based on my own gut feeling, we decided to go for a custom Exchange Transport Agent. I'm in contact with a couple of consultancy companies, who will get back to me with how the will attack the problem and what it would cost. If you have any experience with outsourcing programming tasks, feel free to leave feedback to my [related question on Stack Overflow](https://stackoverflow.com/questions/14746400/what-requirements-specifications-should-be-part-of-small-programming-outsourcing "asd"), because I don't.
2013/01/25
[ "https://serverfault.com/questions/472312", "https://serverfault.com", "https://serverfault.com/users/105219/" ]
To solve the problem the way you have requested, you could write your own Transport Agent using the [Microsoft Exchange Transport Agent SDK](http://www.microsoft.com/en-us/download/details.aspx?id=13156). Transport Agents are event based so Exchange will call a function in your library when a message is received. Your library can then do something like hold the message. If you don't have the skills in-house to do this, I'm sure you could hire a developer to write it for you. But I don't think this is a great solution. As an alternative for you to investigate, you might want to look in to something like an SMTP proxy for low-quality links. As you have discovered, SMTP is a horrible protocol for low-quality links because an interrupted connection causes the message transmission to restart from the beginning instead of resuming from where it left off. If you're going to hire a developer for something, I would consider writing a server program that accepts incoming SMTP connections and sends the message on to a remote instance of this same program at the other end of the satellite connection in a resumable manner (possibly segregating the large messages from the small messages via TCP port to allow for QoS treatment by your WAN accelerator). The remote instance could then, upon receipt of the complete message, complete the delivery of the message via SMTP.
**Message Moderation** One probably non-ideal solution is to use a transport rule to forward messages over a certain size to either the sender's manager or a designated mailbox (on the ship's Exchange server) for moderation. This way if they are at sea, large messages can be essentially queued up in another mailbox. When the ship arrives at port, the manager or designated moderator can approve them for delivery. The downsides are: * this rule is always on unless you manually disable it (but could be done via a script) so even in port large messages would redirect to the moderator mailbox * all large messages would need manual review by someone before sending, but you can add exceptions in the rule for specific things * another person would be reading outgoing mail, which may not be ideal due to privacy concerns, but this depends on your org One upside is you would have a human making decisions on whether or not a message should even be sent such as if a user was trying to send a bunch of non work-related crap that would just bog down the connection for no reason. They could be corrected by administrative controls like pointing to a policy and slapping them on the wrist so they don't do it again. [Exchange 2010 Transport Rules](http://technet.microsoft.com/en-us/library/aa995961%28v=exchg.141%29.aspx) **Custom Script** RE: A custom script to manage large e-mails. I could see something like the below that would enable/disable your Send Connector on the Exchange server. A downside is all mail is held in queue instead of just large messages, but some logic along these lines should work: 1. Check for latency. If it is low, enable the Send Connector, unsuspend any large messages, and wait 5 minutes (or other arbitrary length of time). If it is high, disable the Send Connector. 2. Wait 5 minutes. 3. After 5 minutes, check for large messages and suspend them. Re-enable the Send Connector so small, queued messages are released until the queue is empty (you could even cycle through 1 message at a time so as to not clog the queue/WAN link after re-enabling the Send connector) 4. Disable the Send Connector and goto #1 This logic isn't fully polished to make 100% sense, but you get the idea - queue all mail, check for latency, suspend large messages if it is high, un-queue mail, queue all mail, etc. Another downside of running a script like this is if it ever crashes or stops, how would you know to reinitialize it with no IT staff on board the ships? It could either potentially stop all outbound mail indefinitely (if it stops after disabling the Send Connector) or you could lose your large message control if it just leaves the Send Connector enabled and the script is no longer running. **SMTP Proxy** Even though you have indicated you are against any message handling outside of Exchange, After thinking about this some more, I've decided I'm with @longneck on using some type of SMTP proxy solution. Even IIS SMTP has a deferred delivery mechanism that it would seem Exchange 2010 does not. You could redirect large messages to the IIS SMTP server which could store them on disk, and, checking for latency first, have the IIS SMTP server send them via a script when latency is low. The worst-case if your scheduling mechanism got stuck or stopped would be the large messages get stuck on disk, but small messages continue to be sent. There are probably better solutions than IIS SMTP, and I have never used it myself, but it is just an example. [Configure SMTP E-Mail in IIS 7](http://www.iis.net/learn/application-frameworks/install-and-configure-php-on-iis/configure-smtp-e-mail-in-iis-7-and-above)
17,995,962
I created a custom component which extended from `JTextField`. I want to prevent calling `getText()` method from my component. Is there a solution for this problem?
2013/08/01
[ "https://Stackoverflow.com/questions/17995962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971067/" ]
Override it and throw [UnsupportedOperationexception](http://docs.oracle.com/javase/7/docs/api/java/lang/UnsupportedOperationException.html) in method body or just leave it empty. Throwing exception will guarantee you that this method is never used since you'll be getting exceptions otherwise and fix.
Override it with a dummy implementation and add documentation mentioning `Not to be used!` or throw an exception from inside.
23,806
Why video call has no (even if there is, it is lower than human perception can discern) latency, but no matter what options of ffmpeg I tried to transmit video to a remote server, the lowest I can get is ~0.2s latency (estimated, not sure how to profile)? ***What is the technology behind video call that allows it to be much faster than ffmpeg?*** I tried sending to the server and make the server send back the stream using the following commands: CLIENT: termimal 1- ``` ffmpeg -pixel_format mjpeg -s hd720 -r 30 -i /dev/video1 -c libx264 -preset ultrafast -tune zerolatency -crf 18 -b 5M -f matroska -vf hflip tcp://X:5000 ``` termimal 2- ``` mplayer -benchmark ffmpeg://tcp://Y:5000?listen ``` SERVER: ``` ffmpeg -i tcp://X:5000 -c copy -f matroska tcp://Y:5000 ``` However, the video I got back has a slight delay of about 0.5s (estimated, not sure how to profile). Is sending to and fro different that causes it to have longer delay?
2018/04/13
[ "https://avp.stackexchange.com/questions/23806", "https://avp.stackexchange.com", "https://avp.stackexchange.com/users/21908/" ]
Try using UDP. It should be faster than TCP but with possibility of losing paackets.
Sources of any delays: 1. TCP protocol. Long handshake, possible error with time loss in future 2. Long encoder initialization (video call already prepared it) 3. Long decoder initialization (video call already prepared it), buffering for analyze data 4. Unoptimized protocol / format for low-time communication, like MKV 5. Prebuffering in encoder for B-frames and other optimizations Video conferencing software also have many tricks to detect delays and resync streams. It why in video conferencing has frame drops and it not suitable for transmitting high quality video.
42,468
What is the difference between Strict Avalanche Criterion(SAC) and Avalanche criterion?
2016/12/21
[ "https://crypto.stackexchange.com/questions/42468", "https://crypto.stackexchange.com", "https://crypto.stackexchange.com/users/42265/" ]
The definition of avalanche effect is given in the paper of Webster, A. F. ["On the design of S-boxes". Advances in Cryptology - Crypto '85](https://link.springer.com/chapter/10.1007%2F3-540-39799-X_41#page-1) as : > > For a given transformation to exhibit the avalanche effect, **an average of one half of the output bits should change whenever a single input bit is complemented**. > > > It is also seen as **each bit should have 50% chances to change if you change 1 bit of the input**. (strict avalanche) --- In the **avalanche criterion** you look at the **output as a whole** (average 50% of the bits changes). In the **strict avalanche criterion**, you look at **each bit one by one** and you verify that what ever the other bits will change, it will have a 50% probability to switch. Related questions: * [Hash functions and the Avalanche effect](https://crypto.stackexchange.com/questions/40268/hash-functions-and-the-avalanche-effect/40271#40271) * [Calculation of the avalanche effect coefficient](https://crypto.stackexchange.com/questions/34269/calculation-of-the-avalanche-effect-coefficient)
Avalanche criterion, or Avalanche effect is informal. Small changes in inputs should always lead to large changes in outputs. Consider a vector Boolean function $$f:F\_2^n \rightarrow F\_2^m$$ with $n$ bit input and $m$ bit output. Strict Avalanche Criterion (SAC) says that if any input bit is flipped then exactly half of output bits should change. There are higher order versions as well where $k$ input bits are flipped and the same property is required of the output bits.
18,464,346
I am getting a a request like this and the url looks like this : <http://domain.com/page.php?text=>{Arabic Word} Now am trying to get the text using $\_GET['text'] but i keep getting it like "????????" , whats the problem ``` <?php header('Content-type: text/html; charset=UTF-8'); include('EnTransliteration.class.php'); $tr = new EnTransliteration(); $str = iconv( "utf-8//TRANSLIT//IGNORE","windows-1256", $_GET['text']); $en_str = $tr->ar2en($str); $string = <<<XML <root> <translation>$en_str</translation> </root> XML; $xml = new SimpleXMLElement($string); header('Content-type: text/xml; charset=UTF-8'); echo $xml->asXML(); ?> ```
2013/08/27
[ "https://Stackoverflow.com/questions/18464346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2017288/" ]
Your HTML form needs to explicitly declare that the data must be sent as UTF-8. Otherwise, it will use the user's locale, which may not mean windows-1256, and certainly doesn't mean UTF-8. e.g. ``` <form action="" method="get" accept-charset="UTF-8"> ```
1-open start 2-open notepad 3-write your code 4-when you saving file make Encoding: utf-8 5-file name name.html name.php
4,794
I am curious to the information and level of detail that people are storing on Kanban cards? Or beter yet some templates of how they are put together. For reference here is a description of a Kanban Card <http://en.wikipedia.org/wiki/Kanban_cards>
2010/09/04
[ "https://pm.stackexchange.com/questions/4794", "https://pm.stackexchange.com", "https://pm.stackexchange.com/users/3284/" ]
Why not apply Kaizen to your Kanban cards? Start with the smallest thing that gives you value - probably a title, so you can identify what the card represents. Get feedback from the team about the next most important thing that's missing. Add that. Repeat. Stop when adding information would no longer be an improvement. The team should feel comfortable with suggesting the removal of information when it's no longer needed, too. You may also want to include the input of other stakeholders, if they use your board for status, etc.
Its all up to how big is your Dev Team and how they are comfortable with, kid of information. From my point of view> Agile < Kan-ban card don't have any set value to fill with the information. Default values are already discussed here. SO GO agile and using Kan-ban system at your ease level.
2,846,872
I'm currently using the following code for thread-safe access of a variable. ``` int gnVariable; void getVariableValue(int *pnValue) { acquireLock(); //Acquires the protection mechanism *pnValue = gnVariable; releaseLock(); //Releasing the protection mechanism } ``` I would like to change my API signature to a more user-friendly ``` int getVariableValue(void); ``` How should I rewrite the function - such that the users of the API don't have to bother about the locking/unlocking details?
2010/05/17
[ "https://Stackoverflow.com/questions/2846872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/293407/" ]
Since you gave C++ as an option, you can wrap the mutex lock/unlock. You can then return the value directly: ``` class lock_wrapper { public: lock_wrapper() { acquireLock(); } ~lock_wrapper() { releaseLock(); } }; int getVariableValue() { lock_wrapper lw; return gnVariable; } ``` This will also come in handy if you ever need to do a lock/unlock around code that can throw an exception.
You return a copy of the local variable. Something like: ``` int getVariableValue(void) { int local= 0; acquireLock(); local = gnVariable; releaseLock(); return local; } ``` As a side note, it is better to [RAII](http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization) principle for locking instead of `acquireLock` and `releaseLock` methods.
20,970,980
I earlier learned that abstract class can extend concrete class. Though I don't see the reason for it from JAVA designers, but it is ok. I also learned that abstract class that extends concrete class can make overriden methods abstract. Why? Can you provide with use case where it is useful? I am trying to learn design patterns and I do not want to miss anything. Here is example: ``` public class Foo { public void test() { } } public abstract class Bar extends Foo { @Override public abstract void test(); } ```
2014/01/07
[ "https://Stackoverflow.com/questions/20970980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2764414/" ]
This becomes useful if I have a set of classes that I want a default implementation of `test()` for (so they can extend from `Foo`), and a subset of those classes that I want to force to provide their own implementation (in which case making it abstract in the subclass would enforce this.) Of course, the alternative way in this example would be to declare `test()` abstract in the top level class rather than in the subclass, and that's what you'd usually do - but there are cases where satisfying the is-a relationship of inheritance means that it occasionally makes more sense from a design perspective doing it this way around. It's rare, but you do sometimes see it. As an aside, though a special case, remember that all classes implicitly extend `Object` unless otherwise specified. So if you include this case, abstract classes extending concrete classes isn't so unusual after all!
If you make the `test` method abstract it forces anyone deriving from the `Bar` class provide an implementation of the method. If you remove the abstract method from the `Bar` class then anyone deriving from `Bar` would not *have* to implement the `test` method as `Foo` already provides an (empty) implementation.
170,318
To my understanding, mixed states is composed of various states with their corresponding probabilities, but what is the actual difference between [maximally mixed states](http://www.google.com/search?as_epq=maximally+mixed+state) and [maximally entangled states](http://www.google.com/search?as_epq=maximally+entangled+state)?
2015/03/14
[ "https://physics.stackexchange.com/questions/170318", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/74564/" ]
Suppose we have two Hilbert spaces $\mathcal{H}\_A$ and $\mathcal{H}\_B$. A quantum state on $\mathcal{H}\_A$ is a normalized, positive trace-class operator $\rho\in\mathcal{S}\_1(\mathcal{H}\_A)$. If $\mathcal{H}\_A$ is finite dimensinal (i.e. $\mathbb{C}^n$), then a quantum state is just a positive semi-definite matrix with unit trace on this Hilbert space. Let's stick to finite dimensions for simplicity. Let's now consider the idea of a pure state: A pure state is a rank-one state, i.e. a rank-one projection, or a matrix that can be written as $|\psi\rangle\langle \psi|\equiv\psi\psi^{\dagger}$ for some $\psi\in\mathcal{H}\_A$ (the first being the Dirac notation, the second is the usual mathematical matrix notation - since I don't know which of the two you are more familar with, let me use both). A mixed state is now a convex combination of pure states and, by virtue of the spectral theorem, any state is a convex combination of pure states. Hence, a mixed state can be written as $$ \rho=\sum\_i \lambda\_i |\psi\_i\rangle \langle \psi\_i|$$ for some $\lambda\_i\geq 0$, $\sum\_i \lambda\_i=1$. In a sense, the $\lambda\_i$ are a probability distribution and the state $\rho$ is a "mixture" of $|\psi\rangle\langle\psi|$ with weights $\lambda\_i$. If we assume that the $\psi\_i$ form an orthonormal basis, then a **maximally mixed state** is a state where the $\lambda\_i$ are the uniform probability distribution, i.e. $\lambda\_i=\frac{1}{n}$ if $n$ is the dimension of the state. In this sense, the state is maximally mixed, because it is a mixture where all states occur with the same probability. In our finite dimensional example, this is the same as saying that $\rho$ is proportional to the identity matrix. Note that a maximally mixed state is defined for all Hilbert spaces! In order to consider **maximally entangled states**, we need to have a bipartition of the Hilbert space, i.e. we now consider states $\rho\in\mathcal{S}\_1(\mathcal{H}\_A\otimes \mathcal{H}\_B)$. Let's suppose $\mathcal{H}\_A=\mathcal{H}\_B$ and finite dimensional. In this case, we can consider entangled state. A state is called *separable*, if it can be written as a mixture $$ \rho =\sum\_i \lambda\_i \rho^{(1)}\_i\otimes \rho^{(2)}\_i $$ i.e. it is a mixture of product states $\rho^{(1)}\_i$ in the space $\mathcal{H}\_A$ and $\rho^{(2)}\_i$ in the space $\mathcal{H}\_B$. All states that are not separable are called *entanglend*. If we consider $\mathcal{H}\_A=\mathcal{H}\_B=\mathbb{C}^2$ and denote the standard basis by $|0\rangle,|1\rangle$, an entangled state is given by $$ \rho= \frac{1}{2}(|01\rangle+|10\rangle)(\langle 01|+\langle 10|)$$ You can try writing it as a separable state and you will see that it's not possible. Note that this state is pure, but entangled states do not need to be pure! It turns out that for bipartite systems (if you consider three or more systems, this is no longer true), you can define an order on *pure* entangled states: There are states that are more entangled than others and then there are states that have the maximum amount of possible entanglement (like the example I wrote down above). I won't describe how this is done (it's too much here), but it turns out that there is an easy characterization of a maximally entangled state, which connects maximally entangled and maximally mixed states: A pure bipartite state is maximally entangled, if the reduced density matrix on either system is maximally mixed. The reduced density matrix is what is left if you take the [partial trace](http://en.wikipedia.org/wiki/Partial_trace) over one of the subsystems. In our example above: $$ \rho\_A = tr\_B(\rho)= tr\_B(\frac{1}{2}(|01\rangle\langle 01|+|10\rangle\langle 01|+|01\rangle\langle 10|+|10\rangle\langle 10|))=\frac{1}{2}(|0\rangle\langle 0|+|1\rangle\langle 1|) $$ and the last part is exactly the identity, i.e. the state is maximally mixed. You can do the same over with $tr\_A$ and see that the state $\rho$ is therefore maximally entangled.
When the state space for a system can be expressed as a tensor product of the state spaces of individual components of the system, an entangled state is one that can't be expressed as a tensor product of states of those individual components. Thus an entangled state is a particular type of (pure, i.e. non-mixed) state. A mixed state, by contrast, is a probability distribution over pure states. This makes perfectly good sense whether or not the state space decomposes as a tensor product. So an entangled state is a mixed state only in the degenerate sense that the probability distribution is concentrated on a single point. Of course you can also have a non-trivial mixture of entangled states.
3,457,697
friend's I have a task to place the horizontal scroll or swipe menu tabs in my application i did it where the appears top of the header,but my problem is to place the scroll menu has below the header i have RelativeLayout where it contains two elements one after another, ----------------------------------------------------------------------- ``` TextView - for header Gallery - for Scroll menu items ``` from the above code Gallery content been set from my activity, * for example the output i'm getting 1. looks, scroll menus(Gallery) - Header 2. (text view defined the above layout) ======================================== * but i need it has 1. + Header (text view defined the above layout) - 2. scroll menus(Gallery) how can i get it. thanks in advance.
2010/08/11
[ "https://Stackoverflow.com/questions/3457697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407506/" ]
Solved this by using CURL. Here's the code. It will work with remote files e.g. **<http://yourdomain.com/file.ext>** ``` $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, ''.$file_path_str.''); curl_setopt($ch, CURLOPT_HTTPGET, 1); curl_setopt ($ch, CURLOPT_HEADER, 0); curl_setopt ($ch, CURLOPT_USERAGENT, sprintf("Mozilla/%d.0",rand(4,5))); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_MAXREDIRS, 10); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $curl_response_res = curl_exec ($ch); curl_close ($ch); ``` I could not use @James solution because I'm using `ob_start` and `ob_flush` elsewhere in my code, so that would have messed things up for me.
I recently solved this problem. On my windows machine it is acceptable to have spaces in your folder names. However PHP wasnt able to read this path. I changed my folder name From: ``` C:\Users\JasonPC\Desktop\Jasons Work\Project ``` To: ``` C:\Users\JasonPC\Desktop\JasonsWork\Project ``` Then PHP was able to read my files again.
29,115,837
I'm currently making a program which asks the user for the input for two integers and compare if they are correct. I need help coding this program. (sorry I am new to c++). For example, this is my desired output. Enter your positive integer: 123 Enter your positive integer: 124 number 1: 123 number 2: 124 number of comparison: 3 3 -- 4 (incorrect) 2 -- 2 (correct) 1 -- 1 (correct) so far i have this code: ``` void twoInt() { int first, second; cout << "\n\nEnter your positive integer : "; cin >> first; cout << "\nEnter your positive integer : "; cin >> second; cout << "\n\nNumber 1: " << setw(10) << first; cout << "\nNumber 2: " << setw(10) << second; // how do i compare each digit that user has entered //through keyboard and compare them to first and second integer variable fflush(stdin); cin.get(); } ``` which in-built function should i use to compare by using a for loop? Thanks in advance! Any tips and help will be much appreciated!
2015/03/18
[ "https://Stackoverflow.com/questions/29115837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4330757/" ]
``` void twoInt() { int first, second; int fDigit; int sDigit; cout << "\n\nEnter your positive integer : "; cin >> first; cout << "\nEnter your positive integer : "; cin >> second; cout << "\n\nNumber 1: " << setw(10) << first; cout << "\nNumber 2: " << setw(10) << second; while ( (first ) && (second )) { fDigit = first % 10; first = first/10; sDigit = second % 10; second = second / 10; if (fDigit == sDigit ) { printf(" %d - % d Correct\n",fDigit,sDigit); } else { printf(" %d - % d Incorrect\n",fDigit,sDigit); } } fflush(stdin); cin.get(); } ```
Convert both numbers to strings with std::to\_string() Compare with the algorithm that you prefer: std::equal() or std::mismatch() Why don't you compare them directly as intergers?
5,851,569
**HTML** ``` <form action="inc/q/prof.php?pID=<?php echo $the_pID; ?>" method="post"> <select id="courseInfoDD" name="courseInfoDD" tabindex="1"><?php while($row3 = $sth3->fetch(PDO::FETCH_ASSOC)) { echo "<option>".$row3['prefix']." ".$row3['code']."</option>"; }echo "</select>"; ?> <input type="text" id="addComment" name="addComment" tabindex="3" value="Enter comment" /> <input type="hidden" name="pID" value="<?php echo $the_pID; ?>"> <input type="submit" name="submit" id="submit" /> </form> ``` **PHP** ``` $connect = mysql_connect("##", $username, $password) or die ("Error , check your server connection."); mysql_select_db("###"); //Get data in local variable if(!empty($_POST['courseInfoDD'])) $course_info=mysql_real_escape_string($_POST['courseInfoDD']); if(!empty($_POST['addComment'])) $course_info=mysql_real_escape_string($_POST['addComment']); if(!empty($_POST['pID'])) $the_pID=mysql_real_escape_string($_POST['pID']); print_r($_POST); echo $the_pID; // check for null values if (isset($_POST['submit'])) { $query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')"; mysql_query($query) or die(mysql_error()); echo "Your message has been received"; } else if(!isset($_POST['submit'])){echo "No blank entries";} else{echo "Error!";} ``` ?> ?> **Table** ``` commId int(11) info text date timestamp reported char(1) degree char(1) pID int(11) cID int(11) ``` It gives me `"Error!"` now, I try the db credentials and they are fine... ?? And the `r_post(`) is still giving an error of `Array()` Why isn't Array() accepting values? Anyone???
2011/05/01
[ "https://Stackoverflow.com/questions/5851569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/700070/" ]
Like @user551841 said, you will want to limit your possibility of sql injection with his code. You are seeing that error because you're code told it to echo that error if nothing was entered, which is the case upon first page load. You shouldn't need that until submit is done. Edit: Sorry, I was assuming you are directly entering the page which needs the $\_POST data without going through the form submit. You also should do something along the lines of if(!isset($variable)) before trying to assign it to something less your server will spit out error of undefined variables. ``` if(!empty($_POST['courseInfoDD'])) $course_info=mysql_real_escape_string($_POST['courseInfoDD']); ``` do that to all of them. Then you can check ``` if (!isset($user_submitted) && !isset($the_comment) && !isset($course_info) && !isset($the_pID) ){ echo "All fields must be entered, hit back button and re-enter information"; } else{ $query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')"; mysql_query($query) or die(mysql_error()); echo "Your message has been received"; } ```
To answer to your question `what is wrong here` **you've got a huge gaping SQL-injection hole!!** Change this code ``` //Get data in local variable $course_info=$_POST['courseInfoDD']; $the_comment=$_POST['addComment']; $the_pID=$_POST['pID']; ``` To this ``` //Get data in local variable $course_info = mysql_real_escape_string($_POST['courseInfoDD']); $the_comment = mysql_real_escape_string($_POST['addComment']); $the_pID = mysql_real_escape_string($_POST['pID']); ``` See: [How does the SQL injection from the "Bobby Tables" XKCD comic work?](https://stackoverflow.com/questions/332365/xkcd-sql-injection-please-explain) For more info on SQL-injection.
34,597
What is the difference between French and British cuts of beef? I am told they just butcher the animals dfferently. Certainly the cuts don't seem the same. For example is faux fillet really exactly the same as British sirloin and is entrecôte really the same as rib steak? Here is a picture of British beef cuts. ![enter image description here](https://i.stack.imgur.com/lFABs.jpg)
2013/06/09
[ "https://cooking.stackexchange.com/questions/34597", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/18672/" ]
The simplest way to see the difference is to compare the cut diagrams: **British** ![enter image description here](https://i.stack.imgur.com/1c2DT.png) **French** ![enter image description here](https://i.stack.imgur.com/cQioc.png) Images courtesy of [Wikipedia - Cut of Beef](https://en.wikipedia.org/wiki/Cut_of_beef) The main difference is in how certain areas are sub-divided. We can see that faux-filet is *part* of the British sirloin, and entrecote is partly forerib and partly sirloin.
Two things 1.The French diagram seemsfar more detailed than the English one, which lacks several cuts 2. Meat cuts are regional in both countries, but I think more in the UK The obvious examples have already been mentioned, fillet steak is definitely an English cut,the eye of the loin. French paleron = feather or blade (regional names) Skirt is not shown (it is related to onglet). Neck is not a cut commonly sold in London, I'm not even sure what I'd ask for, I suspect it goes into anonymous stewing steak and mince
37,651,380
I am trying to toggle the background colour of a div element but my code doesn't work. I wrote the following code: ``` $(document).ready(function(){ var $on_off = true; $('div.hot').on('click', function($on_off){ if($on_off){ $(this).css('background-color', 'red'); } else{ $(this).css('background-color', 'yellow'); } $on_off = !$on_off; }); }); ``` I don't understand why this wouldn't work. Thanks!
2016/06/06
[ "https://Stackoverflow.com/questions/37651380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3887531/" ]
> > Remove argument from `on` handler as first argument is `event-object` which is always evaluated as `true`(`Boolean({})===true`) > > > ```js $(document).ready(function() { var $on_off = true; $('div.hot').on('click', function() { if ($on_off) { $(this).css('background-color', 'red'); } else { $(this).css('background-color', 'yellow'); } $on_off = !$on_off; }); }); ``` **Simplified code:** ```js $(document).ready(function() { var $on_off = true; $('div.hot').on('click', function() { $(this).css('background-color', $on_off ? 'red' : 'yellow'); $on_off = !$on_off; }); }); ```
Event handlers receives an [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event) Object when they are invoked but you are expecting another variable (`$on_off`) which doesn't exist inside event handler. So `$on_off` variable that you have passed to event handler is in fact an object which will be automatically created and passed to the event handlers when they are invoked. This object is commonly referred to as `event` or `e`. This object contains necessary information about event that is actually happened. To use `$on_off` variable you don't need to pass it to event handler explicitly. ```js $(document).ready(function(){ var $on_off = true; $('div.hot').on('click', function(event){ event.preventDefault(); if($on_off){ $(this).css('background-color', 'red'); } else{ $(this).css('background-color', 'yellow'); } $on_off = !$on_off; }); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="hot">Click Me</div> ```
38,785,924
we are using Postgresql 9.4 and i noticed a strange behavior when using date\_trunc. The time zone in result is shifted by 1hr: ``` select date_trunc('year','2016-08-05 04:01:58.372486-05'::timestamp with time zone); date_trunc ------------------------ 2016-01-01 00:00:00-06 ``` There is no such behavior when truncating to for example day: ``` select date_trunc('day','2016-08-05 04:01:58.372486-05'::timestamp with time zone); date_trunc ------------------------ 2016-08-05 00:00:00-05 ``` Is this expected behavior? If so what is the logic behind that?
2016/08/05
[ "https://Stackoverflow.com/questions/38785924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5168941/" ]
The `date_trunc(text, timestamptz)` variant seems a bit under-documented, so here are my findings: 1) below the `day` precision (first parameter) the time zone **offset** of the result is always the same as the second parameters' offset. 2) at or above `day` precision, the time zone **offset** is recalculated, according to the current `TimeZone` configuration parameter (which [can be set](https://www.postgresql.org/docs/current/static/sql-set.html) with `set time zone '...'` or `set TimeZone to '...'`). The recalculated offset is always the same as it would be on that exact time-instant with the **same** `TimeZone` configuration parameter in effect. So, f.ex. when the `TimeZone` parameter **contains DST** information, then the offset is aligned accordingly. However, when the actual `TimeZone` parameter does not contain DST informations (such as a fix offset), the result's time zone offset is untouched. All-in-all, the `date_trunc(text, timestamptz)` function can be simulated with the `date_trunc(text, timestamp)` variant and the `at time zone` operator**s**: ``` date_trunc('month', tstz) ``` should be equivalent to: ``` date_trunc('month', tstz at time zone current_setting('TimeZone')) at time zone current_setting('TimeZone')) ``` At least, that's what I thought. As it turned out, there are some `TimeZone` configuration settings, which are problematic. Because: > > PostgreSQL allows you to specify time zones in three different forms: > > > * A **full time zone name**, for example `America/New_York`. The recognized time zone names are listed in the `pg_timezone_names` view (see Section 50.80). PostgreSQL uses the widely-used IANA time zone data for this purpose, so the same time zone names are also recognized by much other software. > * A **time zone abbreviation**, for example `PST`. Such a specification merely defines a particular offset from `UTC`, in contrast to full time zone names which can imply a set of daylight savings transition-date rules as well. The recognized abbreviations are listed in the `pg_timezone_abbrevs` view (see Section 50.79). You cannot set the configuration parameters `TimeZone` or `log_timezone` to a time zone abbreviation, but you can use abbreviations in date/time input values and with the AT TIME ZONE operator. > > > (The third is the fix offset, or its POSIX form, but that's not important here). As you can see, **abbreviations** cannot be set to `TimeZone`. But there are some abbreviations, which is also considered a **full time zone name**, f.ex. `CET`. Thus, `set time zone 'CET'` will succeed, but will actually use `CEST` in the summer time. But `at time zone 'CET'` will always refer to the **abbreviation**, which is a fixed offset from `UTC` (and never `CEST`, for that one can use `at time zone 'CEST'`; but `set time zone 'CEST'` is invalid). Here is a full list of time zone settings, which has incompatible meanings when they are used in `set time zone` vs. when they are used in `at time zone` (as of 9.6): ``` CET EET MET WET ``` With the following script, you can check for your version: ``` create or replace function incompatible_tz_settings() returns setof text language plpgsql as $func$ declare cur cursor for select name from pg_timezone_names; begin for rec IN cur loop declare r pg_timezone_names; begin r := rec; execute format('set time zone %L', (r).name); if exists(select 1 from generate_series(current_timestamp - interval '12 months', current_timestamp + interval '12 months', interval '1 month') tstz where date_trunc('month', tstz) <> date_trunc('month', tstz at time zone (r).name) at time zone (r).name) then return next (r).name; end if; end; end loop; end $func$; ``` <http://rextester.com/GBL17756>
It is expected to have two variants of `date_trunc`: one for `timestamp` and one for `timestamptz`, because [the doc](https://www.postgresql.org/docs/current/static/functions-datetime.html) says: > > All the functions and operators described below that take time or > timestamp inputs actually come in two variants: one that takes time > with time zone or timestamp with time zone, and one that takes time > without time zone or timestamp without time zone. For brevity, these > variants are not shown separately. > > > Should you want to better understand timestamp and timestamptz, read first [the great answer here](https://stackoverflow.com/questions/9571392/ignoring-timezones-altogether-in-rails-and-postgresql/9576170#answer-9576170). Then about `date_trunc`. According to my experiments and interpretation of various SO answers (like [this one](https://stackoverflow.com/questions/29102110/how-do-i-specify-the-start-of-today-in-a-specific-time-zone)), everything behaves as if, when receiving a timestamptz, `date_trunc` first converts it to a timestamp. This conversion returns a timestamp in local time. Then truncation is performed: keep only the date and drop the hours/min/seconds. To avoid this conversion (thanks pozs), provide a timestamp (not timestamptz) to date\_trunc: ``` date_trunc('day', TIMESTAMPTZ '2001-07-16 23:38:40Z' at time zone 'UTC') ``` the part `at time zone 'UTC'` says "convert this timestamptz to a timestamp in UTC time" (the hour isn't affected by this conversion). Then date\_trunc returns `2001-07-16 00:00:00`.
32,891,518
**EDIT: This question is deprecated.** Please see [How to set a variable from an $http call then use it in the rest of the application WITHOUT making the whole application asynchronous](https://stackoverflow.com/questions/33129638/how-to-set-a-variable-from-an-http-call-then-use-it-in-the-rest-of-the-applicat) instead. In my constant, I need to read from a local file. The way I've seen to do that is `$http.get('localfile.ext').then ...` It's telling me `$http` is undefined. The [documentation](http://www.learn-angular.org/#!/lessons/the-constant-recipe) says constant is special, services are available in a constant. ``` angular.module('myApp').constant( 'test', ['xml','$http', (function ($http, x2js) { $http.get('web.config').then(function (response) { var appSettings = []; /*setting up the response*/ var json = x2js.xml_str2json(response.data); var url = '' /* get url from json */; }); // Use the variable in your constants return { URL: url } })()]); ``` **EDIT:** Ok [this documentation](https://github.com/angular/angular.js/wiki/Understanding-Dependency-Injection) says you can't use DI in a constant. But I need to use $http to get a value and use it to set a constant. So how can I do it or what would be a alternative that allows me to read the value anywhere in the app once it is set?
2015/10/01
[ "https://Stackoverflow.com/questions/32891518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1045881/" ]
**Build a constant** Build the confguration into Angular `constant` with build system. There are [grunt-ng-constant](https://github.com/werk85/grunt-ng-constant) and [gulp-ng-constant](https://github.com/guzart/gulp-ng-constant). **Resolve the dependency** Use ng-route or ui-router `resolve` to resolve config dependency for all routes. **Defer bootstrap** Defer bootstrapping process to resolve global dependencies before the app is there with [angular-deferred-bootstrap](https://github.com/philippd/angular-deferred-bootstrap). **Use synchronous request** Synchronous requests are blocking, and bad, and blocking... they are bad also. Either raw `XMLHttpRequest` or `jQuery.ajax` can be used (`$http` doesn't support synchronous requests). ``` app.config(function ($provide) { var config; var xhr = new XMLHttpRequest(); xhr.open('GET', 'configfile', false); xhr.send(); if (xhr.status == '200') { config = xhr.responseText; } $provide.constant('config', config); }); ```
What I've generally done is to generate the code for the constant on the server. As opposed to having the constant populated by some call back to the server. ``` using Newtonsoft.Json.Linq; public class JavascriptConstantsHelper { public static string GetConstantsJavascriptFile() { var constantsCollectionModel = new JObject(); constantsCollectionModel.Add("version", CoreAssembly.Version.ToString()); const string outputTemplate = @" (function() { 'use strict'; window.myModule.constant('constantsCollection', function() { return {constantsCollection}; }); })();"; return outputTemplate.Replace("{constantsCollection}", constantsCollectionModel.ToString()); } } ``` The controller could look like this then ``` public class JavascriptController : Controller { public ActionResult GetConstants() { return Content(JavascriptConstantsHelper.GetConstantsJavascriptFile(), "application/javascript"); } } ``` The script tag would then look something like this ``` <script src="/Javascript/GetConstants"></script> ```
12,830,197
I want to declare an array of arrays or multidimensional array without knowing the size. I want to do something similar to what I did in this cases with simple arrays: ``` int *array; cin >> size; array = new int[size]; ``` Maybe I can loop to initialize a pointer of pointers like this: ``` int **array; cin >> rows >> col; array = new *int[rows] for (int i = 0; i < rows; ++i) array[i] = new int[col]; ``` But I would prefer to not do this if a better solution exists.
2012/10/10
[ "https://Stackoverflow.com/questions/12830197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1192999/" ]
You're pretty much going to have to go with the loop version. You can make one slight improvement, which is to allocate one big block and then build your own `int*` index into it: ``` int **array; int *storage; cin >> rows >> col; array = new *int[rows]; storage = new int[rows*col]; for (int i = 0; i < rows; ++i) array[i] = storage + col * i; ``` This has the nice property that you can still use `array[i][j]` syntax for accessing the array.
You could use a single std::vector to contain the entire two dimensional array and wrap it in a class to hide the details. Here's an example, it uses a `data( row, col )` member function that returns a reference to the element at `row` and `col`. I included an example 2 dimensional matrix of `int` where each entry in the array is initialized to the product of its `row` and `col`. When an instance of this class goes out of scope, the default destructor will get called and release the memory, that way you don't have to remember to call delete[] to release the memory. All elements of the matrix will be contiguous in memory, this is cache friendly and should give you good performance. ``` #include <iostream> #include <vector> #include <stdexcept> template <typename T> class matrix { std::vector<T> data_; public: size_t const rows_; size_t const cols_; matrix(size_t rows, size_t cols) : rows_(rows) , cols_(cols) , data_( rows * cols ) {} T& data( size_t row, size_t col ) { if (row > rows_ || col > cols_) throw std::out_of_range("matrix"); return data_[ row * cols_ + col ]; } }; int main( int argc, char** argv ) { matrix<int> array(100,100); for(size_t r=0; r < array.rows_; ++r) { for(size_t c=0; c < array.cols_; ++c) { array.data(r,c) = r * c; } } std::cout << "8 x 7 = " << array.data(8,7) << std::endl; return 0; // array goes out of scope here, memory released automatically } ``` When you run this you will get ``` 8 x 7 = 56 ```
460,293
Having the hours and minutes, is there any easier or better way to set it into a Calendar object than: ``` calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), hour, minute); ```
2009/01/20
[ "https://Stackoverflow.com/questions/460293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6068/" ]
In 2018 no one should use the `Calendar` class anymore. It it long outmoded, and `java.time` the modern Java date and time API is so much nicer to work with. Instead use, depending on you exact requirements, a `ZonedDateTime` or perhaps an `OffsetDateTime` or `LocalDateTime`. In either case, set the time of day this way: ``` dateTime = dateTime.with(LocalTime.of(hour, minute)); ``` **Link**: [Oracle Tutorial Date Time](https://docs.oracle.com/javase/tutorial/datetime/)
In addition to [the great accepted answer by Xn0vv3r](https://stackoverflow.com/a/460312/2359227), don't forget to set `calendar.set(Calendar.SECOND, 0);`
53,654,728
The **following code** displays the **following window**: ``` import numpy as np import matplotlib.pylab as pl import matplotlib.gridspec as gridspec from matplotlib import pyplot as plt def plot_stuff(x,y,z): gs = gridspec.GridSpec(3, 1) plt.style.use('dark_background') pl.figure("1D Analysis") ax = pl.subplot(gs[0, 0]) ax.set_ylabel('X VALUE') pl.plot(x, color="red") ax = pl.subplot(gs[1, 0]) ax.set_ylabel('Y VALUE') pl.plot(y, color="green") ax = pl.subplot(gs[2, :]) ax.set_ylabel('Z VALUE') pl.plot(z, color="blue") plt.show() ``` [![](https://i.stack.imgur.com/ySSNa.png)](https://i.stack.imgur.com/ySSNa.png) How do I close the window without an explicit mouse click? I need to visualize a LOT of data so I'm searching a way to automating the process of opening and closing windows. I know that `plt.show()` is a blocking operation and I've tried using the `plt.close("all")` method *as mentioned in the related questions* but the window remains there, does not close and I have to close it manually. **I need a simple code for automating the process of opening a window, visualize the data, closing the window after a certain interval of time; and then repeat the procedure in a for loop fashion.**
2018/12/06
[ "https://Stackoverflow.com/questions/53654728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5052566/" ]
Here is another solution, using an explicit `close` statement to close then recreate the figure at each iteration ``` from matplotlib import gridspec import matplotlib.pyplot as plt import numpy as np def plot_stuff(x, y, z): gs = gridspec.GridSpec(3, 1) plt.style.use('dark_background') fig = plt.figure("1D Analysis") ax = plt.subplot(gs[0, 0]) ax.set_ylabel('X VALUE') plt.plot(x, color="red") ax = plt.subplot(gs[1, 0]) ax.set_ylabel('Y VALUE') plt.plot(y, color="green") ax = plt.subplot(gs[2, :]) ax.set_ylabel('Z VALUE') plt.plot(z, color="blue") return fig things_to_plot = [np.random.random(size=(100, 3)), np.ones((100, 3)), np.random.random(size=(100, 3))] delay = 5 if __name__ == "__main__": plt.ion() for things in things_to_plot: fig = plot_stuff(x=things[:, 0], y=things[:, 1], z=things[:, 2]) plt.show() plt.pause(delay) plt.close() ```
I have tested the below solution and which is working perfectly. I have used only pylab module. ``` import numpy as np import matplotlib.pylab as pl import matplotlib.gridspec as gridspec def plot_stuff(x,y,z): pl.ion() # interactive mode on gs = gridspec.GridSpec(3, 1) pl.style.use('dark_background') pl.figure("1D Analysis") ax = pl.subplot(gs[0, 0]) ax.set_ylabel('X VALUE') pl.plot(x, color="red") ax = pl.subplot(gs[1, 0]) ax.set_ylabel('Y VALUE') pl.plot(y, color="green") ax = pl.subplot(gs[2, :]) ax.set_ylabel('Z VALUE') pl.plot(z, color="blue") pl.show() pl.pause(3) # pause for 3 sec pl.close() # close the window items = [np.random.rand(100, 3), np.random.randint(10, size=(100, 3)), np.random.rand(100, 3)] for item in items: plot_stuff(x=item[:, 0], y=item[:, 1], z=item[:, 2]) ```
44,322,178
I am using Android Database Component Room I've configured everything, but when I compile, Android Studio gives me this warning: > > Schema export directory is not provided to the annotation processor so > we cannot export the schema. You can either provide > `room.schemaLocation` annotation processor argument OR set > exportSchema to false. > > > As I understand it is the location where DB file will be located How can it affect my app? What is the best practice here? Should I use the default location (`false` value)?
2017/06/02
[ "https://Stackoverflow.com/questions/44322178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3101777/" ]
I use `.kts` Gradle files (Kotlin Gradle DSL) and the `kotlin-kapt` plugin but I still get a script compilation error when I use Ivanov Maksim's answer. ``` Unresolved reference: kapt ``` For me this was the only thing which worked: ``` android { defaultConfig { javaCompileOptions { annotationProcessorOptions { arguments = mapOf("room.schemaLocation" to "$projectDir/schemas") } } } } ```
Probably you didn't add your room class to child `RoomDatabase` child class in `@Database(entities = {your_classes})`
13,133,734
I have run this below query and it is giving error: ``` UPDATE t_o SET t_o.mlm_order_id = mt.order_id FROM temp_orders t_o, mlm_transaction mt WHERE mt.v2_order_id = t_o.order_id ``` Error is: ``` #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM temp_orders t_o, mlm_transaction mt WHERE mt.v2_order_id = t_o.order_id' at line 3 ``` Please help ??
2012/10/30
[ "https://Stackoverflow.com/questions/13133734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1784710/" ]
One more version - ``` UPDATE temp_orders t_o, mlm_transaction mt SET t_o.mlm_order_id = mt.order_id WHERE mt.v2_order_id = t_o.order_id ```
Updates don't use the FROM clause. Use something like this: ``` UPDATE table_name SET column1=value1, column2=value2,... WHERE some_column=some_value ```
61,338,917
I have a dataframe that has x/y values every 5 seconds, with a depth value every second (time column). There is no depth where there is an x/y value. ``` x <- c("1430934", NA, NA, NA, NA, "1430939") y <- c("4943206", NA, NA, NA, NA, "4943210") time <- c(1:6) depth <- c(NA, 10, 19, 84, 65, NA) data <- data.frame(x, y, time, depth) data x y time depth 1 1430934 4943206 1 NA 2 NA NA 2 10 3 NA NA 3 19 4 NA NA 4 84 5 NA NA 5 65 6 1430939 4943210 6 NA ``` I would like to calculate the maximum depth between the x/y values that are not NA and add this to a new column in the row of the starting x/y values. So max depth of rows 2-5. An example of the output desired. ``` x y time depth newvar 1 1430934 4943206 1 NA 84 2 NA NA 2 10 NA 3 NA NA 3 19 NA 4 NA NA 4 84 NA 5 NA NA 5 65 NA 6 1430939 4943210 6 NA NA ``` This is to repeat whenever a new x/y value is present.
2020/04/21
[ "https://Stackoverflow.com/questions/61338917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11372268/" ]
You can use `ave` and `cumsum` with `!is.na` to get the groups for ave like: ``` data$newvar <- ave(data$depth, cumsum(!is.na(data$x)), FUN= function(x) if(all(is.na(x))) NA else { c(max(x, na.rm=TRUE), rep(NA, length(x)-1))}) data # x y time depth newvar #1 1430934 4943206 1 NA 84 #2 <NA> <NA> 2 10 NA #3 <NA> <NA> 3 19 NA #4 <NA> <NA> 4 84 NA #5 <NA> <NA> 5 65 NA #6 1430939 4943210 6 NA NA ```
Using `dplyr`, we can create groups of every 5 rows and update the first row in group as `max` value in the group ignoring `NA` values. ``` library(dplyr) df %>% group_by(grp = ceiling(time/5)) %>% mutate(depth = ifelse(row_number() == 1, max(depth, na.rm = TRUE), NA)) ``` --- In base R, we can use `tapply` : ``` inds <- seq(1, nrow(df), 5) df$depth[inds] <- tapply(df$depth, ceiling(df$time/5), max, na.rm = TRUE) df$depth[-inds] <- NA ```
1,061,911
How well does Django handle the case of different timezones for each user? Ideally I would like to run the server in the UTC timezone (eg, in settings.py set TIME\_ZONE="UTC") so all datetimes were stored in the database as UTC. Stuff like [this](https://stackoverflow.com/questions/689831/changing-timezone-on-an-existing-django-project) scares me which is why I prefer UTC everywhere. But how hard will it be to store a timezone for each user and still use the standard django datetime formatting and modelform wrappers. Do I anticipate having to write date handling code everywhere to convert dates into the user's timezone and back to UTC again? I am still going through the django tutorial but I know how much of a pain it can be to deal with user timezones in some other frameworks that assume system timezone everywhere so I thought I'd ask now. My research at the moment consisted of searching the django documentation and only finding [one reference](http://docs.djangoproject.com/en/dev/ref/settings/#time-zone) to timezones. --- Additional: * There are a [few bugs submitted](http://code.djangoproject.com/ticket/2626) concerning Django and timezone handling. * Babel has [some contrib code for django](http://svn.edgewall.org/repos/babel/contrib/django/) that seems to deal with timezone formatting in locales.
2009/06/30
[ "https://Stackoverflow.com/questions/1061911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84262/" ]
**Update, January 2013**: Django 1.4 now has [time zone](https://docs.djangoproject.com/en/3.2/topics/i18n/timezones/) support!! --- Old answer for historical reasons: I'm going to be working on this problem myself for my application. My first approach to this problem would be to go with django core developer Malcom Tredinnick's advice in [this django-user's post](http://groups.google.com/group/django-users/msg/ee174701c960ff2d). You'll want to store the user's timezone setting in their user profile, probably. I would also highly encourage you to look into the [pytz module](http://pytz.sourceforge.net/), which makes working with timezones less painful. For the front end, I created a "timezone picker" based on the common timezones in pytz. I have one select box for the area, and another for the location (e.g. US/Central is rendered with two select boxes). It makes picking timezones slightly more convenient than wading through a list of 400+ choices.
Django doesn't handle it at all, largely because Python doesn't either. Python (Guido?) has so far decided not to support timezones since although a reality of the world are "[more political than rational, and there is no standard suitable for every application](http://docs.python.org/library/datetime.html#module-datetime)." The best solution for most is to not worry about it initially and rely on what Django provides by default in the settings.py file `TIME_ZONE = 'America/Los_Angeles'` to help later on. Given your situation [pytz](http://pytz.sourceforge.net/#example-usage) is the way to go (it's already been mentioned). You can install it with `easy_install`. I recommend converting times on the server to UTC on the fly when they are asked for by the client, and then converting these UTC times to the user's local timezone on the client (via Javascript in the browser or via the OS with iOS/Android). The server code to convert times stored in the database with the `America/Los_Angeles` timezone to UTC looks like this: ``` >>> # Get a datetime from the database somehow and store into "x" >>> x = ... >>> >>> # Create an instance of the Los_Angeles timezone >>> la_tz = pytz.timezone(settings.TIME_ZONE) >>> >>> # Attach timezone information to the datetime from the database >>> x_localized = la_tz.localize(x) >>> >>> # Finally, convert the localized time to UTC >>> x_utc = x_localized.astimezone(pytz.utc) ``` If you send `x_utc` down to a web page, Javascript can convert it to the user's operating system timezone. If you send `x_utc` down to an iPhone, iOS can do the same thing, etc. I hope that helps.
41,837,927
I am trying to implement realm migration using version v0.81.0 When I install and run the new version of the app with an additional field in one of my data access objects, instead of calling the realm migration callback it just throws an exception (RealmMigrationNeededException) telling me I have to migrate because I have added a property to one of my data access objects. This is my first attempt at migration therefore previously the callback to schema version was not set Here is my code, can anyone see any issues. The encryption key used here is just for example purposes ``` try { var config = new RealmConfiguration("MyExampleDatabase.realm"); var encryptionKey = new byte[64] // key MUST be exactly this size { 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, }; config.EncryptionKey = encryptionKey; // Start of new code added config.MigrationCallback = (migration, oldSchemaVersion) => { // do migration here!! }; config.SchemaVersion = 1; // End of new code added var realm = Realm.GetInstance(config); return realm; } catch (Exception ex) { // Log error here } ```
2017/01/24
[ "https://Stackoverflow.com/questions/41837927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1898970/" ]
Your code was throwing the same format because both **DateFormat** were constructed with the same pattern and that is not correct.. ``` SimpleDateFormat sdfuk = new SimpleDateFormat("dd/MM", Locale.UK); SimpleDateFormat sdfus = new SimpleDateFormat("dd/MM", Locale.US); ``` You will need the local if you have a String that is going to be converted to date... for the parsing you are trying to do (string -> Date) only the pattern is ok... **Example** ``` DateFormat sdfuk = new SimpleDateFormat("dd/MM"); DateFormat sdfus = new SimpleDateFormat("MM/d"); System.out.println(sdfuk.format(new Date())); // 24/01 System.out.println(sdfus.format(new Date())); // 01/24 ```
tl;dr ===== ``` MonthDay.from( LocalDate.now( ZoneId.of( "America/Montreal" ) ) ).format( DateTimeFormatter.ofPattern( "MM/dd" ) ) ``` > > 01/24 > > > `MonthDay` ========== There's a class for that: [`MonthDay`](https://docs.oracle.com/javase/8/docs/api/java/time/MonthDay.html). The `MonthDay` represents the combination of a month and day-of-month. ``` MonthDay md = MonthDay.of( Month.JANUARY , 24 ); ``` Avoid legacy date-time classes. =============================== Avoid the troublesome old date-time classes such as `SimpleDateFormat`, now legacy, supplanted by the java.time classes. The `MonthDay` class is part of the java.time framework built into Java 8 and later. Much of java.time is back-ported to Java 6 & Java 7 (see below). ISO 8601 ======== > > md.toString(): --01-24 > > > The `toString` method generates a String in standard [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. The `MonthDay` class can also parse such strings. Current date ============ You want the month-day of the current date. For the current date we will use the `LocalDate` class. The [`LocalDate`](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html) class represents a date-only value without time-of-day and without time zone. Time zone --------- A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in [Paris France](https://en.wikipedia.org/wiki/Europe/Paris) is a new day while still “yesterday” in [Montréal Québec](https://en.wikipedia.org/wiki/America/Montreal). Specify a [proper time zone name](https://en.wikipedia.org/wiki/List_of_tz_zones_by_name) in the format of `continent/region`, such as [`America/Montreal`](https://en.wikipedia.org/wiki/America/Montreal), [`Africa/Casablanca`](https://en.wikipedia.org/wiki/Africa/Casablanca), or `Pacific/Auckland`. Never use the 3-4 letter abbreviation such as `EST` or `IST` as they are *not* true time zones, not standardized, and not even unique(!). Be clear that `Locale` has *nothing* to do with time zones. A `Locale` only applies to the format of text when generating strings, but is separate and distinct from time zone. ``` ZoneId z = ZoneId.of( "America/Montreal" ); LocalDate today = LocalDate.now( z ); ``` Now extract a `MonthDay` object. ``` MonthDay md = MonthDay.from( today ); ``` > > today.toString(): 2017-01-25 > > > md.toString(): --01-25 > > > Other formats ============= You can generate strings in other formats. The java.time classes can automatically localize some date-time values by `Locale`. Unfortunately, this does not apply to `MonthDay`. For `MonthDay` you must explicitly specify the desired format in a `DateTimeFormatter` object when you want something other than the standard ISO 8601 format. By the way, I encourage you to **stick with the standard format whenever possible**, especially for exchanging data. You might even consider training your users to accept this format. The standard format is unambiguous, whereas your UK-US formats (dd/MM, MM/dd) can be entirely ambiguous such as 01/02 being either January 2nd or February 1st. [`Locale`](http://docs.oracle.com/javase/8/docs/api/java/util/Locale.html) to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, and such. Generally, I advise always specifying a `Locale` for your `DateTimeFormatter` rather than relying implicitly on the JVM’s current default `Locale`. But I do not see any way the `Locale` would affect the output of this particular format. So I omit the `Locale` in this example. ``` DateTimeFormatter fUS = DateTimeFormatter.ofPattern( "MM/dd" ); DateTimeFormatter fUK = DateTimeFormatter.ofPattern( "dd/MM" ); String output = md.format( fUS ); ``` Live code ========= See this example [code run live at IdeOne.com](http://ideone.com/HTZbqW). --- About java.time =============== The [java.time](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) framework is built into Java 8 and later. These classes supplant the troublesome old [legacy](https://en.wikipedia.org/wiki/Legacy_system) date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html), & [`SimpleDateFormat`](http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html). The [Joda-Time](http://www.joda.org/joda-time/) project, now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advises migration to the [java.time](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. To learn more, see the [Oracle Tutorial](http://docs.oracle.com/javase/tutorial/datetime/TOC.html). And search Stack Overflow for many examples and explanations. Specification is [JSR 310](https://jcp.org/en/jsr/detail?id=310). Where to obtain the java.time classes? * [**Java SE 8**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8) and [**SE 9**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9) and later + Built-in. + Part of the standard Java API with a bundled implementation. + Java 9 adds some minor features and fixes. * [**Java SE 6**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6) and [**SE 7**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7) + Much of the java.time functionality is back-ported to Java 6 & 7 in [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/). * [**Android**](https://en.wikipedia.org/wiki/Android_(operating_system)) + The [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project adapts *ThreeTen-Backport* (mentioned above) for Android specifically. + See [*How to use ThreeTenABP…*](https://stackoverflow.com/q/38922754/642706). The [ThreeTen-Extra](http://www.threeten.org/threeten-extra/) project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as [`Interval`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html), [`YearWeek`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html), [`YearQuarter`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html), and [more](http://www.threeten.org/threeten-extra/apidocs/index.html).
390,449
Hmmm. Is there a primer anywhere on memory usage in Java? I would have thought Sun or IBM would have had a good article on the subject but I can't find anything that looks really solid. I'm interested in knowing two things: 1. at runtime, figuring out how much memory the classes in my package are using at a given time 2. at design time, estimating general memory overhead requirements for various things like: * how much memory overhead is required for an empty object (in addition to the space required by its fields) * how much memory overhead is required when creating closures * how much memory overhead is required for collections like ArrayList I may have hundreds of thousands of objects created and I want to be a "good neighbor" to not be overly wasteful of RAM. I mean I don't really care whether I'm using 10% more memory than the "optimal case" (whatever that is), but if I'm implementing something that uses 5x as much memory as I could if I made a simple change, I'd want to use less memory (or be able to create more objects for a fixed amount of memory available). I found a few articles ([Java Specialists' Newsletter](http://www.javaspecialists.eu/archive/Issue078.html) and something from [Javaworld](http://www.javaworld.com/cgi-bin/mailto/x_java.cgi?pagetosend=/export/home/httpd/javaworld/javaworld/javaqa/2003-12/02-qa-1226-sizeof.html&pagename=/javaworld/javaqa/2003-12/02-qa-1226-sizeof.html&pageurl=http://www.javaworld.com/javaworld/javaqa/2003-12/02-qa-1226-sizeof.html&site=jw_core)) and one of the builtin classes [java.lang.instrument.getObjectSize()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/instrument/Instrumentation.html) which claims to measure an "approximation" (??) of memory use, but these all seem kind of vague... (and yes I realize that a JVM running on two different OS's may be likely to use different amounts of memory for different objects)
2008/12/24
[ "https://Stackoverflow.com/questions/390449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44330/" ]
If you are using a pre 1.5 VM - You can get the approx size of objects by using serialization. Be warned though.. this can require double the amount of memory for that object.
I believe the profiler included in Netbeans can moniter memory usage also, you can try that
306,768
I'm looking for a **UPNP/DLNA Client for Windows**. The server is **MediaTomb** on a Ubuntu box. The clients are **Windows** (any, XP and up). I'm looking for a *simplistic* music player program but failed to identify any. I'm hoping for something in the *style* of Winamp or Windows Media Player. I've looked, but so far only been able to achieve playback on Windows with HTPC-ish software like **XBMC**, and on an **android** cellphone (several players for that there, all worked fine). Edit: Just to clarify, I'm not looking for an HTPC Suite (IE XBMC), I'm looking for a regular-looking music player.
2011/07/05
[ "https://superuser.com/questions/306768", "https://superuser.com", "https://superuser.com/users/85665/" ]
[foobar2000](http://www.foobar2000.org/) has a supported DNLA [plugin](http://www.foobar2000.org/components/view/foo_upnp). Its winamp-styled, configurable and works pretty well in general
Have you tried VLC? <http://www.videolan.org/vlc/> Upgrade it to VLC media player 2.0.1 Twoflower. UPnP was added back into the Windows build as of V2. If you still like your V1.1 for some reason you can always parallel install V2 in a different folder. Open the Playlist menu. On the left side, click on Local Network and Universal Plug'n'Play should be an item, click on it and wait from a few seconds up to 30 seconds or so to list all the media servers on your lan. Click on your media server's icon and work with its media listings. It may take a while for it to populate a large collection's listings. You can build playlists from there.
2,861,139
I have a class that implements an interface. In another area of the code I check if that class instance contains that interface, but it doesn't work. The check to see if the class contains the interface always fails (false) when it should be true. Below is a simple representation of what I am trying to accomplish. Example ``` public interface IModel { bool validate(); } public class SomeModel : IModel { public SomeModel { } public bool Validate() { return true; } } // Dummy method public void Run() { SomeModel model = new SomeModel(); if (model is IModel) { string message = "It worked"; } else { string message = "It failed"; } } ```
2010/05/18
[ "https://Stackoverflow.com/questions/2861139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173432/" ]
Did you make sure you tested against the correct interface? By that I mean, is your "is" test using the correct version of IModel? IModel doesn't strike me as a unique type name, so you may have imported an incorrect namespace. Try explicitly qualifying your check. I.e. ``` if (model is MyNamespace.IModel) ... ```
One *very* common error here is to declare the interface in two different assemblies, for example by including the same `.cs` file in two different dlls. Since types are defined by their assembly, this gives two *conflicting* interfaces, which *happen* to have the same name. The same scenario is also common (with *different* namespaces), for example when importing web-services; the proxy/generated type is different to the originating type.
4,530,069
I am trying to subtract one date value from the value of `datetime.datetime.today()` to calculate how long ago something was. But it complains: ```none TypeError: can't subtract offset-naive and offset-aware datetimes ``` The return value from `datetime.datetime.today()` doesn't seem to be "timezone aware", while my other date value is. How do I get a return value from `datetime.datetime.today()` that is timezone aware? The ideal solution would be for it to automatically know the timezone. Right now, it's giving me the time in local time, which happens to be PST, i.e. UTC - 8 hours. Worst case, is there a way I can manually enter a timezone value into the `datetime` object returned by `datetime.datetime.today()` and set it to UTC-8?
2010/12/25
[ "https://Stackoverflow.com/questions/4530069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/323874/" ]
Here is a solution using a readable timezone and that works with today(): ``` from pytz import timezone datetime.now(timezone('Europe/Berlin')) datetime.now(timezone('Europe/Berlin')).today() ``` You can list all timezones as follows: ``` import pytz pytz.all_timezones pytz.common_timezones # or ```
If you get current time and date in python then import date and time,pytz package in python after you will get current date and time like as.. ``` from datetime import datetime import pytz import time str(datetime.strftime(datetime.now(pytz.utc),"%Y-%m-%d %H:%M:%S%t")) ```
4,970,489
Using the development server, it works with debug=True or False. In production, everything works if debug=True, but if debug=False, I get a 500 error and the apache logs end with an import error: "ImportError: cannot import name Project". Nothing in the import does anything conditional on debug - the only code that does is whether the development server should serve static files or not (in production, apache should handle this - and this is tested separately and works fine).
2011/02/11
[ "https://Stackoverflow.com/questions/4970489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/508724/" ]
Just to say, I ran into a similar error today and it's because Django 1.5 requires the `ALLOWED_HOSTS` parameter in the settings. You simply need to place this row to make it work ;) ``` ... ALLOWED_HOSTS = '*' ... ``` However, **be aware** that you need to set this parameter properly according to your actual host(s) (<https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts>)! > > Values in this list can be fully qualified names (e.g. 'www.example.com'), in which case they will be matched against the request’s Host header exactly (case-insensitive, not including port). A value beginning with a period can be used as a subdomain wildcard: '.example.com' will match example.com, www.example.com, and any other subdomain of example.com. A value of '\*' will match anything; in this case you are responsible to provide your own validation of the Host header (perhaps in a middleware; if so this middleware must be listed first in MIDDLEWARE\_CLASSES). > > > So basically it's better for you to use this type of configuration once you're in production: ``` ... ALLOWED_HOSTS = [ '.yourdomain.com', ] ... ``` thanks to [gertvdijk](https://stackoverflow.com/users/1254292/gertvdijk) for pointing this out
This can also happen if you do not have both a 500.html and 404.html template present. Just the 500 isn't good enough, even for URIs that won't produce a 404!
99,429
A contractor looked at our house and told me that you can't fix a house (with old wiring) that has some outlets that are not grounded. He said that you can go on YouTube and search the internet and it will tell you that you can. He says that the only way to properly fix and ground everything is to do a whole house rewire. Is he correct? If, theoretically, you have an old house that has no ground whatsoever, can you run a grounding wire from the panel to all of the outlets to fix this? **updated** We have BX/AC wiring. And also apparently we have "...old-style AC (BX) with cloth insulated wires in a paper overall wrap under the spiral armor (no bonding tape)" Courtesy of @ThreePhaseEel.
2016/09/17
[ "https://diy.stackexchange.com/questions/99429", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/672/" ]
It's perfectly legal to run JUST a ground wire to retrofit old work. You do not need to also pull all the conductors. This is legal as of NEC 2014, so if your region hasn't adopted it yet, just wait. People who say "might as well pull all new conductors" do not fully understand what the new rule permits. Retrofit grounds do not need to follow the same path as the conductors. What's more, you can borrow/share grounds from one circuit to another as long as they all terminate back at the same panel, and are of large enough size. That is **much** easier than pulling all new homeruns! For instance you can run a 10 AWG ground to a clothes dryer, and any nearby 20A outlet can simply ground to that, etc. etc. It is also both legal and safe to put GFCI protection on ungrounded receptacles or circuits. GFCI protection is safer than a ground, although not as awesome for surge suppressors and radios.
A ground for an outlet,is not ground for the service.Ground for a 3 prong outlet must return to the ground bar or neutral bar in the sub panel.A ground rod has nothing to do with it .That is for lightning protection to the service, and there should only be one ground rod by the meter in a normal residential installation.The PG&E neutral is attached to the neutral bar & ground bar & rod at the service entrance main panel,and then outlet grounds and neutrals are separated at any additional sub panels installed to prevent objectionable neutral current from flowing on metal surface raceways.Service entrance ground rod,& outlet safty grounds are 2 different animals.I reccomend Mike Holts couarses on grounding and bonding for clarity.
309,633
One can define the fundamental concepts of probability theory (such as a probability measure, random variable, etc) in a purely axiomatic manner. However, when we teach probability, we start off with the notion of an "experiment", a concept it seems to me which is something akin to pornography: difficult to define, but you tend to know it when you see it. So I am curious if there is a general definition of an experiment (or if it something really best regarded more as an explanatory construct). To try to define an experiment as a type of function seems difficult to me b/c it would require the notion of a "random function" of some type. Thanks, Jack
2013/02/20
[ "https://math.stackexchange.com/questions/309633", "https://math.stackexchange.com", "https://math.stackexchange.com/users/62659/" ]
I like the way it is defined in [Mathematical Statistics](http://books.google.com/books?id=9QHcJ8WQQ5UC) By Wiebe R. Pestman: "A probability experiment is an experiment which, when repeated under the same conditions, does not necessarily give the same results" [This](http://www.futureaccountant.com/probability/study-notes/trial-result-event-outcome.php) is useful as well.
While reading Grimmett & Welsh book, I found that an experiment is > > Any procedure whose consequences are not predetermined. > > > This is quite a restrictive definition in my opinion, because it excludes "deterministic" experiments where we can determine the final result 100% precision (because there is actually only one possible result). So to me, it the following definition given by Wikipedia seems more precise: > > Any procedure that is infinitely repeatable and whose outcomes are well-defined > > > This seems fine, but it doesn't seem tremendously mathematical. So my guess is that the definition above is correct, and that is the definition used to define a sample space, outcomes, events, event space, probability measure, and so on. However, once we've defined all those mathematical structures, we can go back and say: actually, an experiment can easily be represented by a probability space $(\Omega, \Sigma, \mathbb{P})$. This could be seen as a circular definition, but if you use the word "represented" instead of "defined" then you should be fine. I just wrote an article (which I will extend soon, it's still under construction) in my website [SimpleAI](http://simpleai.it/en/learn/mathematics/probability/42-probabilistic-experiment) [![experiment_circular_definition](https://i.stack.imgur.com/9YU7z.png)](https://i.stack.imgur.com/9YU7z.png)
40,150,192
I have to update multiple rows in a table in a MySQL db, where the condition to find the rows to be updated are in the same table. For instance, I have a table called "cdrs". There is a column in the table called "tf", that is the one I have to update. The column that has the condition to update or not the row is "calltype". "recordId" is the key for that table. The query I am using is this one: ``` UPDATE cdrs SET tf = 1 WHERE recordId in (SELECT recordId from cdrs WHERE calltype = 11); ``` But with this query, I get the following error: > > Error Code: 1093. You can't specify target table 'cdrs' for update in > FROM clause. > > > I searched here and, to be honest, found many posts on this issue but all of them deal with this issue when the same table is in the SET clause, not the WHERE. For instance, I found this post: [MySQL Error 1093 - Can't specify target table for update in FROM clause](https://stackoverflow.com/questions/45494/mysql-error-1093-cant-specify-target-table-for-update-in-from-clause) I tried to use that idea but no success. Does anyone had the same problem and found a solution? I appreciate any help in solving this issue. Thank you very much, Joao Paulo
2016/10/20
[ "https://Stackoverflow.com/questions/40150192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7045849/" ]
You can do simple request : ``` UPDATE cdrs SET tf = 1 WHERE calltype = 11; ```
It is as simple as `UPDATE cdrs SET tf = 1 WHERE calltype = 11;`
5,955,421
Say there are 5 records from the query, how do I get the top 1 records? This is my current code. ``` public Application GetByUserIdAndVersion(int userId, string version) { VettingDataContext dc = new VettingDataContext(_connString); return (from a in dc.Applications where a.UserId == userId && a.chr_Version == version select a).SingleOrDefault<Application>(); } ```
2011/05/10
[ "https://Stackoverflow.com/questions/5955421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/695101/" ]
Just use `FirstOrDefault()` instead: ``` return (from a in dc.Applications where a.UserId == userId && a.chr_Version == version select a).FirstOrDefault<Application>(); ``` `SingleOrDefault()` will throw an exception if there is more than one record, `FirstOrDefault()` will just take the first one. Also you shouldn't have to cast to `Application` - your record already is of type `Application`.
For the first record you can try: ``` return (from a in dc.Applications where a.UserId == userId && a.chr_Version == version select a).FirstOrDefault(); ``` For the first N use: ``` return (from a in dc.Applications where a.UserId == userId && a.chr_Version == version select a).Take(N); ```
37,299
When Joffrey becomes king, he seems to give equal weight to both the Lannister and Baratheon sigils. Why is this? Robb Stark doesn't consider himself a Tully. It's almost as if Joffrey himself knows he's not a Baratheon.
2013/06/24
[ "https://scifi.stackexchange.com/questions/37299", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/15454/" ]
Three people were flying the stag. Stannis changed his as well. Not sure how Renly the guy with the weakest claim wound up with the old school stag though. The lion was probably added as a PR move to remind people where the most powerful house stood.
The reason why is because Joffrey is of House Baratheon of King's Landing. Stannis flies the banner of House Baratheon of Dragonstone because Robert installed him there and made him Lord of Dragonstone, thus creating a cadet branch of House Baratheon. His banner and sigil is a stag surrounded by a heart of fire, appropriate for a follower of R'hllor. Renly thus becomes the Lord of Storm's End, which has also been relegated to being a cadet house, and continues to fly the traditional banner and sigil of House Baratheon of Storm's End. Thus the reason why Joffrey changes his banner and sigil is to distinguish his house, House Baratheon of King's Landing, which represents the union of House Lannister and House Baratheon, from the cadet Baratheon houses. Robert most likely maintained his old sigil as he felt he was from Storm's End. However, given Joffrey's pride and arrogance, it would make sense for him to adopt a new sigil and banner for himself, as the first heir of House Baratheon of King's Landing to have been born in King's landing. He views himself as the culmination of both house's, evidenced by his mockery of Tywin's "hiding under Casterly Rock" and his general disdain for Renly and Stannis. During the War of the Five Kings, this new banner and sigil served to both distinguish himself from the other claimants of the Throne, Renly and Stannis, as well as to remind the kingdom of his Lannister ties.
33,563,736
I have two database tables: ``` subscribers: (ID, name, email_address etc) ``` And subscriptions: (subsc\_id, user\_id, subsc\_start, subsc\_end) My question is how can I get a result of all expired members? I wrote an SQL query: ``` SELECT * FROM subscriptions LEFT JOIN subscribers ON subscriptions.user_id = subscribers.ID WHERE DATE(subscription.subsc_end) < DATE(NOW()) GROUP BY subscriptions.user_id ``` The problem is if a subscriber has an active subscription but also has an earlier expired subscription, then that subscriber will be also added to the expired list. Can anybody help me to write the proper query? Thank you
2015/11/06
[ "https://Stackoverflow.com/questions/33563736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2161265/" ]
So you want to find users whose expiry date is in the past AND their start date is *before* their expiry date - so try this: ``` SELECT * FROM subscriptions LEFT JOIN subscribers ON subscriptions.user_id = subscribers.ID WHERE DATE(subscriptions.subsc_end) < DATE(NOW()) AND DATE(subscriptions.subsc_start) < DATE(subscriptions.subsc_end) GROUP BY subscriptions.user_id HAVING MAX(DATE(subscriptions.subsc_end)) < DATE(NOW()) ```
Probably easiest to do a LEFT OUTER JOIN of non expired subscriptions to subscribers, and check in the WHERE clause that no non expired subscription is found. Saves any aggregate functions. ``` SELECT * FROM subscribers LEFT JOIN subscriptions ON subscriptions.user_id = subscribers.ID AND DATE(subscription.subsc_end) > DATE(NOW()) WHERE subscriptions.subsc_id IS NULL ```
10,511,897
I have an click event that I want to assign to more than class. The reason for this is that I'm using this event on different places in my application, and the buttons you click have different styling in the different places. What I want is something like $('.tag' '.tag2'), which of course don't work. ``` $('.tag').click(function (){ if ($(this).hasClass('clickedTag')){ // code here } else { // and here } }); ```
2012/05/09
[ "https://Stackoverflow.com/questions/10511897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/937624/" ]
Approach #1 ----------- ``` function doSomething(){ if ($(this).hasClass('clickedTag')){ // code here } else { // and here } } $('.tag1').click(doSomething); $('.tag2').click(doSomething); // or, simplifying further $(".tag1, .tag2").click(doSomething); ``` Approach #2 ----------- This will also work: ``` ​$(".tag1, .tag2").click(function(){ alert("clicked"); });​ ``` [Fiddle](http://jsfiddle.net/Afg5s/1/) I prefer a separate function (approach #1) if there is a chance that logic will be reused. See also [How can I select an element with multiple classes?](https://stackoverflow.com/questions/1041344/jquery-multiple-class-selector) for handling multiple classes on the same item.
Have you tried this: ``` function doSomething() { if ($(this).hasClass('clickedTag')){ // code here } else { // and here } } $('.tag1, .tag2').click(doSomething); ```
9,077,055
``` InputStream is = new URL(someUrl).openStream(); long length = is.skip(Long.MAX_VALUE); ``` When I call `is.skip(Long.MAX_VALUE)`, does it download the file before returning the value, or does it actually skip the given number of byte (assume the size is less than `MAX_VALUE`)?
2012/01/31
[ "https://Stackoverflow.com/questions/9077055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1177604/" ]
From the [docs](http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html#skip%28long%29): > > Skips over and discards n bytes of data from the input stream. > > > The skip method may, for a variety of reasons, end up skipping over some smaller number of bytes, possibly 0. If n is negative, an IOException is thrown, even though the skip method of the InputStream superclass does nothing in this case. The actual number of bytes skipped is returned. > > > This method may skip more bytes than are remaining in the backing file. This produces no exception and the number of bytes skipped may include some number of bytes that were beyond the EOF of the backing file. Attempting to read from the stream after skipping past the end will result in -1 indicating the end of the file. > > >
Looking at the implementation of the [JDK6 HTTP client](http://hg.openjdk.java.net/jdk6/jdk6/jdk/file/ef3efe6d9488/src/share/classes/sun/net/www/http/), you see no special handling of the `skip` method. That means that (by default, assuming you don't do something elaborate like configuring a range header on the request) you'll be reading all those bytes one chunk at a time. The chunk size is itself variable (Peter Lawrey makes a good case for it being 1024 bytes) but will be bounded by the MTU at the IP layer, i.e. usually around 1500 bytes. That code as posted will download the whole file. Sorry.
11,875,590
Can anybody help me in solving this error. I am getting Invalid response from paypal sandbox. My sandbox account is verified, IPN is on at my account, I have also set notify url in my sandbox account. Here is my button code ``` <form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_xclick"> <input type="hidden" name="business" value="myverifiedpaypalemail@gmail.com"> <input type="hidden" name="item_name" value="My Business"> <input type="hidden" name="item_number" value="10101"> <input type="hidden" name="amount" value="101.35"> <input type="hidden" name="currency_code" value="USD"> <input type="hidden" name="lc" value="US"> <input type="hidden" name="bn" value="PP-BuyNowBF"> <input type="image" src="http://www.mydomain.com/wp-content/themes/MiniMeCity/images/paypalbutton.jpg" border="0" name="submit" alt="Make payments with PayPal - it's fast, free and secure!"> <img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1"> <input type="hidden" name="return" value="http://www.mydomain.com/payment-confirmation/"> <input type="hidden" name="cancel_return" value="http://www.mydomain.com/"> <input type="hidden" name="rm" value="2"> <input type="hidden" name="notify_url" value="http://www.mydomain.com/paypalipn.php" /> </form> ``` and here is my IPN code : <http://codepad.org/Xu0rhDBY>
2012/08/09
[ "https://Stackoverflow.com/questions/11875590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1076123/" ]
Inside your IPN, you are opening a socket to www.paypal.com instead of www.sandbox.paypal.com
<https://www.paypal-community.com/t5/Selling-on-your-website/IPN-response-problem/m-p/521312#M2445> I recently experienced this problem, going from a code base that hadn't changed and was working correctly on the Paypal sandbox. If you can provide more information was to what is occuring, i can point you more in the right direction. I'd suggest doing what's been talked about in that post first. Which is simply adding the new header. $header .= "Host: www.sandbox.paypal.com\r\n"; Just be aware not to have this header on a production system. Hope this helps. If it doesn't resolve your issue, use var\_dump line 39 to see what the responses are. I've posted a more detail response in a different topic which outlines debugging in an easier manner : [Paypal IPN Integration into PHP](https://stackoverflow.com/questions/11875053/paypal-ipn-integration-into-php/11875535#11875535)
13,363,398
I was wondering whether exists any dashlet which allows you to explore a site's document library. As far as I know doesn't exist such dashlet out of the box, there only exists the "Site Content" dashlet but it is slightly limited. I have been searching around and "googling" and I found these useful resources that could be useful as a starting point if I had to create my own: <http://ecmarchitect.com/archives/2012/05/08/1592> <http://code.google.com/p/fme-alfresco-extensions/wiki/GalleryPlusDashlet2> Do somebody know more dashlets/resources targeting this issue? Any suggestion? As a temporary solution, I'm also thinking in the possibility of taking advantage of the "Web View" dashlet, by configuring in it such URL that retrieves the ***documentlist*** region/component in the ***documentlibrary*** page. For example:, **share/page/components/documentlibrary/documentlist** or **share/page/site/{site}/documentlibrary?region=documentlist**. Maybe it is crazy or what I'm saying doesn't make any sense, but it is just an idea. Another idea that have just came to my mind is the option of creating a custom Surf/Share page which includes the component/webscript that implements the explorer of the document library, specifically the documentlist component. Then configure the "Web View" dashlet giving the URL that points to the custom page created. Would it make sense? Thanks in advance.
2012/11/13
[ "https://Stackoverflow.com/questions/13363398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1514315/" ]
You are going to see a couple of site visualization and navigation dashlets on Alfresco Visualization Tools available on <https://github.com/bhagyas/alfresco-visualization-tools>. The project is still at it's initial phase, but you will find interesting snippets of code used to retrieve the document library content trees within the dashlets. The project was presented by me at Alfresco DevCon in Berlin just a week ago to bring interactive navigation and content analytics. If interested, you can find the slides at the lightening talk slides in the DevCon 2012 site at Alfresco. Cheers! =)
There is a document-liberary-display dashlet available in the alfresco add-on list which can be used to show all the documents from document-library on site-dashlet. <http://addons.alfresco.com/addons/document-library-display-dashlet>
6,161
I am unable to autotune on 21Mhz as the SWR is more than 1:3 which is out side the range of the radio. I would like use it only for digital TX with a max. power of 50 watts. Any solution/s?
2016/05/07
[ "https://ham.stackexchange.com/questions/6161", "https://ham.stackexchange.com", "https://ham.stackexchange.com/users/6641/" ]
The traditional "No balun" G5RV design is famous (infamous, more like) for these sorts of quirks, primarily because the claim that it behaves in various different (and universally desirable) ways at different frequencies is a crock. In reality, it has two modes, a balanced dipole when used on a frequency where SWR (and in theory, common mode current) is low (30 and 17m on the Lite), and a sort of Frankenstein vertical (driven by common mode) and dipole (driven by the differential mode) everywhere else. That second mode is unpredictable at best, because the coax shield is just hanging there begging to act as part of the antenna, and the ladderline likes to radiate to varying degrees depending on frequency and severity of imbalance. In your case, a quick model suggests you've got several hundred ohms of inductive reactance at the junction between the coax and ladderline at 21MHz, which may be more than your tuner can handle. The best way to handle this would be to extend the ladder line to the shack window, or as close as you can get it, place a good quality 2 core 4:1 current balun there, and then run a short length of low loss coax like RG-213 in to the tuner. This should drastically reduce your feedline losses, and generally results in a much broader useful bandwidth overall. In your case, if this model is even remotely close to accurate, you're likely losing more than 50% of your power in the coax run, even if you're using just 50 feet of RG-8X in the current setup. The "band aid" solution would be to place a bit of capacitive reactance across the ladderline to counteract the inductive reactance. I'm not sure exactly how much capacitance you might need, as that's going to be highly situation dependent. I would recommend using a variable capacitor at low power to determine how much is necessary to get below 4:1 or so, and then swap the variable capacitor out for a fixed capacitor with at least a 1kV voltage rating when you want to run 15 meters, and remove it otherwise. A final (and maybe optimal) solution, but requiring substantial financial investment, would be to place a remote tuner like an Icom AH-4 or LDG RT-100 at the point where the ladderline from the G5RV ends, and run coax to the tuner. This is probably the best of all worlds, keeping coax loss low, giving maximum bandwidth, making it easy to isolate the coax from the antenna, and eliminating the frustrations of running ladderline long distances.
The usual solution to autotuner problems is to change the length of the coax. Try adding a half wavelength of coax, approx 5 m, to the antenna feed, and see if that helps. You could also try 2.5 or 7.5 m, anything about that long will have some impact. Although the VSWR won't change much if you add a bit of cable, the impedance will change completely, from inductive to capacitive, from high to low, or vice versa. You will likely move from a spot where the tuner can't cope, to a better spot where it can match the antenna. While you are at it, do you at least have a coil of coax or some other choke at the base of the G5RV? If not, it might help all bands to have 5 turns about 20-30 cm in diameter, right at the end of the ladder line.
35,632,928
I need my buttons to have several pieces of text on them in a specific layout, so I'm trying to put a grid on my button to organize the info. My problem is that while I can get the unmodified button to appear, the grid never appears in or on top of it. Here's the .xaml code: ``` <!-- ...other code up above... --> <ItemsControl x:Name="btnList"> <ItemsControl.ItemTemplate> <DataTemplate> <Grid Background="Green"> <Grid.RowDefinitions> <RowDefinition Height="3*" /> <RowDefinition Height="2*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="1*" /> <ColumnDefinition Width="1*" /> <ColumnDefinition Width="1*" /> </Grid.ColumnDefinitions> <TextBlock Grid.ColumnSpan="3" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Center" Margin="15" Text="Test Text 1" /> <TextBlock Grid.Row="1" Grid.Column="0" HorizontalAlignment="Center" Text="Test Text 2" /> <TextBlock Grid.Row="1" Grid.Column="1" HorizontalAlignment="Center" Text="Test Text 3" /> <TextBlock Grid.Row="1" Grid.Column="2" HorizontalAlignment="Center" Text="Test Text 4" /> </Grid> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> ``` Here's the associated .xaml.cs code: ``` public THINGSelectFlyout() { this.InitializeComponent(); foreach (XTHING_IndexItem indexItem in DataStore.Instance.THINGsFoundOnTap) { Button button = new Button() { Name = indexItem.cGuid.ToString("N"), Content = indexItem.cName, Style = Application.Current.Resources["BigButtons"] as Style }; button.Click += THINGButton_Click; btnList.Items.Add(button); } ``` When run like this the buttons appear (with the default background color, blue) and have the content that's given to them in the .xaml.c file. As a side note, I am modifying someone else's code and long story short I cannot move the entire button construction into the .xaml file; too many other things expect it to be there.
2016/02/25
[ "https://Stackoverflow.com/questions/35632928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4224414/" ]
You must unhide the sheet before copying it (at least to a new workbook as lturner notes) - you can then re-hide it ``` Dim shtTemplate as Worksheet, sheetWasHidden As Boolean Set shtTemplate = ThisWorkbook.Sheets(Machine) 'handle the case where the sheet to be copied is Hidden If shtTemplate.Visible = xlSheetHidden Then shtTemplate.Visible = xlSheetVisible sheetWasHidden = True End If shtTemplate.Copy If sheetWasHidden Then shtTemplate.Visible = xlSheetHidden 're-hide if needed ```
When you have the worksheet object and use the `Copy` method, Excel seems to be making assumptions (or not) about where you want to put the new sheet. I pretty much always use the `After` option to define where the new sheet should go. ``` Option Explicit Sub test() Dim wsCopy As Worksheet Set wsCopy = ActiveSheet wsCopy.Copy After:=wsCopy End Sub ```
37,219,424
I can only seem to find answers about last/first element in a list or that you can get a specific item etc. Lets say I have a list of 100 elements, and I want to return the last 40 elements. How do I do that? I tried doing this but it gave me one element.. ``` Post last40posts = posts.get(posts.size() -40); ```
2016/05/13
[ "https://Stackoverflow.com/questions/37219424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6208277/" ]
Do use the method sub list ``` List<Post> myLastPosts = posts.subList(posts.size()-40, posts.size()); ```
(To complete Ankit Malpani answer) If `40` is provided by our lovely users, then you will have to restrict it to the list size: ``` posts.subList(posts.size()-Math.min(posts.size(),40), posts.size()) ``` Another way to show it: ``` @Test public void should_extract_last_n_entries() { List<String> myList = Arrays.asList("0","1","2","3","4"); int myListSize = myList.size(); log.info(myList.subList(myListSize,myListSize).toString()); // output : [] log.info(myList.subList(myListSize-2,myListSize).toString()); // output : [3, 4] log.info(myList.subList(myListSize-5,myListSize).toString()); // output : [0, 1, 2, 3, 4] int lastNEntries = 50; // now use user provided int log.info(myList.subList(myListSize-Math.min(myListSize,lastNEntries),myListSize).toString()); // output : [0, 1, 2, 3, 4] // log.info(myList.subList(myListSize-lastNEntries,myListSize).toString()); // ouch IndexOutOfBoundsException: fromIndex = -45 } ```
49,918,511
I have a dataframe like this, ``` col1 1 2 3 2 2 3 1 1 2 3 1 1 3 3 1 1 3 ``` When I compute `print df['col1'].value_counts(bins=2)` It gives me, ``` (0.997, 2.0] 11 (2.0, 3.0] 6 Name: col1, dtype: int64 ``` Result is good. But in index it gives mixed of `(`&`]`. Why it behaves like this. Because I want to preserve index as a new column like below. `temp=pd.DataFrame(df['col1'].value_counts(bins=2).reset_index()).rename(columns={'index':'bin'})` Is there any way to keep same parenthesis either '(' or ']'. or should I clean (replace) that by another line of code? Please help to understand the problem. Thanks in advance.
2018/04/19
[ "https://Stackoverflow.com/questions/49918511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4684861/" ]
Now you can find the documentation here: <https://angular.io/api/forms/FormControlName#use-with-ngmodel-is-deprecated> So you have 3 options: 1. use Reactive forms 2. use Template driven forms 3. silence warning (not recommended) ``` <!-- language: lang-ts --> imports: [ ReactiveFormsModule.withConfig({warnOnNgModelWithFormControl: 'never'}); ] ```
add ``` [ngModelOptions]="{standalone: true}" ``` You can read more from angular website <https://angular.io/api/forms/NgModel>
29,956,610
I am using vagrant to set up my enviroment, when I use sudo npm update, I get this error. ``` npm ERR! Linux 3.13.0-49-generic npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "update" npm ERR! node v0.12.2 npm ERR! npm v2.7.4 npm ERR! path ../mime/cli.js npm ERR! code EPROTO npm ERR! errno -71 npm ERR! EPROTO, symlink '../mime/cli.js' npm ERR! npm ERR! If you need help, you may report this error at: npm ERR! <https://github.com/npm/npm/issues> npm ERR! Linux 3.13.0-49-generic npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "update" npm ERR! node v0.12.2 npm ERR! npm v2.7.4 npm ERR! path npm-debug.log.7dead0fa1a1d874805ab6e477bd46e0e npm ERR! code ETXTBSY npm ERR! errno -26 npm ERR! ETXTBSY, rename 'npm-debug.log.7dead0fa1a1d874805ab6e477bd46e0e' npm ERR! npm ERR! If you need help, you may report this error at: npm ERR! <https://github.com/npm/npm/issues> npm ERR! Please include the following file with any support request: npm ERR! /vagrant/myapp/npm-debug.log ``` NOTE1: I am using trusty32 box also I am using node 0.12, npm 2.7.4 and mongodb 2.6. NOTE2: I can not install mongoose and the default express-generator npm modules found in the package.json UPDATE1: Npm error when i try "sudo npm install mongoose -save" ``` npm ERR! tar.unpack untar error /home/vagrant/.npm/wrappy/1.0.1/package.tgz npm ERR! tar.unpack untar error /home/vagrant/.npm/brace-expansion/1.1.0/package .tgz npm ERR! Linux 3.13.0-49-generic npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install" "mongoose" npm ERR! node v0.12.2 npm ERR! npm v2.7.4 npm ERR! path /vagrant/myapp/node_modules/mongoose/node_modules/mongodb/node_mod ules/mongodb-core/node_modules/bson/node_modules/bson-ext/node_modules/node-pre- gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/tes t/extglob-ending-with-state-char.js npm ERR! code EPERM npm ERR! errno -1 npm ERR! Error: EPERM, open '/vagrant/myapp/node_modules/mongoose/node_modules/m ongodb/node_modules/mongodb-core/node_modules/bson/node_modules/bson-ext/node_mo dules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_module s/minimatch/test/extglob-ending-with-state-char.js' npm ERR! at Error (native) npm ERR! { [Error: EPERM, open '/vagrant/myapp/node_modules/mongoose/node_modul es/mongodb/node_modules/mongodb-core/node_modules/bson/node_modules/bson-ext/nod e_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_mo dules/minimatch/test/extglob-ending-with-state-char.js'] npm ERR! errno: -1, npm ERR! code: 'EPERM', npm ERR! path: '/vagrant/myapp/node_modules/mongoose/node_modules/mongodb/node _modules/mongodb-core/node_modules/bson/node_modules/bson-ext/node_modules/node- pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch /test/extglob-ending-with-state-char.js' } npm ERR! npm ERR! Please try running this command again as root/Administrator. npm ERR! Linux 3.13.0-49-generic npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install" "mongoose" npm ERR! node v0.12.2 npm ERR! npm v2.7.4 npm ERR! path /vagrant/myapp/node_modules/mongoose/node_modules/mongodb/node_mod ules/mongodb-core/node_modules/bson/node_modules/bson-ext/node_modules/node-pre- gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stre am/lib/_stream_duplex.js npm ERR! code EPERM npm ERR! errno -1 npm ERR! Error: EPERM, open '/vagrant/myapp/node_modules/mongoose/node_modules/m ongodb/node_modules/mongodb-core/node_modules/bson/node_modules/bson-ext/node_mo dules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_module s/readable-stream/lib/_stream_duplex.js' npm ERR! at Error (native) npm ERR! { [Error: EPERM, open '/vagrant/myapp/node_modules/mongoose/node_modul es/mongodb/node_modules/mongodb-core/node_modules/bson/node_modules/bson-ext/nod e_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_mo dules/readable-stream/lib/_stream_duplex.js'] npm ERR! errno: -1, npm ERR! code: 'EPERM', npm ERR! path: '/vagrant/myapp/node_modules/mongoose/node_modules/mongodb/node _modules/mongodb-core/node_modules/bson/node_modules/bson-ext/node_modules/node- pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable- stream/lib/_stream_duplex.js' } npm ERR! npm ERR! Please try running this command again as root/Administrator. npm ERR! Linux 3.13.0-49-generic npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install" "mongoose" npm ERR! node v0.12.2 npm ERR! npm v2.7.4 npm ERR! path npm-debug.log.547bda60a6af6dbfaba7873fdc566e0c npm ERR! code ETXTBSY npm ERR! errno -26 npm ERR! ETXTBSY, rename 'npm-debug.log.547bda60a6af6dbfaba7873fdc566e0c' npm ERR! npm ERR! If you need help, you may report this error at: npm ERR! <https://github.com/npm/npm/issues> npm ERR! Linux 3.13.0-49-generic npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install" "mongoose" npm ERR! node v0.12.2 npm ERR! npm v2.7.4 npm ERR! path /vagrant/myapp/node_modules/mongoose/node_modules/mongodb/node_mod ules/mongodb-core/node_modules/bson/node_modules/bson-ext/node_modules/node-pre- gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-strea m/lib/delayed_stream.js npm ERR! code EPERM npm ERR! errno -1 npm ERR! Error: EPERM, open '/vagrant/myapp/node_modules/mongoose/node_modules/m ongodb/node_modules/mongodb-core/node_modules/bson/node_modules/bson-ext/node_mo dules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_module s/delayed-stream/lib/delayed_stream.js' npm ERR! at Error (native) npm ERR! { [Error: EPERM, open '/vagrant/myapp/node_modules/mongoose/node_modul es/mongodb/node_modules/mongodb-core/node_modules/bson/node_modules/bson-ext/nod e_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_mo dules/delayed-stream/lib/delayed_stream.js'] npm ERR! errno: -1, npm ERR! code: 'EPERM', npm ERR! path: '/vagrant/myapp/node_modules/mongoose/node_modules/mongodb/node _modules/mongodb-core/node_modules/bson/node_modules/bson-ext/node_modules/node- pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-s tream/lib/delayed_stream.js' } npm ERR! npm ERR! Please try running this command again as root/Administrator. npm ERR! tar.unpack untar error /home/vagrant/.npm/lodash._basetostring/3.0.0/pa ckage.tgz npm ERR! tar.unpack untar error /home/vagrant/.npm/lodash._createpadding/3.6.0/p ackage.tgz npm ERR! tar.unpack untar error /home/vagrant/.npm/lodash._createpadding/3.6.0/p ackage.tgz npm ERR! tar.unpack untar error /home/vagrant/.npm/lodash._createpadding/3.6.0/p ackage.tgz npm ERR! tar.unpack untar error /home/vagrant/.npm/lodash._basetostring/3.0.0/pa ckage.tgz npm ERR! tar.unpack untar error /home/vagrant/.npm/lodash._basetostring/3.0.0/pa ckage.tgz npm ERR! Linux 3.13.0-49-generic npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install" "mongoose" npm ERR! node v0.12.2 npm ERR! npm v2.7.4 npm ERR! path /vagrant/myapp/node_modules/mongoose/node_modules/mongodb/node_mod ules/mongodb-core/node_modules/bson/node_modules/bson-ext/node_modules/node-pre- gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-vali d/test/json-schema.js npm ERR! code EPERM npm ERR! errno -1 npm ERR! Error: EPERM, open '/vagrant/myapp/node_modules/mongoose/node_modules/m ongodb/node_modules/mongodb-core/node_modules/bson/node_modules/bson-ext/node_mo dules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/ is-my-json-valid/test/json-schema.js' npm ERR! at Error (native) npm ERR! { [Error: EPERM, open '/vagrant/myapp/node_modules/mongoose/node_modul es/mongodb/node_modules/mongodb-core/node_modules/bson/node_modules/bson-ext/nod e_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modu les/is-my-json-valid/test/json-schema.js'] npm ERR! errno: -1, npm ERR! code: 'EPERM', npm ERR! path: '/vagrant/myapp/node_modules/mongoose/node_modules/mongodb/node _modules/mongodb-core/node_modules/bson/node_modules/bson-ext/node_modules/node- pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json- valid/test/json-schema.js' } npm ERR! npm ERR! Please try running this command again as root/Administrator. npm ERR! Linux 3.13.0-49-generic npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install" "mongoose" npm ERR! node v0.12.2 npm ERR! npm v2.7.4 npm ERR! path /vagrant/myapp/node_modules/mongoose/node_modules/mongodb/node_mod ules/mongodb-core/node_modules/bson/node_modules/bson-ext/node_modules/node-pre- gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/bro wser/bluebird.min.js npm ERR! code EPERM npm ERR! errno -1 npm ERR! Error: EPERM, open '/vagrant/myapp/node_modules/mongoose/node_modules/m ongodb/node_modules/mongodb-core/node_modules/bson/node_modules/bson-ext/node_mo dules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/ bluebird/js/browser/bluebird.min.js' npm ERR! at Error (native) npm ERR! { [Error: EPERM, open '/vagrant/myapp/node_modules/mongoose/node_modul es/mongodb/node_modules/mongodb-core/node_modules/bson/node_modules/bson-ext/nod e_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modu les/bluebird/js/browser/bluebird.min.js'] npm ERR! errno: -1, npm ERR! code: 'EPERM', npm ERR! path: '/vagrant/myapp/node_modules/mongoose/node_modules/mongodb/node _modules/mongodb-core/node_modules/bson/node_modules/bson-ext/node_modules/node- pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js /browser/bluebird.min.js' } npm ERR! npm ERR! Please try running this command again as root/Administrator. npm ERR! tar.unpack untar error /home/vagrant/.npm/ansi-styles/2.0.1/package.tgz npm ERR! tar.unpack untar error /home/vagrant/.npm/has-ansi/1.0.3/package.tgz npm ERR! tar.unpack untar error /home/vagrant/.npm/strip-ansi/2.0.1/package.tgz npm ERR! tar.unpack untar error /home/vagrant/.npm/escape-string-regexp/1.0.3/pa ckage.tgz npm ERR! tar.unpack untar error /home/vagrant/.npm/supports-color/1.3.1/package. tgz npm ERR! tar.unpack untar error /home/vagrant/.npm/graceful-readlink/1.0.1/packa ge.tgz npm ERR! Please include the following file with any support request: npm ERR! /vagrant/myapp/npm-debug.log ``` UPDATE2: Switching to nvm works better with npm update but i cant not install mongoose i got the same error UPDATE3: I think the problem is because the path
2015/04/29
[ "https://Stackoverflow.com/questions/29956610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4434843/" ]
There are two problems with using sudo with `npm` 1. 99 problems like this. 2. It's a [security issue](https://news.ycombinator.com/item?id=8947493). The best solution is to use a node version manager. I use [nvm](https://github.com/creationix/nvm). Another called [n](https://www.npmjs.com/package/n) exists as well. It felt like a couple steps "backwards" and I resisted it for a week or two, but making the switch was worth it. NOTE: You should uninstall your "sudo" version of node.js, then install nvm as described on the github page.
You are using an older version of NPM, the current latest version is 2.8.4 you are currently on 2.7.4. The release notes for 2.7.5 mention an issue with symbolic links that was fixed. Updating NPM should fix this, run: ``` sudo npm install npm -g ```
50,086,247
So, as one of my first projects, I tried to do a little lottery draw site, but I can't display the `winPercentage` variable from the `script.js` on the site. It just stays empty. Why? The `script.js` part: ``` var winPercentage = winCount / gameCount * 100; document.getElementById("winPercentageID").innerHTML = winPercentage; ``` The HTML part: ``` Your Win Percentage is : <br> <span id = "winPercentageId"></span> ```
2018/04/29
[ "https://Stackoverflow.com/questions/50086247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Your id `winPercentageID` does not match `winPercentageId` (uppercase "ID" vs "Id")
In case if you want to do it with jQuery. ``` var winPercentage = winCount / gameCount * 100; $("#winPercentageID").html(winPercentage) ```