text
stringlengths
70
452k
dataset
stringclasses
2 values
Question on weights and minimal degree Edit: question has been changed from 'lexicographic' (cf. "D K"'s answer below) to 'degree' minimality. Let $x_1,x_2,x_3$ be indeterminates. Fix an integer $k> 3$. Consider the set $M$ of all monomials of the form $x_1^{i_1}.x_2^{i_2}.x_3^{i_3}$ where each $i_j\in \mathbb{N}$ with $i_j\geq 1$ and $i_1+i_2+i_3 = k$. Fix an arbitrary $F\in M$ and write $F = x_1^{a}.x_2^{b}.x_3^{c}$. Question When does there exist a triple $(w_1, w_2, w_3)$, with each $w_i\in \mathbb{N}$ and $w_i\geq 1$, such that $$a.w_1 + b.w_2 + c.w_3 < i_1.w_1 + i_2.w_2 + i_3.w_3, \forall G = x_1^{i_1}.x_2^{i_2}.x_3^{i_3}\in M \;\text{with} \; G\neq F ?$$ In the exponential case, same question replaced by $a^{w_1}+ b^{w_2}+ c^{w_3} < i_1^{w_1}+i_2^{w_2}+ i_3^{w_3}$. Positive example in additive case: $k = 4$ on three indeterminates. Then if $F$ corresponds to the element of $B_4$ with exponents $(2,1,1)$, then for any $w_2, w_3>1$, $w = (1,w_2,w_3)$ has the desired property. Sometimes this question has a negative answer: e.g. k=4 on only two indeterminates. if we take F to correspond to the element in $B_4$ with exponents $(2,2)$ then we cannot achieve both $2w_1 + 2w_2 < w_1 + 3 w_2$ and $2w_1+2w_2 < 3w_1+w_2$. Same question for $n$-variables $x_1,\ldots, x_n$ and $k > n.$ Apologies if this question has been answered; (general and specific) references also appreciated. I haven't completely checked, but examples suggest that $F$ must be, up to reordering the $x_i$'s, the minimal lexicographic element in $B_k$ (in general, you can also replace $B_k$ with a subset of $B_k$, and then take the minimal element of this new set) Example: take $k=5$. Then $(a,b,c)$ must have one of $a,b,$ or $c$ equal to $3$, i.e. no exponent of 2 is allowed in $F$ for a positive answer. Explicitly, for the affirmative: we can assume without loss of generality that $F = xyz^3$. Then we get that $w_3 < w_1$, $w_3 < w_2$ and $2w_3 < w_1+w_2$, which is infinitely possible. Take, e.g. $w = (2,2,1)$. On the other hand if $F = xy^2z^2$ there is no solution since we must satisfy $w_3 < w_2$ and $w_2 < w_3$. ok, I think that's correct in the general case: for $n\geq 2, k>n$, then if $F$ is, up to reordering, the minimal element of $B_k$ in the lexicographic ordering, then there are infinitely many $w's$ for which you have a positive answer to your question. It's probably true that this condition is also sufficient, i.e. if $F$ is not minimal, then there are no solutions. It is clearly not the case, as the optimal choice for $a,b,c$ once the weights are fixed is always to put $k$ on the minimal weight and $0$ on the others. You can see that if you start from a different configuration, the total weight will decrease when you move to this one, as you transfer "mass" from "heavy" to "light". So if $a,b,c$ are not $k,0,0$ (in any order), then it cannot be a minimal choice, no matter what the weights are. This is still true in the exponentiation setting. thank you, though i have now changed the question. and yes, you are completely correct that in the original (and wrong) version of the question, we won't get a desired lexicographic ordering unless the chosen $f$ was already the minimal wrt lex. ordering. as a very easy example of positivity for the new question: take $k=4$ for three indeterminates. Then the exponents of the three elements of $B_k$ have coordinates $(2,1,1), (1,2,1),$ and $(1,1,2)$. Say we take $F\in B_k$ to be the element with $(2,1,1)$. Then in fact there are infinitely-many good $w's$, namely $w = (1, w_2, w_3)$ where $w_2,w_3>1$
common-pile/stackexchange_filtered
OCaml - Access Derived Functions from Another Module If a record is defined in a module in lib and it contains a deriving annotation that generates functions, how can those functions be used in another module? For example, the yaml/ppx_deriving_yaml opam module contains a [@@deriving yaml]. If [@@deriving yaml] is applied to a record, functions are generated, such as {record_name}_to_yaml, which converts a record to a Yaml data structure. Example: When [@@deriving yaml] is added to the book record, when compiled, there will be several functions generated, one being book_to_yaml. (* ./lib/books.ml *) type book = { title: string; authors: string list } [@@deriving yaml] But if you try and access book_to_yaml from outside the Books module, it is unavailable. Why is that function unavailable? How is it accessed? (* ./bin/main.ml *) let () = let (b: book) = { title = "Cryptonomicon"; authors = [ "Neal Stephenson" ] } in Yaml.pp Stdlib.Format.std_formatter (book_to_yaml b); Error ^^^^^^^^^^^^ My assumption is that this is something specific to how deriving and modules work. This doesn't answer why, but is one way I found around the issue. Lets assume the library is named 'bookstore': (* ./lib/dune *) (library (name bookstore) (libraries yaml) (preprocess (pps ppx_deriving_yaml))) A function can be defined in the module with the record, which directly exposes the generated function. In this case book_to_yaml will be exposed with a function called convert_book_to_yaml. type book = { title: string; authors: string list } [@@deriving yaml] let convert_book_to_yaml = book_to_yaml Now you can access convert_book_to_yaml by either adding open Bookstore.Books or directly with the full namespace Bookstore.Books.convert_book_to_yaml. (* ./bin/main.ml *) let () = let (b: Bookstore.Books.book) = { title = "Cryptonomicon"; authors = [ "Neal Stephenson" ] } in Yaml.pp Stdlib.Format.std_formatter (Bookstore.Books.convert_book_to_yaml b);
common-pile/stackexchange_filtered
Display Full Date in React Using Words in DatePicker I have a very simple problem. I wanted to display the full date words, something like Nov 22th 2020. Right now, i can only display the Month and the Date Pls check my codesandbox CLICK HERE <MuiPickersUtilsProvider utils={DateFnsUtils}> <DatePicker error={false} helperText={null} autoOk fullWidth inputVariant="outlined" value={selectedDate} onChange={handleDateChange} variant="outlined" /> </MuiPickersUtilsProvider> All you need is add prop format to picker, according to your example, you need format="MMM do yyyy". Here you can find more options
common-pile/stackexchange_filtered
JSR 283 Query and Seaching I am in the early stage of a tagged document repository using Apache Jackrabbit. My initial exploration was with JSR 170. Upon learning that JSR 283 deprecates things like XPath, I began to look more at JSR 283. My (still quite ignorant) impression is that JSR 283 moved to a more SQL-centric API, although the underlying node structure remains the same. For my application, I would like to have scored tag searches and be able to search tags using regular expressions (although scoring becomes more complex in that case). My questions are these: Should I pursue using non-deprecated API features in JSR 283 for this project? If so, where (or how) would I find information on JSR 283 API for such an application? After searching for more information on JSR 283, I've concluded that the best (and perhaps only) source for what I need is the JSR 283 reference implementation available at Day Software. http://www.day.com/day/en/products/jcr/jsr-283.html http://www.day.com/specs/jcr/2.0/6_Query.html
common-pile/stackexchange_filtered
F#: How do I use Map with a Collection (like Regex Matches)? Soo... F# no longer has IEnumerable.map_with_type... which is the way people were mapping over collections. How do I do that now? let urlPat = "href\\s*=\\s*(?:(?:\\\"(?<url>[^\\\"]*)\\\")|(?<url>[^\\s]* ))";; let urlRegex = new Regex(urlPat) let matches = urlRegex.Matches(http("http://www.google.com")) let matchToUrl (urlMatch : Match) = urlMatch.Value let urls = List.map matchToUrl matches Thanks! you would write the last line like this: let urls = Seq.map matchToUrl (Seq.cast matches);; And this can be written in a nicer way using pipelining operator: let urls = matches|> Seq.cast |> Seq.map matchToUrl;; F# automatically figures out what is the right target type (because it knows what matchToUrl looks like). This is available only for Seq, so you can use List.of_seq to get the data into a list again. Is Seq.cast what you are looking for? Sounds like it... how would that work? I tried googling but haven't found anything useful. See Tomas' answer. Seq.cast takes an IEnumerable and converts it to IEnumerable (and usually infers the T on your behalf).
common-pile/stackexchange_filtered
Using external DC input to remove DC component from signal using differential-amplifier based circuit I want to use this Fully Differential Amplifier to design an OPAMP stage that is powered by +3.5 and -3.5 V DC power supplies, which will get a single-ended input signal that has AC and DC components. The stage should amplify the signal and feed it to an ADC with a 85 Ω differential load. The design will also get a DC input (External VDC), that I want to use to remove the input signal DC component. What is the value of external VDC? I have done something similar driving an ADC. At power up the device measures its DC level and then applies it to a 12 bit DAC to zero the level. Then it powers up the source device. The advantage here is that you can still measure DC levels and you can cancel out any offset in the amp. AC coupling would work too, but you lose DC and still have the amp offset. It makes for a poor design to pass spectrum that contains noise considering CMRR from DC to GHz without a great effort and broad spectrum experience . Is there a reason to not just use a capacitor to block the DC? Trying to cancel it will involve getting VDC_EX rather precise and having it track any variations in Vin_DC. Using a blocking capacitor should allow for a wider input signal range, the amplifier input range only has to accommodate the peak signal instead of the peak + DC. If you need to cancel the DC without using a cap, one thing you might be able to do is derive VDC_EX from the input signal by using an integrator with a long time constant to extract the DC component which is then used as VDC_EX. This can also be done using the output signal instead of the input. This is sometimes done in audio amplifiers to remove any DC offset in the output. Thanks @GodJihyo, appreciated. I will try look deeper at your suggested solution, but for now, I was interested in certain direction for how to solve it, can you please check my question update? If you are going to go up to 8GHz, capacitive/inductive effects of all you components are going to have a major impact on any circuit operation. As suggested by others, using a DC blocking cap will allow you to focus on these other factors. With a 10MHz lower cutoff, the components can also be selected for minor impact on accuracy.
common-pile/stackexchange_filtered
Binning in python pandas dataframe (not manually setting bins) I have a data frame. i want to bin values and append it to the new column. i can do it with pd.cut. But the thing is that, with pd.cut i set labels and bins manually. But, i want to just set step size (not bin number). i tried also np.linespace, np.arange but there i have to specify the start and end point also bin count. but there can be a dataframe which i would not be able to know the max and min number in dataframe df = pd.DataFrame([10, 10, 23, 42, 51, 33, 52, 42,44, 67, 65, 12, 10, 2, 3, 2, 77, 76],columns=['values']) bins = [0, 10, 20,30, 40, 50, 60, 70] labels = ['0-10', '10-20', '20-30', '30-40', '40-50', '50-60', '60-70'] df['bins'] = pd.cut(df['values'], bins, labels=labels) print (df) values bins 0 10 0-10 1 10 0-10 2 23 20-30 3 42 40-50 4 51 50-60 5 33 30-40 6 52 50-60 7 42 40-50 8 44 40-50 9 67 60-70 10 65 60-70 11 12 10-20 12 10 0-10 13 2 0-10 14 3 0-10 15 2 0-10 16 77 NaN 17 76 NaN Here is my output, i want to get same output but not with manually setting bins and labels p.s. As u see from here if i have the values greater than 70 it will be Nan. So it is also reason why i want to just set step size "10". I can have continues values, so i want it to label is automatically by using steps size 10 I would really aprreciate your helps Thanks!!! Just a slight variation to your code, note that I added a row with value 93 at the end of your df. df = pd.DataFrame([10, 10, 23, 42, 51, 33, 52, 42,44, 67, 65, 12, 10, 2, 3, 2, 77, 76, 93],columns=['values']) bins = np.arange(0,df['values'].max() + 10, 10) df['bins'] = pd.cut(df['values'], bins) values bins 0 10 (0, 10] 1 10 (0, 10] 2 23 (20, 30] 3 42 (40, 50] 4 51 (50, 60] 5 33 (30, 40] 6 52 (50, 60] 7 42 (40, 50] 8 44 (40, 50] 9 67 (60, 70] 10 65 (60, 70] 11 12 (10, 20] 12 10 (0, 10] 13 2 (0, 10] 14 3 (0, 10] 15 2 (0, 10] 16 77 (70, 80] 17 76 (70, 80] 18 93 (90, 100] Edit: To include zeros in the bins as asked in the comments, set the parameter include_lowest to True df = pd.DataFrame([0, 0, 0, 10, 10, 23, 42, 51, 33, 52, 42,44, 67, 65, 12, 10, 2, 3, 2, 77, 76, 93],columns=['values']) bins = np.arange(0,df['values'].max() + 10, 10) df['bins'] = pd.cut(df['values'], bins, include_lowest=True) You get values bins 0 0 (-0.001, 10.0] 1 0 (-0.001, 10.0] 2 0 (-0.001, 10.0] 3 10 (-0.001, 10.0] 4 10 (-0.001, 10.0] 5 23 (20.0, 30.0] 6 42 (40.0, 50.0] 7 51 (50.0, 60.0] 8 33 (30.0, 40.0] 9 52 (50.0, 60.0] 10 42 (40.0, 50.0] 11 44 (40.0, 50.0] 12 67 (60.0, 70.0] 13 65 (60.0, 70.0] 14 12 (10.0, 20.0] 15 10 (-0.001, 10.0] 16 2 (-0.001, 10.0] 17 3 (-0.001, 10.0] 18 2 (-0.001, 10.0] 19 77 (70.0, 80.0] 20 76 (70.0, 80.0] 21 93 (90.0, 100.0] Oh i see. Thank you, this is what i needed. sorry for my lack of knowledge in programming, so as a start point u selected, as a stop point you selected max value in dataframe, but they why you added "10" to df['values'].max()? @Mischa, all of us are at a different stage of learning so no need to be sorry. In the range function, the upper boundary is not included, eg: range(0,100, 10) will only give you numbers from 0 to 90. +10 will handle I accepted this answer but i have another issue now, if i have zeros in a dataframe np.arrange can not inclue it in a bins. Should i use another function o r is there a way to inclue zeros with np.arange df = pd.DataFrame([0, 0, 0, 10, 10, 23, 42, 51, 33, 52, 42,44, 67, 65, 12, 10, 2, 3, 2, 77, 76, 93],columns=['values']) if this is my dataframe the the bins for zeros will be NaN bins = np.arange(-1,df['values'].max() + 10, 10) i can replace zero with '-1', but in this case my bins will from -1 to 9, form 9 to 19 and etc @Vaishalihow would you account for negative bins? Like the range of the dataframe is from -200 to 200. @Syed Ahmed, You can change np.arange(0,df['values'].max() + 10, 10) to np.arange(-200, 210, 10). Or np.arange(df[‘values’].min(), df['values'].max() + 10, 10) That worked amazing @Vaishali. Is there also a way to convert the interval into a separate list? For example an interval of (-1653.431, -1648.43] and onwards could only be visible as [-1653.431] as type list @SyedAhmed, not sure I understand the question. If you print the variable bins, you will see that they are in list already @Vaishali - can I check is there anyway to create the bins based on outcome label distribution? Can you please help me with this post if you have time? https://stats.stackexchange.com/questions/561758/how-to-create-encoding-for-continuous-variable-based-on-label-frequency @Vaishali basically answered the question, but just to add that in order to get your desired labels programmatically, you can use the bin values in a list comprehension, resulting in the string labels below (matching your desired frame) df = pd.DataFrame([10, 10, 23, 42, 51, 33, 52, 42,44, 67, 65, 12, 10, 2, 3, 2, 77, 76],columns=['values']) bins = np.arange(0,df['values'].max() + 10, 10) labels = ['-'.join(map(str,(x,y))) for x, y in zip(bins[:-1], bins[1:])] df['bins'] = pd.cut(df['values'], bins = bins, labels=labels) >>> df values bins 0 10 0-10 1 10 0-10 2 23 20-30 3 42 40-50 4 51 50-60 5 33 30-40 6 52 50-60 7 42 40-50 8 44 40-50 9 67 60-70 10 65 60-70 11 12 10-20 12 10 0-10 13 2 0-10 14 3 0-10 15 2 0-10 16 77 70-80 17 76 70-80 Here we solve this problem, simply using the Binning Function and bit help of numpy function. df = pd.DataFrame([10, 10, 23, 42, 51, 33, 52, 42,44, 67, 65, 12, 10, 2, 3, 2, 77, 76],columns=['values']) max = df['value'].max() df['Bins'] = pd.cut(df['value'], np.arange(0, max + 10, 10)) print(df) Code-only answers are generally frowned upon on SO. Please edit your answer to include an explanation of what your code does and how it solves OP's problem. While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply.
common-pile/stackexchange_filtered
Very slow MySQL query execution I have created a database in MySQL on Ubuntu to get an overview which comics I own and to get some details like the title of an issue, it's writers, editors, pencilers etc. No problems with the query itself but with the amount of time it takes to execute it. This is the query: select issue.issueNR, issue.issueName, series.seriesName, writer.writerName, editor.editorName, penciler.pencilerName, letterer.lettererName, colourist.colouristName, coverArtist.coverArtistName from writer, writerLookup, editor, editorLookup, penciler, pencilerLookup, letterer, lettererLookup, colourist, colouristLookup, coverArtist, coverArtistLookup, issue, series where (issue.issueID = writerLookup.issueID and writerLookup.writerID = writer.writerID) and (issue.issueID = editorLookup.issueID and editorLookup.editorID = editor.editorID) and (issue.issueID = pencilerLookup.issueID and pencilerLookup.pencilerID = penciler.pencilerID) and (issue.issueID = lettererLookup.issueID and lettererLookup.lettererID = letterer.lettererID) and (issue.issueID = colouristLookup.issueID and colouristLookup.colouristID = colourist.colouristID) and (issue.issueID = coverArtistLookup.issueID and coverArtistLookup.coverArtistID = coverArtist.coverArtistID) and issue.seriesID = series.seriesID; The result: +---------+---------------------------+---------------------------+-------------+-------------+----------------+-------------------+---------------+-----------------+ | issueNR | issueName | seriesName | writerName | editorName | pencilerName | lettererName | colouristName | coverArtistName | +---------+---------------------------+---------------------------+-------------+-------------+----------------+-------------------+---------------+-----------------+ | 1 | X-Men | X-Men | Stan Lee | Stan Lee | Jack Kirby | Sam Rosen | Uncredited | Jack Kirby | | 1 | X-Men | X-Men | Stan Lee | Stan Lee | Jack Kirby | Sam Rosen | Uncredited | Sol Brodsky | | 1 | The Long Way Home, Part 1 | Buffy, the Vampire Slayer | Joss Whedon | Scott Allie | Georges Jeanty | Richard Starkings | Dave Stewart | Jo Chen | | 1 | The Long Way Home, Part 1 | Buffy, the Vampire Slayer | Joss Whedon | Scott Allie | Georges Jeanty | Jimmy Betancourt | Dave Stewart | Jo Chen | | 1 | The Long Way Home, Part 1 | Buffy, the Vampire Slayer | Joss Whedon | Scott Allie | Georges Jeanty | Richard Starkings | Dave Stewart | Georges Jeanty | | 1 | The Long Way Home, Part 1 | Buffy, the Vampire Slayer | Joss Whedon | Scott Allie | Georges Jeanty | Jimmy Betancourt | Dave Stewart | Georges Jeanty | +---------+---------------------------+---------------------------+-------------+-------------+----------------+-------------------+---------------+-----------------+ 6 rows in set (2 min 55.66 sec) As you can see it takes almost 3 minutes to generate 6 rows and that's really too slow, especially because this is not the complete query because I also have an inker, tpb, ... You can find the bash script which I use to create the tables here: http://textuploader.com/degt Is there some way to make the query or my database more performant? Do you have indexes on all the files you're using in the joins? The query takes 55.66 sec, not 3 minutes, the difference is transfering from server to browser and rendering html. You are joining 14 tables, and not even using a real JOIN. Do you use index? Can you put EXPLAIN before the select and put the result up here. Also, they way you join tables is NOT recommended. @DanFromGermany, it does say 2 min before 55.56 sec ;) @MarcB Nope, no indexes. Then definitely add indexes. General rule of thumb is to ALWAYS have an index on any field involved in a where or a join operation. Timo, you probably dont want to hear this but, I would recommend you to start over. This is a terrible query and very hard to read. Take your time to read about joining tables with indexes, and you will have a query that probably runs in less than 1 second if you set it up properly. This query is to bad to even begin to fix IMHO. @KayNelson This is the output of the EXPLAIN http://textuploader.com/deg0 First time btw that I'm trying to create something like this so I knew I would have to start over a couple of times :) @MarcB I have added index on fields that I use in the where clause but it still takes 55 seconds to execute. Something else I should look after? just how many records are there in this db? if the size of the indexes exceeds your db's memory setup, then you'll be hitting disk and get painfully bad execution times. @MarcB Every table (19 to be exact) contains maximum 3 rows but when I delete the database, it says that 19 rows are affected.
common-pile/stackexchange_filtered
Kubernetes on AWS - managing virtual IPs I've just set-up a 3-node Kubernetes cluster on AWS using Kelsey's guide. I notice that K8 assigns a unique virtual IP address to each pod and service. In the guide, a AWS route table is used to map the virtual IPs to actual IPs. While this works, it seems quite primitive and is not scalable when nodes are added/removed to the Kubernetes cluster. What's the standard way to handle these virtual IPs when hosting Kubernetes on AWS at scale? I think Kelsey's guide is very useful to understand how Kubernetes actually works but there are better choices to deploy Kubernetes on AWS, like CoreOS kube-aws or kops. https://github.com/coreos/kube-aws https://github.com/kubernetes/kops AWS route tables have a limit of 50 entries each, so that's not a very scalable solution. The most common approach is to use an overlay network. Two popular ones are CoreOS Flannel Weaveworks Weave The Flannel README in particular gives a good overview of how it works.
common-pile/stackexchange_filtered
How to pass the value by clicking UI button in unity How to pass the value by clicking UI button in unity i have 4 buttons in my scene so what i want to do means button A have 5 button B have 25 button C have 2 button D have 7 EXAMPLE: If i click the button A and Button B value 30 and how to detect the button is clicked first time and second time ?? Please Help me out thank you in advance https://stackoverflow.com/questions/38518903/unity-5-how-to-pass-multiple-parameters-on-button-click-function-from-inspector To pass a value in a UI button you can use a public function with one parameter. Here's an example code using switch to detect which button was clicked, and a dictionary to count clicks for each button. int sum; Dictionary<string, int> clickCounts = new Dictionary<string, int>(); void Start() { clickCounts.Add("A", 0); clickCounts.Add("B", 0); clickCounts.Add("C", 0); clickCounts.Add("D", 0); } public void ButtonClick(string buttonLetter) { switch (buttonLetter) { case "A": sum += 5; clickCounts["A"]++; break; case "B": sum += 25; clickCounts["B"]++; break; case "C": sum += 2; clickCounts["C"]++; break; case "D": sum += 7; clickCounts["D"]++; break; } }
common-pile/stackexchange_filtered
Autofill form with existing form values I am trying to get a form field to autofill with the same value as another field using Ninja Forms and Wordpress. I have looked at some solutions using JQuery but none of them seem to work. Please help me figure out what I am doing wrong. Here is a link to the form: https://optionsqa.wpengine.com/test-page/ I want to get the content in "COPY THIS LINK" to automatically populate the field below. This is the script I am trying: <script type="text/javascript"> jQuery(document).ready(function() { jQuery('.copy-link').on('change', function() { jQuery('.favorite-link-field').val($(this).val()); }); }); </script> jQuery solution (updated to include ninja form ready state, as per comments): I prefer using the id over class since classes can be used multiple times. That being said: This will update when #nf-field-10 or Favorites Link is changed. jQuery(document).on( 'nfFormReady', function( e, layoutView ) { jQuery('#nf-field-10').on('change', function() { jQuery('#nf-field-10').val(jQuery('#nf-field-16').val()); }); }); Not working! :( Could ninja forms be preventing this from working? not sure. Tested this in DevTools and it worked as described. Based on both answers not working, it might be ninja forms. Thanks for the reply! After what you said I dug further and found this: https://stackoverflow.com/questions/40875677/custom-jquery-not-working-on-wordpress-ninja-forms-plugin. It seems to work as it now listens to a regular print function, but how do I apply this to the code you provided? Please remember to mark as the answer / upvote if this works for you.
common-pile/stackexchange_filtered
prevent from printing extra whitespace at the end of my line C++ so I'm taking in input by string input,word; while(getline(cin, input)) { stringstream ss; ss<<input while(ss >> word) ... and printing the stuff I want by cout <<word<<" "; However, when I do this it creates an extra whitespace at the end of each line and I don't want that. If I don't put that whitespace there there will be no spaces between words when I print them out. Is there an easier way to cout the words I want so that they are automatically spaced? What are some of the things I could do to prevent the extra whitespace at the end of each line. Similar to this: https://stackoverflow.com/questions/35858896/c-compare-and-replace-last-character-of-stringstream/35859132#35859132 and this: https://stackoverflow.com/questions/36137997/convert-vectorunsigned-char-1-2-3-into-string-1-2-3-as-digits/36138229#36138229 Right now you're putting the white-space after the word. You could fix this by printing the first word outside of the while loop, and then printing the whitespace before the each word. Handling the first word separately will avoid a leading whitespace. Won't std::getline work for this? @RandomDavis: the issue is with output, not input. Test the first word extraction outside the loop, then continue the loop with leading spaces: std::string input; while(getline(std::cin, input)) { std::istringstream ss(input); std::string word; if (ss >> word) { std::cout << word; while (ss >> word) std::cout << ' ' << word; std::cout << '\n'; } } Note: newline added for line completion. Use or delete at your discretion. This method only works for some cases due to the nature of what I want to do. Let's say I need to create a new line only if the input I read in is ";" if I'm given input that consists of multiple lines with only 1 word that are not ";" I need to print them in one line with a space between each word. If I do this, all those words will have no spaces in between. @GuiMontag This method works for exactly the problem your question described. If you need something else, the question should reflect that. In your comment "Let's say I need.... only if...", the very presence of "only if" constitute additional boolean checks and actions therein. Those checks simply need to be translated into code. Flip the problem around. Instead of appending a space, figure out when you should prepend a space. The way I do this is to initialize a prefix delimiter to an empty value, then set it to something valid after the first element. In your case, it would be like this: const char *delimiter= ""; while(ss >> word) { ss >> delimiter >> word; delimiter= " "; } Thanks dude, I think your solution passed most of my testing A trick - which still feels a bit frustrating - is adding a boolean variable in the mix: bool space = false; while (ss >> word) { if (space) { cout << " "; } else { space = true; } cout << word; } Sadly the second example doesn't work. It exhibits the same problem. I tried the first method and I got the same problem. I'm not sure why though. Shouldn't the loop stop once input stops? @Galik, thanks removed. @Gui Montag you should put this code as replacement of your while(ss >> word) and there should be no difference in reading the input...
common-pile/stackexchange_filtered
How to know a webpage last-modified date & time in Android Java How can I know the date a webpage last-modified using Android Java? or how I can request for If-Modified-Since: Allows a 304 Not Modified to be returned if content is unchanged using http headers? No, I think last-modified is open for anyone, otherwise how google will sort things by date? I am not certain, but if they were to check every day and compare what is there to what they got last time they'd be able to tell roughly when the change occurred. That can be done, but last-modified and if-modified-since are there in http request & response for some reason! I could do it this way: URL url = null; try { url = new URL("http://www.example.com/example.pdf"); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } HttpURLConnection httpCon = null; try { httpCon = (HttpURLConnection) url.openConnection(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } long date = httpCon.getLastModified();
common-pile/stackexchange_filtered
Jolt Transformation - Replace all matches I am trying to get a JOLT transformation to work using https://jolt-demo.appspot.com/. I would like to replace all "master" values with "7.11". Input: { "build": [ { "number": "7.11.13898", "branchName": "branch1" }, { "number": "7.11.13896", "branchName": "branch2" }, { "number": "7.11.13895", "branchName": "master" }, { "number": "7.11.13900", "branchName": "master" } ] } Desired Output: { "build": [ { "number": "7.11.13898", "branchName": "branch1" }, { "number": "7.11.13896", "branchName": "branch2" }, { "number": "7.11.13895", "branchName": "7.11" }, { "number": "7.11.13900", "branchName": "7.11" } ] } I can't seem to get a transform or shift that works without changing/altering the structure of the data. Current Approach: [ { "operation": "shift", "spec": { "build": { "*": { "number": "build[&1].number", "branchName": { "master": { "#7.11": "build[&3].branchName" }, "*": { "@(2, branchName)": "build[&3].branchName" } } } } } } ] Current Output: { "build" : [ { "number" : "7.11.13898" }, { "number" : "7.11.13896" }, { "branchName" : "7.11", "number" : "7.11.13895" } ] } You are almost found it. You need to replace @(2, branchName) with $ and it should work for you. The "$" operator means use the input key, instead of the input value as output. Solution: [ { "operation": "shift", "spec": { "build": { "*": { "number": "build[&1].number", "branchName": { "master": { "#7.11": "build[&3].branchName" }, "*": { "$": "build[&3].branchName" } } } } } } ] Thank you so much! I was pulling my hair out trying to figure this out.
common-pile/stackexchange_filtered
does the depth of the prototype chain for an object affect the performance? Several days ago,I post a question here about class inheritance Then someone provide a link-- a clever script for class inheritance by John Resig. Then I try to use this script. But I found that object created by this script will have a very deep prototype chain. I use the example in the blog: var Person = Class.extend({ init: function(isDancing){ this.dancing = isDancing; }, dance: function(){ return this.dancing; } }); var Ninja = Person.extend({ init: function(){ this._super( false ); }, dance: function(){ // Call the inherited version of dance() return this._super(); }, swingSword: function(){ return true; } }); var n=new Ninja(true); console.dir(n); With firebug I found this: So I wonder does the depth of the prototype chain for an object affect the performance? It seem there is a Endless loop. The prototype of a constructor is the same constructor. So yes, you are looking at an endless loop. However browsers don't follow the constructor chain when resolving object's members, it has an internal pointer (sometimes called __PROTO__ but don't count on it) which is actually used. A JavaScript engine might also opt to compile to machine code which resolves the possible members in advance so no chain at all exists during actual execution. I strongly doubt that you will experience any slow-down at all. It does affect the performance because it needs to follow the prototype chain to get the property's value. Will this likely become the bottleneck of your application? I highly doubt it. @hguser For some reason I feel compelled to clarify that Russell's question of the potential bottleneck was purely rhetorical. Maybe I understand this poorly but how can an endless chain be followed to get the value?
common-pile/stackexchange_filtered
EventBus/PubSub vs (reactive extensions) RX with respect to code clarity in a single threaded application Currently, I am using an EventBus/PubSub architecture/pattern with Scala (and JavaFX) to implement a simple note organizing app (sort of like an Evernote client with some added mind mapping functionality) and I have to say that I really like EventBus over the observer pattern. Here are some EventBus libraries : https://code.google.com/p/guava-libraries/wiki/EventBusExplained http://eventbus.org (currently seems to be down) this is the one I am using in my implementation. http://greenrobot.github.io/EventBus/ Here is a comparison of EventBus libraries : http://codeblock.engio.net/37/ EventBus is related to the publish-subscribe pattern. However ! Recently, I took the Reactive course by Coursera and started to wonder whether using RXJava instead of EventBus would simplify the event handling code even more in a single threaded application ? I would like to ask about the experiences of people who programmed using both technologies (some kind of eventbus library and some form of the reactive extensions (RX)): was it easier to tackle event handling complexity using RX than with an event bus architecture given that there was no need to use multiple threads ? I am asking this because I have heard in the Reactive Lectures on Coursera that RX leads to much cleaner code than using the observer pattern (i.e. there is no "callback hell"), however I did not find any comparison between EventBus architecture vs RXJava. So it's clear that both EventBus and RXJava are better than the observer pattern but which is better in a single threaded applications in terms of code clarity and maintainability ? If I understand correctly the main selling point of RXJava is that it can be used to produce responsive applications if there are blocking operations (e.g. waiting for response from a server). But I don't care about asychronicity at all, all I care about is keeping the code clean, untangled and easy to reason about in a single threaded application. In that case, is it still better to use RXJava than EventBus ? I think EventBus would be a simpler and cleaner solution and I don't see any reason why I should use RXJava for a single threaded application in favour of a simple EventBus architecture. But I might be wrong! Please correct me if I am wrong and explain why RXJava would be better than a simple EventBus in case of a single threaded application where no blocking operations are carried out. You might want to get in touch with Tomas Mikula, the ReactFX creator. Interesting! Thanks for the tip. scalafx (and javafx) have their own Observable class (actually ObservableValue is closer to RX' observable). I'm currently looking into creating an adapter between the two. If this were possible, you could simply use scalafx's bind directive, which is nice and declarative! I don't know what "Eventbus" is. That being said, event buses are service locators, which are anti-patterns. Using the pub/sub pattern with dependency injection, on the other hand, gets you a lot more explicit control over application modularity, and therefore testing as well. Since Rx is absolutely fantastic for pub/sub, I'd advice that. Again, if Eventbus is something other than an event bus, then I have no advice on the matter. @ChristopherHarris EventBus is a kind of pub/sub pattern. What do you mean pub/sub pattern with dependency injection ? Why do I need DI for pub/sub ? The real question is do I really need Rx over pub/sub in a single threaded application ? What does Rx give me more in a single threaded application than what a simple pub/sub library can give me ? Please see modified and extended question for references to such libraries. I would say that event streams (be it RX or ReactFX) would improve code clarity because 1) event bus is (or feels like) a global object and 2) event streams come with handy stream operators to filter/transform/combine events which, when used properly, can encapsulate a lot of state, reducing mutable state and side effects in your application. Maybe we can advise more if you post some concrete problem or code. Thank you very much for this answer Tomas ! I will try to come up with some model scenario in which both approaches could be compared and the advantages vs disadvantages can be pointed out in a more specific manner. @TomasMikula Tomas, could you perhaps describe an example in an answer that you have on your mind where RX would be better than EventBus? I mean the simplest possible concrete example where RX would beat EventBus in terms of simplicity/understandability/code clarity. I don't see why having a globally shared event channel would be any problem if the number of possible different events (event classes in a hierarchy) is not more than about 100. My problem with RX is that it needs dependency injection, i.e. the objects that send or receive events have to be injected with the channel. So the basic difference between a single channel EventBus and RX is that in RX you have much more channels via which the events can travel, right? In EventBus you have only one channel and this simplifies the application because there is only one channel. Like a CB channel, everybody can listen to the messages but don't have to react if the message is not interesting. I specifically have in mind GUI events which change a domain model which again updates the view. All communication can go on the same channel, why would RX help ? When you have a component A that consumes events produced by component B, their coupling via an event bus is indirect and therefore less clear. a.events().subscribe(b::handle) is much more explicit than eventBus.register(b) somewhere and eventBus.post(evt) somewhere else. Furthermore, the producer's API does not state what types of events it publishes to the event bus. On the other hand, if you have a component that has a method returning EventStream<E> and another one returning EventStream<F>, it is clear that this component produces events of type E and events of type F. You don't necessarily need dependency injection, at least not with ReactFX. A component that produces events will create an event stream instead of getting it as a dependency. A component that reacts to events may just expose event handling methods, or an event sink to which events can be pushed. The wiring between the producer and the consumer is set up in a component encapsulating the two. So basically you say that RX is better because the wiring logic is located in one place instead of scattered all over the place (which is what happens when using EventBus). Also Tomas, if you would kindly add your above comments as an answer then I could accept that and the question then would be properly answered. Yes, but that's not the main strength of reactive event streams, but rather just a disadvantage of event buses. The main strength (in a synchronous single threaded application) is reducing mutable state and side effects. ReactFX (but not rxJava) also has means to eliminate glitches (temporary inconsistencies in observed state) and redundant computation. Whether you can take advantage of these features depends on your use case. Direct rewrite to RX does not automatically yield these benefits. Could you please give a simple example how RX reduces mutable state vs EventBus ? It would be very illuminating for me to see how this can happen. The following is what I see as benefits of using reactive event streams in a single-threaded synchronous application. 1. More declarative, less side-effects and less mutable state. Event streams are capable of encapsulating logic and state, potentially leaving your code without side-effects and mutable variables. Consider an application that counts button clicks and displays the number of clicks as a label. Plain Java solution: private int counter = 0; // mutable field!!! Button incBtn = new Button("Increment"); Label label = new Label("0"); incBtn.addEventHandler(ACTION, a -> { label.setText(Integer.toString(++counter)); // side-effect!!! }); ReactFX solution: Button incBtn = new Button("Increment"); Label label = new Label("0"); EventStreams.eventsOf(incBtn, ACTION) .accumulate(0, (n, a) -> n + 1) .map(Object::toString) .feedTo(label.textProperty()); No mutable variable is used and the side-effectful assignment to label.textProperty() is hidden behind an abstraction. In his master thesis, Eugen Kiss has proposed integration of ReactFX with Scala. Using his integration, the solution could look like this: val incBtn = new Button("Increment") val label = new Label("0") label.text |= EventStreams.eventsOf(incBtn, ACTION) .accumulate(0, (n, a) => n + 1) .map(n => n.toString) It is equivalent to the previous, with the additional benefit of eliminating inversion of control. 2. Means to eliminate glitches and redundant computations. (ReactFX only) Glitches are temporary inconsistencies in observable state. ReactFX has means to suspend event propagation until all updates to an object have been processed, avoiding both glitches and redundant updates. In particular, have a look at suspendable event streams, Indicator, InhiBeans and my blog post about InhiBeans. These techniques rely on the fact that event propagation is synchronous, therefore do not translate to rxJava. 3. Clear connection between event producer and event consumer. Event bus is a global object that anyone can publish to and subscribe to. The coupling between event producer and event consumer is indirect and therefore less clear. With reactive event streams, the coupling between producer and consumer is much more explicit. Compare: Event bus: class A { public void f() { eventBus.post(evt); } } // during initialization eventBus.register(consumer); A a = new A(); The relationship between a and consumer is not clear from looking at just the initialization code. Event streams: class A { public EventStream<MyEvent> events() { /* ... */ } } // during initialization A a = new A(); a.events().subscribe(consumer); The relationship between a and consumer is very explicit. 4. Events published by an object are manifested in its API. Using the example from the previous section, in the event bus sample, A's API does not tell you what events are published by instances of A. On the other hand, in the event streams sample, A's API states that instances of A publish events of type MyEvent. On your point #3, the fact that the "wiring" is loose is a strength of event bus rather than a weakness in my opinion. From the perspective of the consumer, it really does not matter who publishes an event. And vice versa, from the publisher's perspective, it does not care about who receives it - whoever wants to listen and react, can. That is the beauty of the pub/sub architecture. At least that is my understanding of it. @JihoHan What you say is still true about my example in point 3: A does not care who, if anyone, consumes the events it produces, and consumer does not care who produced the event. The added benefit is that the wiring code knows for sure that A is capable of producing events of type MyEvent, and that consumer is capable of consuming them. This gives you more type safety. Too much freedom (as with global event bus) reduces the ability to reason about the code. @TomasMikula Totally agree with you on this one - I sometimes feel like a poorly executed bus is like littering your code with global variables... A well executed Bus isn't a problem, but I find with Observables - it's much easier to execute it well. I think you have to use the rxjava because it provides much more flexibility. If you need a bus you can use an enum like this: public enum Events { public static PublishSubject <Object> myEvent = PublishSubject.create (); } //where you want to publish something Events.myEvent.onNext(myObject); //where you want to receive an event Events.myEvent.subscribe (...); . Why an enum and not just a class? @cyroxis You use the "enum-pattern" because it is the usual way to implement Singletons in Java. But in this particular case the enum is final and prohibit instantiations, so you don't need to write a private constructor. @ChristianUllenboom This is not a singleton, just a static field that could go in a class or interface. Also I would not say that Enum's are the usual way, it does not support lazy instantiation which can be important when load times are a concern (e.g. Android). I learned one or two things since I asked this question 2 years ago, here is my current understanding (as explained in Stephen's FRP book): The both try to help to describe a state machine, i.e. describe how the state of the program is changing in response to events. The key difference between EventBus and FRP is compositionality: What is compositional ? Functional programming is compositional. We can all agree on that. We can take any pure function, combine it with other pure functions and what we get is a more complicated pure function. Compositionality means that when you declare something then at the site of the declaration all behaviour of the declared entity is defined. FRP is a compositional way of describing a state machine, and event-bus is not. Why ? It describes a state machine. It is compositional because the description is done by using pure functions and immutable values. EventBus is not a compositional way of describing a state machine. Why not ? You cannot take any two event busses and compose them in a way that gives a new, composed event bus describing the composed state machine. Why not ? Event busses are not first class citizens (as opposed to FRP's Event/Stream) . What happens if you try to make event busses first class citizens ? Then you get something resembling FRP/RX. State influenced by the event busses are not first class citizens (i.e. referentially transparent, pure values in contrast to FRP's Behaviour/Cell) tied to the event busses in a declarative/functional way, instead state is modified imperatively triggered by event handling In summary, EventBus is not compositional, because the meaning and behaviour of a composed EventBus (i.e. the time evolution of the state that is influenced by said composed EventBus) depends on time (i.e the state of those parts of the software which are not included explicitly in the declaration of the composed EventBus). In other words, if I would try to declare a composed EventBus then it would not be possible to determine (just by looking at the declaration of the composed EventBus) what rules govern the state evolution of those states that are influenced by the composed EventBus, this is in contrast to FRP, where this can be done.) As per my comment above, JavaFx has a class ObservableValue which sort of corresponds to RX Observable (probably ConnectableObservable to be more precise, as it allows more than one subscription). I use the following implicit class to convert from RX to JFX, like this: import scala.collection.mutable.Map import javafx.beans.InvalidationListener import javafx.beans.value.ChangeListener import javafx.beans.value.ObservableValue import rx.lang.scala.Observable import rx.lang.scala.Subscription /** * Wrapper to allow interoperability bewteen RX observables and JavaFX * observables. */ object JfxRxImplicitConversion { implicit class JfxRxObservable[T](theObs : Observable[T]) extends ObservableValue[T] { jfxRxObs => val invalListeners : Map[InvalidationListener,Subscription] = Map.empty val changeListeners : Map[ChangeListener[_ >: T],Subscription] = Map.empty var last : T = _ theObs.subscribe{last = _} override def getValue() : T = last override def addListener(arg0 : InvalidationListener) : Unit = { invalListeners += arg0 -> theObs.subscribe { next : T => arg0.invalidated(jfxRxObs) } } override def removeListener(arg0 : InvalidationListener) : Unit = { invalListeners(arg0).unsubscribe invalListeners - arg0 } override def addListener(arg0 : ChangeListener[_ >: T]) : Unit = { changeListeners += arg0 -> theObs.subscribe { next : T => arg0.changed(jfxRxObs,last,next) } } override def removeListener(arg0 : ChangeListener[_ >: T]) : Unit = { changeListeners(arg0).unsubscribe changeListeners - arg0 } } } Then allows you to use property bindings like so (this is ScalaFX, but corresponds to Property.bind in JavaFX): new Label { text <== rxObs } Where rxObs could be for example: val rxObs : rx.Observable[String] = Observable. interval(1 second). map{_.toString}. observeOn{rx.lang.scala.schedulers.ExecutorScheduler(JavaFXExecutorService)} which is simply a counter that increments every second. Just remember to import the implicit class. I can't imagine it getting any cleaner than that! The above is a bit convoluted, due to the need to use a scheduler that plays nicely with JavaFx. See this question for a link to a Gist of how JavaFXExecutorService is implemented. There is an enhancement request for scala RX to make this into an implicit argument, so in future you may not need the .observeOn call. Thanks for the answer but this was not really the question.
common-pile/stackexchange_filtered
When I post a request through rest template,It throws no suitable HttpMessageConverter HttpHeaders reqheaders= new HttpHeaders(); reqheaders.set(HttpHeaders.Accept,MediaType.Application_xml) reqheaders.set(HttpHeaders.Content_type,MediaType.Application Json) HttpEntity XML= new HttpEntity (json,reqheaders) ResponseEntity<Map> xmlfile= restTemplate.exchange(url,HttpMethod.POST,XML, Map.class) I am getting no suitable HttpMessageConverter found for response type[interface java.util.Map] and content type [application/xml;charset=UTF-8] it looks like no suitable HttpMessageConverter is registered with the RestTemplate can convert xml content to a Map object. There some HttpMessageConverters which are pre-enabled and can be checked here. You need to make sure that the suitable HttpMessageConverter is on your classpath.
common-pile/stackexchange_filtered
How to make a body rotate about a line that does not go through its center of mass by applying external torques In space, is it possible to make a body rotate a point that does not go through its center of mass by applying external torques? Yes, of course you can do this. Try it at home: take a straight pole/broom handle of uniform mass per unit length, and prop it up on a log/bottle lying on its side at a quarter of the distance from one end. Now push down on the short end with your hand. See how it rotates not about its centre of mass (the mid-point), but about the pivot point? (In space, the only difference is that you'd have to use your other hand in place of the log/bottle to provide the reaction force, since there isn't a conveniently placed massive object (the Earth!) to do it for you) Is the object a free object or is it anchored? What reference frame are you using, and are you including possible revolution as part of the idea of "rotation?" Since a system must obey the law of momentum conservation, the center of mass of a system (which can be made of one or many bodies) must have constant velocity if no external force is applied. Hence, a body can rotate around its center of mass, or it can rotate around any other point, but only if under the influence of an external force. Therefore one can made an object rotate around a point which is not its center of mass in many ways. For example, two object in space can rotate one around the other, i.e., around their common center of mass, under the influence of mutual gravitational attraction. This is the case of the Earth, which rotates around the common center of mass of the system which comprise the Earth and the Sun altogether. Another possibility is to make an object rotate around a pivot which is connected to another body with a larger mass. Also in this case, the whole system (the body plus the larger body) rotates around the common center of mass.
common-pile/stackexchange_filtered
Finding out when a td element shows ellipsis I have a table in which the cells show ellipsis if too long. I set overflow: hidden and text-overflow: ellipsis on the td elements. I now need to show a tooltip if the user hovers a cell that can't fit the entire text, but no tooltip on other cells. I can register an event to capture mouseover, but how can I tell if the hovered td shows ellipsis or not? I think you'd have to check the width of the contents against the width of the cell. Can you put together a JS Fiddle, for us to experiment with? You can check the scrollWidth of the content and compare it to the width of the element. Here's a solution with jQuery: $('td').each(function () { if ($(this)[0].scrollWidth > $(this).innerWidth()) { // Text is overflowing } }); http://jsfiddle.net/AvJvW/
common-pile/stackexchange_filtered
How to debug WCF dataservice I have a written dataservice for my windowsphone application and i'm trying to savechanges to this dataservice. To do this i call BeginSaveChanges: Context.AddToMeasurements(temp); Context.BeginSaveChanges(SaveChangesOptions.Batch, SaveChangesComplete, Context); The callback of this function returns an error when EndSaveChanges is called. private void SaveChangesComplete(IAsyncResult result) { // use a dispatcher to make sure the async void // returns on the right tread. Deployment.Current.Dispatcher.BeginInvoke(() => { DataServiceResponse WriteOperationResponse = null; Context = result.AsyncState as MeasurementEntities; try { WriteOperationResponse = Context.EndSaveChanges(result); Debug.WriteLine("Batch State:"); Debug.WriteLine(WriteOperationResponse.BatchStatusCode); } catch (DataServiceRequestException ex) { Debug.WriteLine(ex.Message); } catch (InvalidOperationException ex) { Debug.WriteLine(ex.Message); } }); } The Error the endsavechanges returns: An exception of type 'System.Data.Services.Client.DataServiceClientException' occurred in Microsoft.Data.Services.Client.WP80.DLL and wasn't handled before a managed/native boundary An exception of type 'System.Data.Services.Client.DataServiceRequestException' occurred in Microsoft.Data.Services.Client.WP80.DLL and wasn't handled before a managed/native boundary A first chance exception of type 'System.Data.Services.Client.DataServiceRequestException' occurred in Microsoft.Data.Services.Client.WP80.DLL An exception of type 'System.Data.Services.Client.DataServiceRequestException' occurred in Microsoft.Data.Services.Client.WP80.DLL and wasn't handled before a managed/native boundary An error occurred while processing this request. I would like to see some more detailed information about these errors, or if someone knows what they mean that also would be appreiciated, but how can I accomplish (more details on the dataservice) within visual studio? ps, i have allready added: config.UseVerboseErrors = true; and [ServiceBehavior(IncludeExceptionDetailInFaults = true)] to my dataservice. please help :) edit: When i remove the Try construction and just execute a EndSaveChanges method. I can read the innerExeptions, which is: Cannot insert explicit value for identity column in table 'Measurement' when IDENTITY_INSERT is set to OFF. any idea's what this means? you can attach your debugger to w3wp.exe for debuggind wcf services Is there a guide in how to do so? oh btw, the dataservice is not running on the same desktop as visual studio. then how can you debug it? I can't right now, thats why I've asked this question. It should be possible to move the dataservice to a local dataservice. ill have a look at that later. But for now, visual studio throws me some errormessages when I try to endSaveChanges, and I don't know where to look. Okay, i have got a little further and ive updated my anwser. Cannot insert explicit value for identity column in table 'Measurement' when IDENTITY_INSERT is set to OFF. it means that you are not passing any value to Measurement column and it is a mandatory field in the database. You need to pass value to it. But that is just what i want. I want to insert a measurement without specifing the primary key. I have the database set to increment and seed. So that is the measurmentid value isnt specified, it is automaticly inserted at the bottom of the table. So is there a way to achieve this? Oke, i think i solved it. I had set my database side to be autoincrement and primary key. I had not commited this change to the wcf data service.
common-pile/stackexchange_filtered
How to translate multiple parameters to a PHP conditional if statement Let's say I have the following url: example.php?grab=1,3&something=... grab has two values, how can I translate that to a conditional if statement. For example, if count is a variable and you want to calculate if count is equal to one of the grab values. $grab = $_GET["grab"]; $count = 4; if($count == $grab(values)) { alert("True"); } explode your grab parameter and use in_array or use strpos and check for !== false (meaning it's in there) If its always going to be , that glues the values, just explode them, that turns them into an array. Then just use your resident array functions to check. In this example, in_array: if(!empty($_GET['grab'])) { $grab = $_GET["grab"]; $count = 4; $pieces = explode(',', $grab); if(in_array($count, $pieces)) { // do something here if found } } Sidenote: If you try to devise your url to be like this: example.php?grab[]=1&grab[]=3&something You wouldn't need to explode it at all. You can just get the values, and straight up use in_array. The example above grab already returns it an array: if(!empty($_GET['grab'])) { $grab = $_GET["grab"]; $count = 4; if(in_array($count, $grab)) { // do something here if found } } Method#1: Reformat URL and Use PHP in_array() Why not reformat your url to something like this: example.php?grab[]=1&grab[]=3&something=... which automatically returns the grab value as an array in PHP? And then do something like: if(isset($_GET['grab']) && in_array(4, $_GET['grab'])) { // do something } Method#2: Split String into Array and Use PHP in_array() If you do not wish to reformat your url, then simply split the string into an array using php's explode function and check if value exists, for example: if(isset($_GET['grab'])) { $grab_array = explode(",", $_GET['grab']) if(in_array(4, $grab_array)) { // do something } } Method#3: Use Regular Expressions You could also use regular expressions to check for a match.
common-pile/stackexchange_filtered
need some explanation in Earley algorithm I would be very glad if someone can make clear for me example mentioned ono wikipedia: http://en.wikipedia.org/wiki/Earley_algorithm consider grammar: P → S # the start rule S → S + M | M M → M * T | T T → number and input: 2 + 3 * 4 Earley algorithm works like this: (state no.) Production (Origin) # Comment --------------------------------- == S(0): • 2 + 3 * 4 == (1) P → • S (0) # start rule (2) S → • S + M (0) # predict from (1) (3) S → • M (0) # predict from (1) (4) M → • M * T (0) # predict from (3) this is only first set S(0) but my question is: why algorithm is predicting from (3) in step (4) but it ommits prediction from (2)? I hope somebody understands idea and may help me Using (2) for prediction will not create new productions, because the symbol next to the dot is S. Therefore, will would only get the productions (2) and (3) again, which do not add information.
common-pile/stackexchange_filtered
Call undefined method from module I have a module where I want to call a method not defined in that module. Is it possible? #module def foo(): print bar() #main from foo import foo def bar(): return "Foo bar" def main(): foo.foo() No, you cannot. Python looks up undefined names in the same module a function is defined in. You'll have to pass in a function reference instead: def foo(func): print func() then in main: def main(): foo.foo(bar) You could add the function from one module to the other, but passing it as a callback is probably neater. It depends on the situation. #module def foo(bar): print bar() #main from foo import foo def bar(): return "Foo bar" def main(): foo(bar)
common-pile/stackexchange_filtered
Excel Formula If x in column B then y, Z, K..etc in Column A So basically I have a spreadsheet, with a list of names in column B. For this list of names I want to assign text to add into the adjacent cell in column A. I have tried =IF((C:C="Name1", C:C="Name2"),"Text","") However, this formula gives an error without any help. Can someone please solve this for me, or give me some information on how to solve it, as I need it to finish a project for work? You mention column B but you have column C in your formula? Could you perhaps give an example table? (e.g. tables in this question: http://stackoverflow.com/q/16448835/1578604) You may need to refine your requirements. As I understand it, you need in cell C1 and copied down =IF(OR(B1="Tom",B1="Bill"),"Bill or Tom","") Adjust ranges and names to suit your requirement. If I have understood correctly =if(b1="Name 1","Text","") + if(b1="Name 2","Text","") If the text in cell B1 is equal to Name1 or Name2 then cell A1 (or where you choose to enter the formula) will be have "Text". If B1 does not contain Name1 or Name2 then the cell will remain empty. Your formula is adding a text value with another text value and will return you #VALUE!. If you're looking for an OR option, you will have to modify your formula to =if(OR(b1="Name 1",b1="Name 2"),"Text",""). This worked perfectly for me, thanks very much for the help. I think the problem I was having was that I did not split the formula with respect to names. Thanks again. Yes @Jerry you are right, my bad. I usually only use that formula with numbers.
common-pile/stackexchange_filtered
How can I compare $\log_2 3$ and $\log_3 5$ without using a calculator Compare $\log_2 3$ and $\log_3 5$ without using a calculator. I am not very good at math please explain it clearly What have you tried? Here's a good guide on how to ask a great question. What do you mean "compare"? I would think that you mean "which is larger?", but there are many ways to compare numbers. For the upvoters: This might be an interesting problem, but it is, at the moment, a very poorly phrased question. If you want to show it recognition for being an interesting question, or you are interested in knowing the answer, consider favouriting instead. I think it's clear that comparison in this context is talking about which is larger ... no need to be pedantic about it this question is answered here: https://math.stackexchange.com/questions/415500/which-is-bigger-among-i-log-2-3-and-log-3-5-ii-log-2-3-and-log Note: $$\log_2 3=\frac14 \log_2 81>\frac14\log_2 64=\frac64=\frac32,$$ $$\log_3 5=\frac14 \log_3 625<\frac14\log_3 729=\frac64=\frac32.$$ We'll prove that $$\log_35<\log_23$$ or $$5<3^{\log_23}$$ or $$25<3^{\log_29},$$ which is true because $$3^{\log_29}>3^{\log_28}=27>25.$$ Done! $$\sqrt{3}\approx 1.73,\sqrt{2}\approx 1.42\\2^{1.5}=2\sqrt{2}< 2.84,\ 3^{1.5}=3\sqrt{3}>5.19\\\log_2 3>\log_22.84>\log_22\sqrt2= 1.5=\log_33\sqrt{3}> \log_35.19>\log_3 5$$
common-pile/stackexchange_filtered
How to display text from a textfile in html with javascript I want to use a text file as source for the text on my website. I just can't display it where I want it to be I have already managed to read the text from the file, but now I'm stuck. This is my readFile function: <script> function readFile(input){ var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var textFileText = searchFile(this.responseText, input); document.getElementById(input).innerHTML = this.textFileText; } }; xhttp.open("GET", textFile, true); xhttp.send(); } </script> I've tried it out and it works. This is the searchFile function: <script> function searchFile(text, searched){ var output; var n = text.search(searched); output = text.substr((n+str.length+2), text.indexOf('\n')); return output; } </script> It's supposed to filter the text in the file for a specific word. The text file looks like this: [header]=text [thing1]=more text My idea is that if I call the function like this: readFile("thing1"); The output should be "more text" Here I call the function to display the header Text: <h2 onload = "readFile(this.id)" id = "header"></h2> But then nothing gets displayed. I've also tried this: <h2 onload = "readFile('header')" id = "header"></h2> But again nothing is displayed. Am I missing something or did I do something wrong? append a <p> tag as a child of the header element with the text you want inside of the <p> tag. Why not use a json file, read it and parse the data to a JS object? Much simpler and elegant solution. There is no onload for h2 or most tags for that matter. So instead of calling the function from the onload, I would simply call the function from within script tags on the page. <script>readFile('header');</script> The only error I detected in your code is the misuse of variable => <script> function searchFile(text, searched){ var output; var n = text.search(searched); //output = text.substr((n+str.length+2), text.indexOf('\n')); output = text.substr((n+searched.length+2), text.indexOf('\n')); return output; } </script>
common-pile/stackexchange_filtered
User B can sudo to an user A (not root or group admin) I'm newbie, so please help me : In system , only user 'execute_prog'(not in group admin) has permission to execute a program ABC. Now, I want that user B can sudo as 'execute_prog' to execute this program. How can I do? Many thanks I think you may just be looking for the su command. B@my-pc:~$ su exec_prog exec_prog@pc:~$ Also if you'd like to allow user A to su as B without a password, you can edit /etc/pam.d/su and add the following lines # Change 'exec_prog' to the user you want to allow user B to become auth [success=ignore default=1] pam_succeed_if.so user = execute_prog # replace 'B' with your username auth sufficient pam_succeed_if.so use_uid user = B Hope this helps! Thanks for your answer. But the problem is , we have 10 developers and we dont want them 'su' on 'exec_prog' in the same time sounds like you might be able to make life a little easier by creating a group that can do these tasks. Something like groupadd devops, then add all the developers to that group. Once they are in the new group, allow executing the program ABC by the group: chown exec_prog:devops ABC
common-pile/stackexchange_filtered
Custom Drawing on Mapbox Map Canvas I would like to be able to manually draw complex shapes on a mapbox map using the android sdk. I have inherited the map view class and overridden the ondraw event but unfortunately whatever I draw gets over drawn by the map itself. As an example I need to be able to draw polygons with diamond shaped borders among other complex shapes. This i can do no problem in GoogleMaps using a custom tile provider and overriding ondraw. Here is the only code I have so far for mapbox: @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); Paint stroke = new Paint(); stroke.setColor(Color.BLACK); stroke.setStyle(Paint.Style.STROKE); stroke.setStrokeWidth(5); stroke.setAntiAlias(true); canvas.drawLine(0f,0f,1440f,2464f,stroke); } You can do what You want by 2 ways: 1) as You propose: "inherit the MapView class and overridden the onDraw() event". But MapView extends FrameLayout which is ViewGroup, so You should override dispatchDraw() instead of onDraw(). This approach requires custom view, which extends MapViewand implements: drawing over the MapView; customizing line styles ("diamonds instead of a simple line"); binding path to Lat/Lon coordinates of MapView. For drawing over the MapView You should override dispatchDraw(), for example like this: @Override public void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); canvas.save(); drawDiamondsPath(canvas); canvas.restore(); } For customizing line styles You can use setPathEffect() method of Paint class. For this You should create path for "diamond stamp" (in pixels), which will repeated every "advance" (in pixels too): mPathDiamondStamp = new Path(); mPathDiamondStamp.moveTo(-DIAMOND_WIDTH / 2, 0); mPathDiamondStamp.lineTo(0, DIAMOND_HEIGHT / 2); mPathDiamondStamp.lineTo(DIAMOND_WIDTH / 2, 0); mPathDiamondStamp.lineTo(0, -DIAMOND_HEIGHT / 2); mPathDiamondStamp.close(); mPathDiamondStamp.moveTo(-DIAMOND_WIDTH / 2 + DIAMOND_BORDER_WIDTH, 0); mPathDiamondStamp.lineTo(0, -DIAMOND_HEIGHT / 2 + DIAMOND_BORDER_WIDTH / 2); mPathDiamondStamp.lineTo(DIAMOND_WIDTH / 2 - DIAMOND_BORDER_WIDTH, 0); mPathDiamondStamp.lineTo(0, DIAMOND_HEIGHT / 2 - DIAMOND_BORDER_WIDTH / 2); mPathDiamondStamp.close(); mPathDiamondStamp.setFillType(Path.FillType.EVEN_ODD); mDiamondPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mDiamondPaint.setColor(Color.BLUE); mDiamondPaint.setStrokeWidth(2); mDiamondPaint.setStyle(Paint.Style.FILL_AND_STROKE); mDiamondPaint.setStyle(Paint.Style.STROKE); mDiamondPaint.setPathEffect(new PathDashPathEffect(mPathDiamondStamp, DIAMOND_ADVANCE, DIAMOND_PHASE, PathDashPathEffect.Style.ROTATE)); (in this case there are 2 Path - first one (clockwise) for outer border and second (counter-clockwise) for inner border for "diamond" transparent "hole"). For binding path on screen to Lat/Lon coordinates of MapView You should have MapboxMap object of MapView - for that getMapAsync() and onMapReady() should be overridden: @Override public void getMapAsync(OnMapReadyCallback callback) { mMapReadyCallback = callback; super.getMapAsync(this); } @Override public void onMapReady(MapboxMap mapboxMap) { mMapboxMap = mapboxMap; if (mMapReadyCallback != null) { mMapReadyCallback.onMapReady(mapboxMap); } } Than You can use it in "lat/lon-to-screen" convertating: mBorderPath = new Path(); LatLng firstBorderPoint = mBorderPoints.get(0); PointF firstScreenPoint = mMapboxMap.getProjection().toScreenLocation(firstBorderPoint); mBorderPath.moveTo(firstScreenPoint.x, firstScreenPoint.y); for (int ixPoint = 1; ixPoint < mBorderPoints.size(); ixPoint++) { PointF currentScreenPoint = mMapboxMap.getProjection().toScreenLocation(mBorderPoints.get(ixPoint)); mBorderPath.lineTo(currentScreenPoint.x, currentScreenPoint.y); } Full source code: Custom DrawMapView.java public class DrawMapView extends MapView implements OnMapReadyCallback{ private float DIAMOND_WIDTH = 42; private float DIAMOND_HEIGHT = 18; private float DIAMOND_ADVANCE = 1.5f * DIAMOND_WIDTH; // spacing between each stamp of shape private float DIAMOND_PHASE = DIAMOND_WIDTH / 2; // amount to offset before the first shape is stamped private float DIAMOND_BORDER_WIDTH = 6; // width of diamond border private Path mBorderPath; private Path mPathDiamondStamp; private Paint mDiamondPaint; private OnMapReadyCallback mMapReadyCallback; private MapboxMap mMapboxMap = null; private List<LatLng> mBorderPoints; public DrawMapView(@NonNull Context context) { super(context); init(); } public DrawMapView(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public DrawMapView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public DrawMapView(@NonNull Context context, @Nullable MapboxMapOptions options) { super(context, options); init(); } public void setBorderPoints(List<LatLng> borderPoints) { mBorderPoints = borderPoints; } @Override public void getMapAsync(OnMapReadyCallback callback) { mMapReadyCallback = callback; super.getMapAsync(this); } @Override public void onMapReady(MapboxMap mapboxMap) { mMapboxMap = mapboxMap; if (mMapReadyCallback != null) { mMapReadyCallback.onMapReady(mapboxMap); } } @Override public void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); canvas.save(); drawDiamondsPath(canvas); canvas.restore(); } private void drawDiamondsPath(Canvas canvas) { if (mBorderPoints == null || mBorderPoints.size() == 0) { return; } mBorderPath = new Path(); LatLng firstBorderPoint = mBorderPoints.get(0); PointF firstScreenPoint = mMapboxMap.getProjection().toScreenLocation(firstBorderPoint); mBorderPath.moveTo(firstScreenPoint.x, firstScreenPoint.y); for (int ixPoint = 1; ixPoint < mBorderPoints.size(); ixPoint++) { PointF currentScreenPoint = mMapboxMap.getProjection().toScreenLocation(mBorderPoints.get(ixPoint)); mBorderPath.lineTo(currentScreenPoint.x, currentScreenPoint.y); } mPathDiamondStamp = new Path(); mPathDiamondStamp.moveTo(-DIAMOND_WIDTH / 2, 0); mPathDiamondStamp.lineTo(0, DIAMOND_HEIGHT / 2); mPathDiamondStamp.lineTo(DIAMOND_WIDTH / 2, 0); mPathDiamondStamp.lineTo(0, -DIAMOND_HEIGHT / 2); mPathDiamondStamp.close(); mPathDiamondStamp.moveTo(-DIAMOND_WIDTH / 2 + DIAMOND_BORDER_WIDTH, 0); mPathDiamondStamp.lineTo(0, -DIAMOND_HEIGHT / 2 + DIAMOND_BORDER_WIDTH / 2); mPathDiamondStamp.lineTo(DIAMOND_WIDTH / 2 - DIAMOND_BORDER_WIDTH, 0); mPathDiamondStamp.lineTo(0, DIAMOND_HEIGHT / 2 - DIAMOND_BORDER_WIDTH / 2); mPathDiamondStamp.close(); mPathDiamondStamp.setFillType(Path.FillType.EVEN_ODD); mDiamondPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mDiamondPaint.setColor(Color.BLUE); mDiamondPaint.setStrokeWidth(2); mDiamondPaint.setStyle(Paint.Style.FILL_AND_STROKE); mDiamondPaint.setStyle(Paint.Style.STROKE); mDiamondPaint.setPathEffect(new PathDashPathEffect(mPathDiamondStamp, DIAMOND_ADVANCE, DIAMOND_PHASE, PathDashPathEffect.Style.ROTATE)); canvas.drawPath(mBorderPath, mDiamondPaint); } private void init() { mBorderPath = new Path(); mPathDiamondStamp = new Path(); } } ActivityMain.java public class MainActivity extends AppCompatActivity { private DrawMapView mapView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MapboxAccountManager.start(this, getString(R.string.access_token)); setContentView(R.layout.activity_main); mapView = (DrawMapView) findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(MapboxMap mapboxMap) { mapView.setBorderPoints(Arrays.asList(new LatLng(-36.930129, 174.958843), new LatLng(-36.877860, 174.978108), new LatLng(-36.846373, 174.901841), new LatLng(-36.829215, 174.814659), new LatLng(-36.791326, 174.779337), new LatLng(-36.767680, 174.823242))); } }); } @Override public void onResume() { super.onResume(); mapView.onResume(); } @Override public void onPause() { super.onPause(); mapView.onPause(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mapView.onSaveInstanceState(outState); } @Override public void onLowMemory() { super.onLowMemory(); mapView.onLowMemory(); } @Override protected void onDestroy() { super.onDestroy(); mapView.onDestroy(); } } activity_main.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:mapbox="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="ua.com.omelchenko.mapboxlines.MainActivity"> <ua.com.omelchenko.mapboxlines.DrawMapView android:id="@+id/mapView" android:layout_width="match_parent" android:layout_height="match_parent" mapbox:center_latitude="-36.841362" mapbox:center_longitude="174.851110" mapbox:style_url="@string/style_mapbox_streets" mapbox:zoom="10"/> </RelativeLayout> Finally, as a result, you should get something like this: And You should take into account some "special cases", for example if all points of path is outside current view of map, there is no lines on it, even line should cross view of map and should be visible. 2) (better way) create and publish map with your additional lines and custom style for them (especially take a look at "Line patterns with Images" sections). You can use Mapbox Studio for this. And in this approach all "special cases" and performance issues is solved on Mabpox side. Gidday Andriy, shortly after posting the question I had last minute unexpected business travel so I apologize for not getting back to you sooner. Your answer is just what I needed. Thank you so much for the help. Thank You,@Kevin :) Hope answer helps You. Does this also work when panning and zooming the map? Here, onDraw() and dispatchDraw() are called only once @j3App It works: polylines will be in correct positions, the size of line pattern has not changed. If I understand correctly, you are trying to add a diamond shape to the map (user isn't drawing the shape)? If this is the case, you have a few options: Use Polygon, simply add the list of points and it will draw the shape (in this case, a diamond). This would be the easiest, but I assume you already tried and it doesn't work for you. List<LatLng> polygon = new ArrayList<>(); polygon.add(<LatLng Point 1>); polygon.add(<LatLng Point 2>); ... mapboxMap.addPolygon(new PolygonOptions() .addAll(polygon) .fillColor(Color.parseColor("#3bb2d0"))); Add a Fill layer using the new Style API introduced in 4.2.0 (still in beta). Doing this will first require you to create a GeoJSON object with points and then to add it to the map. The closest example I have to doing this would be this example, found in the demo app. Use onDraw which would essential just translate the canvas to a GeoJSON object and add as a layer like explained in step 2. I'd only recommend this if you are having the user draw shapes during runtime, in this case the coordinates would be uncertain. I'll edit this answer if you are looking for something different. thanks for the reply. Im not trying to draw a diamond polygon. Im trying to draw a polygon which has a border made of small diamonds instead of a simple line. See the image to clarify my question. Option 3 is sort of what I am trying to do but have been unable to achieve as anything i draw on the canvas is overriden once the map renders async from the ondraw event. I also dont think converting the canvas to geojson will work as the geojson cant define the complex polygon diamonds. did you have any further suggestions? I would love to switch to mapbox as the custom maps are way better, but as I cant draw the shapes I need Im stuck with googlemaps until i find a solution. Really appreciate the help. do you know if this possible or not? Would like to move on if its not possible. Thanks again for your help. "do you know if this possible or not?" - it is possible via several ways.
common-pile/stackexchange_filtered
Why is numeric_limits<int>::max() > numeric_limits<int>::infinity()? I was reading Setting an int to Infinity in C++. I understand that when one needs true infinity, one is supposed to use numeric_limits<float>::infinity(); I guess the rationale behind it is that usually integral types have no values designated for representing special states like NaN, Inf, etc. like IEEE 754 floats do (again C++ doesn't mandate neither - int & float used are left to the implementation); but still it's misleading that max > infinity for a given type. I'm trying to understand the rationale behind this call in the standard. If having infinity doesn't make sense for a type, then shouldn't it be disallowed instead of having a flag to be checked for its validity? Are you sure that numeric_limits<int>::has_infinity is true? If it's not, then the standard doesn't require infinity() to be meaningful. http://en.cppreference.com/w/cpp/types/numeric_limits/has_infinity Yep, like I mentioned in the question, one cannot represent infinity using an integer value because of its inherent nature, but still a Joe coder not knowing has_infinity() trying out the above line will shoot his foot nice and square; it seems unintuitive. Most answers say the same thing mentioned in the question, but not the actual rationale; say why did the standards committee, instead of giving a has_infinity(), didn't opt for not defining infinity() for such types? @legends2k: It is not has_infinity(), it is just has_infinity. It is not a function. @legends2k: I agree with you. If this function doesn't return any meaningful value, then it should not exist, or at least require the implementation to reject the code on using this function. That is not that difficult. With the help of some metaprograming, the implementation could detect meaningless usage. But then I think such techniques was discovered later. @Nawaz Oh yes, just noticed that has_infinity isn't a function, thanks! And yes again, one could've avoided it with SFINAE. “Integral types are finite”, as are floating-point types—floats trade precision for range, and merely have additional special representations for positive and negative infinity, signed zero, and NaN. @JonPurdy Agreed, fixed it in the question, thanks! The function numeric_limits<T>::infinity() makes sense for those T for which numeric_limits<T>::has_infinity returns true. In case of T=int, it returns false. So that comparison doesn't make sense, because numeric_limits<int>::infinity() does not return any meaningful value to compare with. In fact, the standard requires non-meaningful values to be 0 or false. Why are we even allowed to make comparisons that don't make sense? Why not fail at compile time if someone tries to use numeric_limits<int>::infinity()? If you read e.g. this reference you will see a table showing infinity to be zero for integer types. That's because integer types in C++ can't, by definition, be infinite. Suppose, conversely, the standard did reserve some value to represent inifity, and that numeric_limits<int>::infinity() > numeric_limits<int>::max(). That means that there would be some value of int which is greater than max(), that is, some representable value of int is greater than the greatest representable value of int. Clearly, whichever way the Standard specifies, some natural understanding is violated. Either inifinity() <= max(), or there exists x such that int(x) > max(). The Standard must choose which rule of nature to violate. I believe they chose wisely. There is a third option: require the implementation to reject the code which uses numeric_limits<int>::infinity() - which is possible with a bit of metaprogramming. @Robᵩ This seems to be right; although I'd say, like Nawaz suggested, this could've been avoided for types which don't have an infinity representation using SFINAE, but I guess these functions were defined earlier than meta-programming's advent. Also this shows that the language projects what the machine does as is, which, in my opinion, isn't great because later suppose some novel machine's architecture does support infinity for integral types, then its has_infinity would be true, and hence it's the programmer who has to add another exception to his mental model. This is exactly what makes C++ expert-friendly and complex for the Joe coder. numeric_limits<int>::infinity() returns the representation of positive infinity, if available. In case of integers, positive infinity does not exists: cout << "int has infinity: " << numeric_limits<int>::has_infinity << endl; prints int has infinity: false
common-pile/stackexchange_filtered
Pin not showing on Mapkit - obj-c I'm a newbie to ios dev. I tried to add pin annotations on map using mapkit. However, after tried the most basic methods, it still didn't show up, either that's a simple pin, or a custom annotationview. There is no error message, it's just the pin won't show up in the map. Here's my code: - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.mapView.delegate = self; NSLog(@"Custom Annotations start."); // Custom Annotations. CLLocationCoordinate2D bryanParkCoordinates = CLLocationCoordinate2DMake(37.785834, -122.406417); MyCustomAnnotation *bryanParkAnnotation = [[MyCustomAnnotation alloc]initWithTitle:@"Bryant Park" Location:bryanParkCoordinates]; [self.mapView addAnnotation:bryanParkAnnotation]; // Simple pin. MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init]; [annotation setCoordinate:bryanParkCoordinates]; [annotation setTitle:@"Title"]; [self.mapView addAnnotation:annotation]; // Another try. CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(37.330713, -121.894348); MKCoordinateSpan span = MKCoordinateSpanMake(0.1, 0.1); MKCoordinateRegion region = {coord, span}; MKPointAnnotation *newannotation = [[MKPointAnnotation alloc] init]; [newannotation setCoordinate:coord]; [self.mapView setRegion:region]; [self.mapView addAnnotation:annotation]; // On your location. MKPointAnnotation *point = [[MKPointAnnotation alloc] init]; point.coordinate = bryanParkCoordinates; point.title = @"Where am I?"; point.subtitle = @"I'm here!!!"; [self.mapView addAnnotation:point]; } -(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation { if([annotation isKindOfClass:[MyCustomAnnotation class]]) { MyCustomAnnotation *myLocation = (MyCustomAnnotation *)annotation; MKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"MyCustomAnnotation"]; if(annotationView == nil) annotationView = myLocation.annotationView; else annotationView.annotation = annotation; return annotationView; } else{ MKPinAnnotationView *pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"DETAILPIN_ID"]; [pinView setAnimatesDrop:YES]; [pinView setCanShowCallout:NO]; return pinView; } } If I just want a simple pin on map, just adding those lines // Simple pin. MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init]; [annotation setCoordinate:bryanParkCoordinates]; [annotation setTitle:@"Title"]; [self.mapView addAnnotation:annotation]; should be enough? Is there other things that I could have missed? Like adding other delegate or something else other than adding those simple codes in 'viewDidLoad'? Thanks so much! Managing Annotation Views You should implement this delegate method and create a view for the annotation and return it. basically when you add an annotation this delegates method will get called and you have to create the view for that annotation within this delegate method - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.mapView.delegate = self; NSLog(@"Custom Annotations start."); // Custom Annotations. CLLocationCoordinate2D bryanParkCoordinates = CLLocationCoordinate2DMake(37.785834, -122.406417); CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(37.330713, -121.894348); MKCoordinateSpan span = MKCoordinateSpanMake(0.1, 0.1); MKCoordinateRegion region = {coord, span}; [self.mapView setRegion:region]; [self.mapView addAnnotation:annotation]; MKPointAnnotation *point = [[MKPointAnnotation alloc] init]; point.coordinate = bryanParkCoordinates; point.title = @"Where am I?"; point.subtitle = @"I'm here!!!"; [self.mapView addAnnotation:point]; } Thanks! Could you give me a short example of how this function will be like for the simple MKPointAnnotation? Sincerely appreciate it! So this function is called in the viewDidLoad method? no . thisis a MKMapViewDelegate method . You need to first confirm to the delegate. then implement the method. one thing you need to understand is what you have added now is an MKPointAnnotation and what you want to see on the map is MKAnnotationView. both are different . annottation is a datasource with which you need to create a MKAnnotationView which is a subclass of UIView Thanks, I edited the code, added the '(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation' method, is that the one you are talking about? But this one still didn't work just try out this link . link Thanks, but sorry I'm still confused, I didn't see it added any MKMapViewDelegate - like method, it only added the annotation, and it's in swift.. sorry.. But I appreciate your help a lot! @Qiaofei. can you check my updated code. just ignore the delegate case simply add this in your viewdidload method Thanks, I tried your code, it still didn't show up, but now I think the problem is the whole mapview didn't update any changes that I made in the code. Because I disabled the location manager, but the user location is still showing up in the map. Do you know any possible reason that the whole mapview still stays in the original situation? Thanks! Also I notice there is an error in console: Could not inset legal attribution from corner 4 Try the following code: - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation { if (annotation == mapView.userLocation) return nil; static NSString* Identifier = @"PinAnnotationIdentifier"; MKPinAnnotationView* pinView; pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:Identifier]; if (pinView == nil) { pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:Identifier]; pinView.canShowCallout = YES; return pinView; } pinView.annotation = annotation; return pinView; } Don't forget to add <MKMapViewDelegate> to your @interface section. @interface YourViewController () <MKMapViewDelegate> Thanks Kosuke! Thanks, I added the Delegate method and updated mine using your code, it still didn't show up, but now I think the problem is the whole mapview didn't update any changes that I made in the code. Because I disabled the location manager, but the user location is still showing up in the map. Do you know any possible reason that the whole mapview still stays in the original situation? Thanks! Also I notice there is an error in console: Could not inset legal attribution from corner 4
common-pile/stackexchange_filtered
getSymbols.google can only get data up to 9/5/2017 I used this function in quantmod tool box to download daily stock data. However, recently, I found that it can download data only up to 9/5. Does anyone else have this issue? Here are my codes: library(quantmod) getSymbols.google("AAPL", globalenv(), return.class = "data.frame", from = Sys.Date()-100, to = Sys.Date()) Today, it is 9/8. However, I cannot see data on 9/6 and 9/7. Using the version of quantmod on github I am getting up to Sep 7th using getSymbols("AAPL") Strange. src = "yahoo" provides till current date - 1.
common-pile/stackexchange_filtered
UnsupportedOperationException while removing elements from list I have two strings having comma separated values, say one having numbers from 1 to 10 and another having prime numbers. I want to remove prime numbers from numbers . Here's my code snippet: String numbers = "1,2,3,4,5,6,7,8,9,10"; String prime = "2,3,5,7"; List<String> numList = Arrays.asList(numbers.split(",")); numList.removeAll(Arrays.asList(prime.split(","))); I'm getting UnsupportedOperationException. Any help would be appreciated. Try to use this:- List<String> numList = new ArrayList<>(Arrays.asList(numbers.split(","))); If you look at the docs:- UnsupportedOperationException - if the removeAll operation is not supported by this list Arrays.asList returns a fixed-size list, and hence, you get the UnsupportedOperationException when you try to perform the remove operation on that.
common-pile/stackexchange_filtered
Object not found! wordpress I locally setup a wordpress project by using a backup and the sub pages are not working in the project only giving the error message below eg- when i tried to go to the about us page it gives the below error in the browser Object not found! The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again. If you think this is a server error, please contact the webmaster. Error 404 localhost Apache/2.4.41 (Win64) OpenSSL/1.1.1c PHP/7.2.26 You can able to login admin dashboard? It's look like server error, Please confirm that you have correctly setup vertual host. Here is code to create virtual host. On Xampp: <VirtualHost wp.local:80> DocumentRoot "D:\dev\wp" ServerName wp.local ServerAlias wp.local <Directory "D:\dev\wp"> DirectoryIndex index.php Require all granted Allowoverride All Order allow,deny Allow from all </Directory> </VirtualHost>
common-pile/stackexchange_filtered
Push to Github Fails under Windows I was unable to push to github from the windows (DOS) command prompt but from bash it worked. If I ran git push origin master I got: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. If I ran ssh-add I got: Could not open a connection to your authentication agent. Everything worked fine under bash (msysgit) - how could this be? The solution was to realise that ssh (under windows) was looking for files called id_rsa in my %USEPROFILE%\.ssh folder but the files there were names github_rsa. Solution: rename %USERPROFILE%\.ssh\github_rsa id_rsa rename %USERPROFILE%\.ssh\github_rsa.pub id_rsa.pub Hey presto, pushing and pulling now works without entering bash! Possible explanation: a previous install of github for windows generated the github_rsa files. Weirdly, after the rename git push still works under bash!
common-pile/stackexchange_filtered
How to include display:block in css code that includes pseudo element 'before' I'm using the pseudo element :before in a side menu to incorporate an indented icon and text and wish to use display:block so that the links are easy to click. Adding .sidemenu-nav li a {display:block;} or slight variants of it just creates unwelcome line breaks. Can display:block be made to work or is there a better alternative? .sidemenu-nav { width:15em; border-top:#cc9999 1px solid; padding-left:0; font-size:0.8em; } .sidemenu-nav li:before { content:url(../a/img/n1.gif)' '; } .sidemenu-nav li {list-style-type:none; margin-left:0; line-height:2.6em; border-bottom:#cc9999 1px solid; } .sidemenu-nav ul {padding-left:0; margin-left:0;} li.extra-indent:before { content:url(../a/img/n2.gif)' ';} li.extra-indent {margin-left:0.9em;} .sidemenu-nav li a:link, a:visited { color: #0033cc; text-decoration: none;} .sidemenu-nav li a:hover, a:active { color: #af247c; text-decoration:underline;} .sidemenu-nav li:hover { background-color: #fcfcfc; } <ul class="sidemenu-nav"> <li><a href="../books.php">Publications</a></li> <li class="extra-indent"><a href="../book1.php">BookName</a></li> <li><a href="../trustees.php">Trustees</a></li> </ul> ::before is a pseudo-element, not a pseudo-class. It's not really clear to me what you are trying to do. If you're using an image why not just make it a background image of the link? Thanks for the correction re pseudo. I'm using an indented icon and link within a menu. I don't see how that can be coded as a background image. If you wish to see it in action, visit www.arshavidya.org.uk/aboutus.php and look at the side menu. Have you tried inline-block? Yes, with no success. You don't need to use a pseudo-element here as you are using an actual image. All that is need is to use the image as a background to the link with a little extra padding on the left. Then set the link to display:block and the whole thing is now clickable as the image is part of the link. .sidemenu-nav { width: 15em; border-top: #cc9999 1px solid; padding-left: 0; font-size: 0.8em; margin-left: 25px; } .sidemenu-nav li a { padding-left: 10px; background-image: url(http://www.arshavidya.org.uk/a/img/n1.gif); background-repeat: no-repeat; background-position: center left; display: block; } .sidemenu-nav li { list-style-type: none; margin-left: 0; line-height: 2.6em; border-bottom: #cc9999 1px solid; } .sidemenu-nav ul { padding-left: 0; margin-left: 0; } li.extra-indent a { margin-left: 0.9em; background-image: url(http://www.arshavidya.org.uk/a/img/n2.gif); } .sidemenu-nav li a:link, a:visited { color: #0033cc; text-decoration: none; } .sidemenu-nav li a:hover, a:active { color: #af247c; text-decoration: underline; } .sidemenu-nav li:hover { background-color: #fcfcfc; } <ul class="sidemenu-nav"> <li><a href="../books.php">Publications</a> </li> <li class="extra-indent"><a href="../book1.php">BookName</a> </li> <li><a href="../trustees.php">Trustees</a> </li> </ul> Happy to help. If this helped please consider upvoting &/or marking as the selected answer when permitted....it's customary. And welcome to Stack Overflow. Very glad to up vote and/or mark as the selected answer, but I don't see any means of doing so. Where can I find that, please? Is there a tick box I've missed or ...? I believe that the 'Accepted' option only becomes available after a delay. 15 minutes I think. Adding li.extra-indent { margin-left: 0.9em;} as a separate line in the css indents the rules as well as the sub-heading, which is preferable for me.
common-pile/stackexchange_filtered
How to open first mail of user in user Lotus Notes mail file (nsf file) via Serverside Javascript When a user logons after then I would like to create a link to reach the first mail of user in XPages via ServerSide Javascript. When the user clicks the links which opens the first mail. is there any way to make this work? Regards Cumhur Ata UPDATE: var mailDb:NotesDatabase = session.getDatabase(database.getServer(), mailFile); var mailView:NotesView = mailDb.getView("($Inbox)"); var unreadEntries:NotesViewEntryCollection = mailView.getAllUnreadEntries(); if (unreadEntries.getCount()>0) { var veUnread:NotesViewEntry = unreadEntries.getFirstEntry(); var dt:NotesDateTime = veUnread.getDocument().getItemValueDateTimeArray("DeliveredDate").elementAt(0) for (var i=0; i<unreadEntries.getCount() && i<3; i++) { //I can get field values. Find the DeliveredDate below.. var dt:NotesDateTime = veUnread.getDocument().getItemValueDateTimeArray("DeliveredDate").elementAt(0) //I think Where I need to create DocLink is here but not succeded yet :( var veUnread:NotesViewEntry = unreadEntries.getNextEntry(veUnread); } } Do you mean open in NotesClient, in WebMail or as Document Datasource? in web mail like opening a document in web browser. It is indeed possible. What have you tried so far? Please find what i have tried so far. I updated my question Make it easier. Simply construct the URL from @MailDbName, and /($Inbox)/$first which will open the first document in the inbox. See the URL Command documentation for details It will however not take into account if the mail is read or not
common-pile/stackexchange_filtered
Can I license a program containing data from a video game? Let's say I want to release a program, written in Java, that is a sort of encyclopedia containing data about a game. This program would contain images from the game, obtained via screenshot, and some of them processed in a program like GIMP. The purpose of these images would be to illustrate about stuff that exists in the game, and not to be a part of the interface of the program (like the appearance of the interface's controls). I would like to license this program with the MIT License (Expat). Is it possible? If not, can I release these images in some other way and make my program load them from the outside? Searching for the answer on Google was nigh impossible (or I don't know the correct search terms). These images would be clearly copyrighted. But would it be fair for you to use them nonetheless? At least in the US there is something called "Fair use". For example, this Wikipedia image is a low res image of a game box and contains this fair use related statement: This image is cover art for a video game, and its copyright is most likely held by the game's publisher or developer. It is believed that the use of low-resolution images of game cover art to visually identify the game in question on the English Wikipedia, hosted on servers in the United States by the non-profit Wikimedia Foundation, constitutes fair use under United States copyright law. Other uses of this image may be copyright infringement. For more information, see Wikipedia:Non-free content. [...] The question is therefore whether or not your planned usage would be fair use or not. A few illustrative images may be. A database with 100 or 1000 screenshots may not and therefore you would be "infringing" of the game developers/authors/owner copyrights. Your best course of action is to ask for an explicit written permission to the game developer. See also Am I allowed to use these gifs for my game?
common-pile/stackexchange_filtered
React to git update I'm trying to create a language server with the language server protocol. I'm currently testing it on visual studio code. I can react to changes in the code by listening to the textdocument/didChange update. However, if I do a git pull in the directory I don't receive any notification of all the modified files, except the actually opened file. I'm confused because I thought that the whole workspace is watched by visual studio. Should I listen to another event for this kind of change?
common-pile/stackexchange_filtered
Linq OR Operator? I have Dogs and Cats classes derived from Animal. I want to find the first black colored animal. I'm currently doing it as follows: Animal blackAnimal = dogs.FirstOrDefault(d => d.Color == "Black"); if (blackAnimal == null) { blackAnimal = cats.FirstOrDefault(c => c.Color == "Black"); } I want to be able to do it in the same statement - such that find the first black dog, but if there's no black colored dog, find the first black colored cat. Notice that the Color property is not from Animal, but rather independent properties on Dog and Cat. shouldn't the Color property be in Animal class? Diego Torres answer is perfect but I will provide another way to do it which can be applicable where his solution will not work: Animal blackAnimal = (Animal)dogs.FirstOrDefault(d => d.Color == "Black") ?? cats.FirstOrDefault(c => c.Color == "Black"); Not allowing me to do this either - Operator '??' cannot be applied to operands of type 'Dog' and 'Cat'. This should be dogs.FirstOrDefault(d => d.Color == "Black") as Animal ?? cats.FirstOrDefault(c => c.Color == "Black") as Animal; @Gengis yes sorry, it has to be casted otherwise it will not be able to find a best match This works well, I'm going to select your answer. Thanks! @GengisKhan Does this answer your question? It's a copy of what you already have in your question. @CamiloTerevinto did you see the question? With Concat: dogs .Cast<Animal>() .Concat(cats) .FirstOrDefault(d => d.Color == "Black"); It will enumerate the second collection after the first. Since you are searching on different properties then you can do var result = dogs.FirstOrDefault(x => x.Color1 == "Black") as Animal ?? cats.FirstOrDefault(x => x.Color2 == "Black"); This might require Cast in case dogs and cats are collections of the child classes and not the Animal class. Yes, currently it's not allowing me to do it as Diego suggested. @GengisKhan right, I forgot about the different types, now I have updated and tested my answer. I forgot another important point, which makes this a little more complicated. Color is not a property of Animal, but both Dog and Cat have it. As a reason, the above solution doesn't work. @GengisKhan That doesn't make any sense, can't you just add it to Animal? Or use an interface? I know, but not all animals have color property, so it's only added to the ones where it's required. Doesn't make much sense to me either, but that's how it is. You will need to .Cast it all if the collections are not of the base type. Given that Color is not a property of Animal, you will have to do something like this: var animal = dogs // check for dogs .Where(d => d.Color == "Black").Cast<Animal>() // check for cats .Concat(cats.Where(c => c.Color == "Black").Cast<Animal>()) // get the first .FirstOrDefault();
common-pile/stackexchange_filtered
Is cp -au / cp --archive --update contradictory? I want to update a directory on a backup disk with new content added to the source, and of course rsync is too slow. cp -a does the trick but is a bulldozer; cp -u should leave existing files alone. However if I inspect what they're doing together (cp -auv) I see plenty of files being copied to the directory which AFAIK were already there. Looking at the cp manual the two options don't seem in contradiction. So I'm probably wrong, and cp is doing the right thing. Some excess work doesn't matter so much anyway because cp is so fast. Or maybe they are contradictory in practice, because there is always some small difference by -a standards between source and destination? I wouldn't be the first confused by -u. ‘--archive’ Preserve as much as possible of the structure and attributes of the original files in the copy (but do not attempt to preserve internal directory structure; i.e., ‘ls -U’ may list the entries in a copied directory in a different order). Try to preserve SELinux security context and extended attributes (xattr), but ignore any failure to do that and print no corresponding diagnostic. Equivalent to -dR --preserve=all with the reduced diagnostics. ‘--update’ Do not copy a non-directory that has an existing destination with the same or newer modification time. If time stamps are being preserved, the comparison is to the source time stamp truncated to the resolutions of the destination file system and of the system calls used to update time stamps; this avoids duplicate work if several ‘cp -pu’ commands are executed with the same source and destination. If --preserve=links is also specified (like with ‘cp -au’ for example), that will take precedence. Consequently, depending on the order that files are processed from the source, newer files in the destination may be replaced, to mirror hard links in the source.
common-pile/stackexchange_filtered
Passing numpy string array to C using Swig my C program needs a char** input which I store in python as a numpy object array of strings. a = np.empty(2, dtype=object) a[0] = 'hi you' a[1] = 'goodbye' What is the correct way to pass this to my C program considering that numpy.i only defines typemaps for char* arrays? So it is doable, but you need to convert the numpy object array to a list of python strings with a.tolist(). Then you can pass it to the C code with the following tutorial code as a char ** http://www.swig.org/Doc1.3/Python.html#Python_nn59 Edit: Turned out to be a real pain in the *** since the example above is for Python 2 but gives useless error messages in Python 3. Python 3 moved to unicode strings and I had to do some doc reading to make it work. Here is the python 3 equivalent of the above example. // This tells SWIG to treat char ** as a special case %typemap(in) char ** { /* Check if is a list */ if (PyList_Check($input)) { int size = PyList_Size($input); Py_ssize_t i = 0; $1 = (char **) malloc((size+1)*sizeof(char *)); for (i = 0; i < size; i++) { PyObject *o = PyList_GetItem($input,i); if (PyUnicode_Check(o)) $1[i] = PyUnicode_AsUTF8(PyList_GetItem($input,i)); else { //PyErr_SetString(PyExc_TypeError,"list must contain strings"); PyErr_Format(PyExc_TypeError, "list must contain strings. %d/%d element was not string.", i, size); free($1); return NULL; } } $1[i] = 0; } else { PyErr_SetString(PyExc_TypeError,"not a list"); return NULL; } } // This cleans up the char ** array we malloc'd before the function call %typemap(freearg) char ** { free((char *) $1); } Essentially just had to replace PyString_Check with PyUnicode_Check and PyString_AsString with PyUnicode_AsUTF8 (introduced in python 3.3 and later) That's impossibru AFAIK, and as far as the docs go: Some data types are not yet supported, like boolean arrays and string arrays. You'll either have to write an intermediary function that takes the strings as separate arguments, put them in an array and pass that to your C function, or work out another way of doing things
common-pile/stackexchange_filtered
How to schedule a work in Azure Batch from Logic App? everyone. Is there any way to schedule a work on Azure Batch from Logic App? I would like to process a file by its insertion event in Blob Storage. If you know other methodologies to do that, I will appreciate your help. :-) Thank you! Welcome to Stack overflow :) I am not a down voter but I can definitely see that this question is very open ended, see here: https://stackoverflow.com/help/how-to-ask also try to co-relate how and at least provide links to various tools and scenarios in play here. Hope, this helps in better formatting this question so that we can help you. From your description, you don't need Azure Batch and logic app doesn't support Azure Batch. As for your requirement, you could just use Blob connector to implement. There is a trigger: When a blob is added or modified (properties only), I suppose this is what you want, after the trigger you could add actions to process your blob file.
common-pile/stackexchange_filtered
every button click display panelGroup component(it contains 3 components) every button click display panelGroup component(it contains 3 components).how to do it using jsf or richfaces <h:form id="autoId"> <h:panelGroup id="pg1" columns="3" > <rich:autocomplete mode="client" minChars="1" autofill="false" selectFirst="false" autocompleteMethod="#{autocompleteBean.autocomplete}" autocompleteList="#{autocompleteBean.suggestions}" /> <h:inputText value=""/> <h:inputText value=""/> </h:panelGroup> <a4j:commandButton value="show pg" /> </h:form> when clicking on commanButton i like to show panelGroup how to do it Could you provide a piece of code and where you got so far? Add rendered attribute in h:panelGroup (false on start) and render attribute in a4j:commandButton. See answer for similar question (in you case it is button, in answer it is check box, but mechanism is the same).
common-pile/stackexchange_filtered
Setup Weylus using USB tethering Being behind corporate firewall, I need to make Weylus works via USB Tethering. The README says it's possible but doe not provide step-by-step instruction. How can I have it working via USB Tethering? I don't know where to start. I'm on Ubuntu 20.10, Linux 5.8 Did it. Here are the steps for future readers: Connect your tablet to your PC via the USB cable On your Android tablet, use "USB for file transfer" mode Enable USB debugging on your tablet (see here for instructions) Install adb on your system (on Ubuntu, run sudo apt-get install adb) Reverse the port you are going to use, so that your tablet will connect to your PC. The first port is the webserver, the second port is the websocket: adb reverse tcp:1701 tcp:1701 adb reverse tcp:9001 tcp:9001 Run Wyelus and start the server On your tablet, connect to localhost:1701. Use localhost and not an IP address. I think the answer that I added below might suit most users better because it doesn't involve adb. You may want to consider marking it as the answer. Note: The other answer involves using adb, but actually there is no need to use adb at all or any other tools. This is with Android 12. Here are the steps: Connect your tablet to your PC via the USB cable. On your tablet USB settings select "USB Tethering" (as opposed to "USB for file transfer") On your linux machine, use ifconfig to find the ip address for your PC on the USB tether network, it should look something like this (in this case the ip address is <IP_ADDRESS>): usb0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet <IP_ADDRESS> netmask <IP_ADDRESS> broadcast <IP_ADDRESS> Start Weylus On your tablet connect to the ip address from above and port 1701, for example <IP_ADDRESS>:1701 Pro-tip: if your tablet is connected via usb0, you can get Weylus to automatically display the QR code for the correct ip address with weylus --bind-address $(ifconfig usb0 | grep -oP 'inet \K[^ ]+').
common-pile/stackexchange_filtered
Use a For Loop to alternate a set of ID's in a SQL query I have a query calculating some gambling statistics for just one 'team_id' but I would like to calculate for all team_id's to create reports/graphs. I do know some python and wondering if a "for loop" would be most efficient for this. I will be creating many queries similar to this one but need to add the team_id in the Select portion(next to ATS_Status) of the query and include every team. Any suggestions would be great. select ATS_Status, round((cast(count(*) as float) /75*100),2) as ATS_Percentage from (select (case when cast(g2.pts as float)-cast(g1.pts as float) < cast(spread2 as float) then 'Covered' when cast(g2.pts as float)-cast(g1.pts as float) = cast(spread2 as float) then 'Push' else 'Loss' end) as ATS_Status from nba_games_all g1 left outer join nba_games_all g2 on g1.game_id = g2.game_id and g1.team_id =g2.a_team_id left join nba_teams_all t on t.team_id=g1.a_team_id left join nba_betting_spread bs on g1.game_id = bs.game_id and book_name = 'Bovada' left join nba_betting_money_line ml on g1.game_id = ml.game_id and ml.book_name = 'Bovada' where g1.team_id = '1610612759' and g1.season_year = '2017' and g1.season_type = 'Regular Season' and g1.game_date >= Convert(datetime, '2017-11-02'))a group by ATS_Status Which DBMS product are you using? "SQL" is just a query language used by all relational databases, not the name of a specific database product. Please add a tag for the database product you are using. Why should I tag my DBMS You can use team_id in the group by and remove the particular condition g1.team_id = '1610612759' as follows: select ATS_Status, team_id, round((cast(count(*) as float) /75*100),2) as ATS_Percentage from (select (case when cast(g2.pts as float)-cast(g1.pts as float) < cast(spread2 as float) then 'Covered' when cast(g2.pts as float)-cast(g1.pts as float) = cast(spread2 as float) then 'Push' else 'Loss' end) as ATS_Status, g1.team_id from nba_games_all g1 left outer join nba_games_all g2 on g1.game_id = g2.game_id and g1.team_id =g2.a_team_id left join nba_teams_all t on t.team_id=g1.a_team_id left join nba_betting_spread bs on g1.game_id = bs.game_id and book_name = 'Bovada' left join nba_betting_money_line ml on g1.game_id = ml.game_id and ml.book_name = 'Bovada' where --g1.team_id = '1610612759' g1.season_year = '2017' and g1.season_type = 'Regular Season' and g1.game_date >= Convert(datetime, '2017-11-02'))a group by ATS_Status, team_id thank you, weird but when i copy and paste your edits and code it works but when I change it myself I get error message "The multi-part identifier "g1.team_id" could not be bound." team_id is in 3 different tables, do you know which one it is pulling it from when i paste your code or why I would be getting that error? Have you given correct alias name before column name? yes I was using 'g1.team_id' and its not liking it, I pasted your code with just' team_id' and no issue. I really want to group by 'abbreviation' which is from 'nba_teams_all' but its not liking that either Ok. In outer query, you just have to use team_id. Without alias and in subquery we have to use it with alias.
common-pile/stackexchange_filtered
Viewport width having no effect? Quick Overview of my Problem: I made a site for mobile, it looks great. Move on tablet it looks horrible. As in it's like 5x stretched out from left and right. Imagine your face stretched horizontally up to 4ft. Research and Possible Solution I had a feeling i could viewport. As I thought, if i could just SCALE the layout instead of having browser provide more width and then my layout spreading to accommodate. Article told me that if i set viewport meta tag width=300 or anything custom then browser scales whole page to fit the current viewport's actual width so 300px would be covering 1200px, at least that's what my impression was. However, it DIDN'T work. No matter what viewport settings I do they appear to have no effect on scaling. What i want I want my page to scale up. I don't want to specify every border width in em units than create dozen media query checkpoints to increase font size. Especially since my layout remains the same only it needs to scale up. If i was going after different layouts then obviously i'd've used media queries. I've tried this: <meta name="viewport" content="width=300"> There is such a thing as viewport units. vh and vw are two examples. vh stands for Viewport Height and vw stands for Viewport Width. The value in front is a percentage of the viewport. So 50vw means 50% of the viewport's width. Example fiddle: https://jsfiddle.net/Ln229jmj/ how would that solve this. I know about them but i couldn't think of a way that would solve this It scales with your screen. If you resize the output window in the fiddle, you'll notice the text scales and the box scales. oh i see, but that again requires me to do over all values in this format 1.3, 1.34,1.44, 1.932. And i can't be precise like 15px 30px. By precise i mean granularity. 1.3vw and 1.4vw have huge difference in them. i got it working check out my answer I solved it using some javascript first add (i'm using jade) meta(id="myViewport", name="viewport", content="width=device-width") Now window.innerWidth will give correct browser width and not some arbitrary number set by browser like 960 which was being reported by chrome on 360 width phone and 2100+ tablet. Now just check if screen is wide then limit the viewport's width that way browser will scale it up so, for my tablet, 500 pixels will take up 2100 pixels. if (window.innerWidth > 450) { var mvp = document.getElementById('myViewport'); mvp.setAttribute('content','width=500'); } //- first set device width so window.innerwidth shows actual width then change accordingly.
common-pile/stackexchange_filtered
Why does LiquidHaskell fail to take guard into account? I am following the Liquid Haskell tutorial: http://ucsd-progsys.github.io/liquidhaskell-tutorial/04-poly.html and this example fails: module Test2 where import Data.Vector import Prelude hiding (length) vectorSum :: Vector Int -> Int vectorSum vec = go 0 0 where go acc i | i < length vec = go (acc + (vec ! i)) (i + 1) | otherwise = acc with the following error: Error: Liquid Type Mismatch 10 | | i < length vec = go (acc + (vec ! i)) (i + 1) ^^^^^^^^^^^^^^^^^ Inferred type VV : {v : GHC.Types.Int | v == acc + ?b} not a subtype of Required type VV : {VV : GHC.Types.Int | VV < acc && VV >= 0} In Context ?b : GHC.Types.Int acc : GHC.Types.Int The question is why? The guard (i < length vec) should ensure that (vec ! i) is safe. This looks like a termination error. Liquid Haskell here seems to assume that acc is the termination metric of go (probably because it's the first Int argument). As such it should always be non-negative and decreasing in each iteration (hence the error message you get). The way to fix this is providing a correct termination metric, which fulfills the above criteria. Here this would be length vec - i and the corresponding signature for go is: {-@ go :: _ -> i:_ -> _ /[length vec - i] @-} or something along those lines. First of all, I don't know which version of LH you were using but I just had the exact same problem. The tutorial states that LiquidHaskell verifies vectorSum – or, to be precise, the safety of the vector accesses vec ! i. The verification works out because LiquidHaskell is able to automatically infer go :: Int -> {v:Int | 0 <= v && v <= sz} -> Int which states that the second parameter i is between 0 and the length of vec (inclusive). LiquidHaskell uses this and the test that i < sz to establish that i is between 0 and (vlen vec) to prove safety. They also state that the tutorial is not in accordance with the current version of LiquidHaskell. It seems that the (refinement-)type inference of LH has changed a bit since the tutorial was written, probably generalizing types more than before, which results in this problem. The problem is NOT that LH doesn't figure out the guard properly. The problem is that it fails to verify the property 0 <= v. The following checks fine with version <IP_ADDRESS> of LH: {-@ LIQUID "--short-names" @-} {-@ LIQUID "--no-termination" @-} {-@ LIQUID "--reflection" @-} import Prelude hiding (length) import Data.Vector {-@ go' :: v:Vector Int -> Int -> {i:Int | i>=0 } ->Int @-} go' :: Vector Int -> Int -> Int -> Int go' vec acc i | i < sz = go' vec (acc + (vec ! i)) (i + 1) | otherwise = acc where sz = length vec vecSum :: Vector Int -> Int vecSum vec = go' vec 0 0 It seems that LH infers thas go is a function in its own right and might be called with an integer smaller than 0 (which it obviously isn't). I am still playing with that example to convince LH of this fact. If anybody had more success on this please leave a comment. EDIT: I found the following paragraph in the same tutorial; It seems that this might have changed: At the call loop 0 n 0 body the parameters lo and hi are instantiated with 0 and n respectively, which, by the way is where the inference engine deduces non-negativity.
common-pile/stackexchange_filtered
How can we apply 3 classes for 1 div at a time? I am trying to apply classes (.text1 .text2 .text3) for one div. How is it possible? In HTML, write it like this : <div class="text1 text2 text3"></div> Demonstration In Javascript, do this : myDiv.className = "text1 text2 text3"; Demonstration You can also use the following selector to target a div that has all 3 classes .text1.text2.text3 { } in css it's like this: .text1.text2.text3 { color: #BADA55; }
common-pile/stackexchange_filtered
I am getting "MongoError: The 'cursor' option is required, except for aggregate with the explain argument" error Due to mongodb version change, i am getting "MongoError: The 'cursor' option is required, except for aggregate with the explain argument" error. I've tried added cursor but still it is giving error. QosAggregator.prototype.aggregatePingsByCheck = function(start, end, callback) { Ping.aggregate( { $match: { timestamp: { $gte: start, $lte: end } } }, { $project: { check: 1, responsive: { $cond: [ { $and: ["$isResponsive"] }, 1, 0] }, time: 1, tags: 1, } }, { $group: { _id: "$check", count: { $sum: 1 }, responsiveness: { $avg: "$responsive" }, responseTime: { $avg: "$time" }, start: { $first: start.valueOf() }, // dunno any other way to set a constant end: { $first: end.valueOf() } } }, callback ).cursor({}); }; can you please tell me what's your mongodb version You appear to be using an old release of Mongoose. Please update that to the latest version as well. Latest release MongoDB versions no have the option to return an aggregate() result as an Array like their used to be. Older mongoose versions relied on this Array and now they understand to use the cursor and convert afterwards. @NarendraChouhan I am using version 3.6.7 as it is old code base project. @shailendrasingh so this is your mongodb version can you check the query in the robomongo, i think your project mongo version would be lower
common-pile/stackexchange_filtered
jquery drop down box font and alignment I am working on this site: http://gitastudents.com/~clarkb/group1/Students.html main css here: http://gitastudents.com/~clarkb/group1/style.css I am unable to change the font color and size on the drop downs. I would like the font to be white not the green that is on the rest of the page. It seems that it is something in the css that isnt set up right but i can't figure out what it is. Also i would like the drop downs to be centered in their respective boxes but i cant get that to work either. Thank you in advance! Bryan Have you considered changing your question title to: "I need you to debug 406 lines of code for me" You're probably having trouble doing it because you need to target those very specifically. The following CSS rule should work: a.ui-selectmenu span{ color:#ffffff; } As for centering the dropdowns, you could use: fieldset{ text-align:center; } I would suggest, however, that you give those fieldset's a class and target the class. I just noticed that you have the dropdowns wrapped in a div...you could modify that div (the one with the class dropdown) giving it a specific width (240px ish) and that should center them (since you've already applied margin: auto to that class). How can I vertically align the boxes too? margin-bottom:auto; margin-top:auto; height:100px; i put that in the div and i didn't work like the horizontal did. There are a couple ways: Use a table and use vertical-align:middle;. 2) Change the containing div (class entryMini) to have display:table-cell; and vertical-align:middle;. Check out this link for a more detailed explanation: http://phrogz.net/css/vertical-align/index.html
common-pile/stackexchange_filtered
Data Attribute Selectors and jQuery I have a group of items with a data attribute that contains an array of categories: <div class="result" data-categories="category-1, category-2, category-3" data-type="logo" data-preview="images/previews/preview.jpg"> I'm having trouble selecting elements WITHOUT the value that I'm passing in, from the data-categories group. $(".media-results .result:not([data-categories*=" + val + "])"); This seems to work ok, but when I change the select element that uses this selector, I get strange, undesirable results(the selector seems to run infinitely and the page keeps hiding and showing elements at random). Any help from anyone? Edit: here is the function that the select passes the value to: allResults.animate({ opacity: 0 }, 500, function(){ console.log("Change triggered. All results hidden."); notSelected.hide(50, function(){ console.log("Unwanted items hidden"); selected.show().animate({ opacity: "1" }, 500); }); }); "array of categories" -> list of categories -- I suspect the issue has nothing to do with the above code, but with the code you're handling the select with. The select only exists to pass a value to the "filter" function, which I've added to the question. I have no trouble getting and passing the value from the select, I am having problems using that value to select the correct elements. You can use filter() elements = $(".media-results .result").filter(function(){ return $(this).data("categories").indexOf(val) == -1 });
common-pile/stackexchange_filtered
Having problems with reagent atom and resert! function Hi guys I'm new at Clojure and ClojureScript... I'm filling out 2 select element ... What I wonna do is update the second select depending on what option the user choose in the first select. This is my code: (ns easy-recipe.components.calculate (:require [reagent.core :as r :refer [atom]] [ajax.core :as ajax] [reagent.session :as session] [easy-recipe.components.common :refer [input select button]] [easy-recipe.bulma.core :refer [horizontal-select horizontal-input-has-addons table columns box]])) (defn handler [request] (session/put! :categories (get-in request [:body :categories])) (session/put! :breads (get-in request [:body :breads])) (session/put! :recipes (get-in request [:body :recipes]))) (defn error-hadler [request] (let [errors {:server-error (get-in request [:body :erros])}] errors)) (defn get-categories-breads-recipes [] (ajax/GET "/api/calculate" {:handler handler :error-hadler error-hadler})) (defn select-fun-wrapper [breads] (fn [e] (let [category_value (-> e .-target .-value)] (reset! breads (filter #(= category_value (str (% :category_id))) (session/get :breads)))))) (defn calculate-page [] (get-categories-breads-recipes) (let [fields (atom {}) categories (atom nil) breads (atom nil) recipe (atom nil)] (fn [] (reset! categories (session/get :categories)) ;(reset! breads (filter #(= 1 (% :category_id)) (session/get :breads))) [:div.container [box [horizontal-select "Category" [select "category" "select" @categories (select-fun-wrapper breads)]] [horizontal-select "Bread" [select "bread" "select" @breads #()]] [horizontal-input-has-addons "Quantity" [input "quantity" "input" :text "" fields] [button "quantity-btn" "button" "Add" #() nil]]] [box [columns [table ["Ingredients" "Quantity"] @recipe] [table ["Product" " "] [["30 Panes" "x"]]]]]]))) As you have noticed the breads reset! is commented... now the "select-fun-wrapper" is working fine, it updates the bread select depening on the category option selected... but if I uncomment that line the "select-fun-wrapper" will stop working (not updating the second select)... I wonna know why does it happend? I can not leave this line commented because right now I have the problem thar the "Bread" select starts empthy... How could I fill the bread atom without using the reset! function? Extra code (if it makes it clear): (ns easy-recipe.bulma.core) (defn horizontal-select [label select] [:div.field.is-horizontal [:div.field-label.is-normal>label.label label] [:div.field-body>div.field.is-narrow>div.control>div.select.is-fullwidth select]]) .... (ns easy-recipe.components.common) (defn select [id class options function] [:select {:id id :class class :on-change function} (for [opt options] ^{:key (opt :id)} [:option {:value (opt :id)} (opt :name)])]) .... I'm not a specialist of session usage, but I would say you should directly the info you retrieved by your ajax request in reagent/atom. I would advice to use global ratom. In your handler function, update the ratom there. In your calculate-page function, deref the ratom in the let binding section. Normally, each time a ratom is update, every component which derefs it should be render again. Also I think that usually local ratom as you proposed should be avoid. Anyway, I don't know if what I proposed will work... i think you should try reagent/with-let
common-pile/stackexchange_filtered
jquery chaining custom events and animations I need to chain events in jquery and i am not sure if i chain them correctly, because i want to trigger a custom event with a animation and if the animation is done i need to trigger another event. this code works, console.log('open is done!') is fired after 5000ms: $.when( // Open $('a').animate({ width: "100%" }, 5000, function() { // Animation complete }) ).done(function() { console.log('open is done!'); $('a.open').trigger('close'); }); but i want to put the animation in another custom event, wait until the event is finished and trigger the other custom event, such as: $.when( // Open $('a').trigger('open') ).done(function() { console.log('open is done!'); $('a.open').trigger('close'); }); $(document).on('open', function(event) { // Open $('a').animate({ width: "100%" }, 5000, function() { // Animation complete }); }); console.log('open is done!') is fired suddenly, how do i have to chain the events correctly? thanks in advance Dirk Try this: $('a').trigger('open') $(document).on('open', function(event) { $('a').animate({ width: "100%" }, 5000, function() { console.log('open is done!'); $('a.open').trigger('close'); }); });
common-pile/stackexchange_filtered
How prove that $AB>AC$ in triangle $ABC$? Point $D$ is chosen inside $\triangle ABC$, and point $E$ on segment $BD$ such that $BD=CE$. Suppose $\angle ABD=\angle ECD=10^{\circ}$, $\angle BAD=40^{\circ}$, and $\angle CED=60^{\circ}$.How prove that $AB>AC$? I have no idea how to do this, can this be proved with simple geometry? Hint: Draw the isosceles triangle $\triangle AFD$ where $F$ is on $AB$, which has common angle $70^\circ$. Find two congruent triangles. Use triangle inequality.
common-pile/stackexchange_filtered
Trigger Clarification Trigger Code: I have created custom field called Expected items in the order object trigger updateorderstatus on OrderItem (after insert,after update) { list<order> updateorder = new list<order>(); set<id>updateorderid = new set<id>(); if(trigger.isinsert) { for(OrderItem ot : trigger.new) { updateorderid.add(ot.OrderId); } } if(trigger.isupdate) { for(OrderItem ot : trigger.new) { updateorderid.add(ot.OrderId); } } updateorder = [select id,Status,Expected_Items__c,(select id from orderitems) from order where id in:updateorderid and Expected_Items__c >0 and Status ='Draft']; for(order orderlst : updateorder) { set<id> orderitemids = new set<id>(); for(orderitem otlst : orderlst.orderitems) { orderitemids.add(otlst.id); } if(orderlst.Expected_Items__c >0 && orderlst.Expected_Items__c !=null) { if(orderlst.Expected_Items__c == orderitemids.size()) { orderlst.status ='Submitted'; } } } if(updateorder.size()> 0) { update updateorder; } } First Case: If the order is inserted with the expected items field value as 2 and add two order products are added then the order status is changed to submitted Second Case: if the order is inserted with the empty field of expected items and add two order products is saved as draft and while editing the order with the expected items field value is changed to two, it is showing error sfdc entity Locked error,This error due to it will check for the first case itself ,expected item value and order item size is equal,it will not going for the Second order Product and update the order status in secondorder product also, How to Overcome this issue according to my Trigger can anyone guide me for the Answer Please anyone guide me for the answer for above trigger should be work in both the scenarios Your code has a number of issues, which I'll outline, and hopefully we can get to the bottom of your problem. trigger updateorderstatus on OrderItem (after insert,after update) { list<order> updateorder = new list<order>(); set<id>updateorderid = new set<id>(); This following mess is completely unnecessary. We'll just iterate over the list in Trigger.new. /* if(trigger.isinsert) { for(OrderItem ot : trigger.new) { updateorderid.add(ot.OrderId); } } if(trigger.isupdate) { for(OrderItem ot : trigger.new) { updateorderid.add(ot.OrderId); } } */ for(OrderItem item: Trigger.new) { updateorderId.add(item.OrderId); } Next, we can clean up and optimize this query in a few ways. First, we know that Status is Draft, so we don't need to query the field. Second, we don't need to query Id unless it's the only field we are querying. Third, we can use an AggreateResult query to keep things simple. /* updateorder = [select id,Status,Expected_Items__c,(select id from orderitems) from order where id in:updateorderid and Expected_Items__c >0 and Status ='Draft']; */ AggregateResult[] orderTally = [SELECT COUNT(Id) sum, SUM(Order.Expected_Items__c) expect, OrderId Id FROM OrderItem WHERE Order.Status = 'Draft' AND Order.Expected_Items__c > 0 AND OrderId = :updateorderId GROUP BY OrderId]; That makes all of the following code useless, because we can now use a trivial loop. /* for(order orderlst : updateorder) { set<id> orderitemids = new set<id>(); for(orderitem otlst : orderlst.orderitems) { orderitemids.add(otlst.id); } if(orderlst.Expected_Items__c >0 && orderlst.Expected_Items__c !=null) { if(orderlst.Expected_Items__c == orderitemids.size()) { orderlst.status ='Submitted'; } } } */ for(AggregateResult ar: orderTally) { if(ar.get('sum') == ar.get('expect')) { updateorder.add(new Order(Id=(Id)ar.get('Id'), Status='Submitted')); } } Finally, there's no point in checking if a list is empty before the DML; it's actually less efficient than just doing it. /* if(updateorder.size()> 0) { */ update updateorder; /* } */ } As another minor note, you should always check for null before you check for a greater-than/less-than comparison when you need to. It wasn't necessary in this case, because we eliminated the code, and because you'd already filtered it out, so that's no longer relevant to this answer. Here's the new, revised version of your trigger: trigger updateorderstatus on OrderItem (after insert,after update) { list<order> updateorder = new list<order>(); set<Id> updateorderId = new Set<Id>(); for(OrderItem item: Trigger.new) { updateorderId.add(item.OrderId); } AggregateResult[] orderTally = [SELECT COUNT(Id) sum, AVG(Order.Expected_Items__c) expect, OrderId Id FROM OrderItem WHERE Order.Status = 'Draft' AND Order.Expected_Items__c > 0 AND OrderId = :updateorderId GROUP BY OrderId]; for(AggregateResult ar: orderTally) { if((Decimal)ar.get('sum') == (Decimal)ar.get('expect')) { updateorder.add(new Order(Id=(Id)ar.get('Id'), Status='Submitted')); } } update updateorder; } Note: there may be another trigger, workflow rule, etc, causing the error, because I have actually tested this in my developer organization. You might need to read some debug logs to figure out why the recursion is happening. Also, this may not work in some cases, for example, where someone deletes line items because they're over the expected value. @user36188 Entity Locked usually means interaction from something else is causing the problem, possibly asynchronous code. You might actually need a locking statement to fix the problem, but it's hard to tell just from what you've posted. As for the AVG question, we need to do this because we need an aggregate function for the query to work, and AVG happens to return the correct value per order. @user36188 Yes, I personally tested this code in my developer org before I posted it. Please feel free to try it for yourself. http://salesforce.stackexchange.com/questions/152332/regarding-trigger-update @sfdcfox can you guide me for the answer @sfdcfox There are a couple lines in your code that need changed. Even though your trigger is defined as AfterInsert and AfterUpdate, you may have some record locking going on. You have if(trigger.isinsert) and if(trigger.isupdate) in your code. Prior to both of these, place an if(trigger.isafter) and see if that doesn't resolve your issue as in: if(trigger.isafter) { if(trigger.isinsert) { for(OrderItem ot : trigger.new) { updateorderid.add(ot.OrderId); } } if(trigger.isupdate) { for(OrderItem ot : trigger.new) { updateorderid.add(ot.OrderId); } } } That's how the above part should be written. You also have this line: orderlst.Expected_Items__c == orderitemids.size() This causes an issue for you that would prevent the insertion of the records initially if the orderiemids.size doesn't match (where you've entered 0 when there actually are 2 order items). This effectively becomes a validation rule. Instead of using it here, I recommend you create a separate validation rule for your page, assuming these records are always entered via a page. If they're not, then you'll want to allow partial success and add records to a list that don't meet this criteria. The other thing to consider, especially in the AfterUpdate trigger, is your entry criteria. You don't appear to be looking to see if these values have changed between trigger.old and trigger.new. In your if statements, there's no comparison or criteria for entry. Perhaps what you want to do is exclude records for update where these two do not match. You need to create the validation rule in Settings|Customize for OrderItem based on the two fields in question. Look in Salesforce Help for validation rules if you don't know how to write them. Give it a try and if you get stuck, post another question telling us where you're having difficulty. While I generally like your answers, this one is just off-base. ☹ @sfdcfox I am strucked , can you guide me @sfdcfox Thanks for the feedback. Happens when you're in a hurry. Have edited and picked up some things of note that you've not covered in your answer. @crmprogdev can you guide me http://salesforce.stackexchange.com/questions/152332/regarding-trigger-update
common-pile/stackexchange_filtered
Is there any way to get Client Id and Secret of UPS without providing payment information We’re creating a UPS connector and wanted to test UPS APIs. Is there a way to get ClientID and secrets without payment details or providing test credit card details to explore sandbox APIs.
common-pile/stackexchange_filtered
How do I read a text file and store it in an array in C programming (values seperated by a comma)? I need help with getting datapoints, x and y values from a txt file into two arrays. Currently, the text file consists of 5 lines like: 0.116 0.118 0.12 0.122 0.124 This is my code: #include <stdio.h> #include <stdlib.h> main(void) { FILE *inp; /* pointer to input file */ double item; int cnt=0,y,d,i; double array[300],swap; /* Prepare files for input */ inp = fopen("testdoc.txt", "r"); /* Read each item */ while ( (fscanf(inp, "%lf", &item) == 1) && (!feof(inp)) ) { array[cnt] = item; cnt++; } for (int i = 0; i < cnt; i++) { printf("%lf\n",array[i]); } printf("The total number of inputs is %d",cnt); fclose(inp); /* Close the files */ return (0); } This only reads the first half of the file, which are the x values. Of which output is 0.116000 0.118000 0.120000 0.122000 The total number of inputs is 4 However, I want to read a text file and store the values in two different arrays for x and y values. The new text file will look like this 0.116,-0.84009 0.118,4.862 0.12,-1.0977 0.122,0.22946 0.124,3.3173 How do i go changing my code above to recognize the Y values after "," sign? And to add both into two arrays at once? Use fgets and then split the string into numbers for example using strtok or sscanf fscanf(inp, "%lf, %lf", &v1, &v2) @MarcoBonelli have tried adding fscanf(inp, "%lf, %lf", &v1, &v2), but still getting compilation error, not sure what is wrong https://pastebin.com/aPG1zwwb Notice that while (!feof(fp)) is always wrong. The feof() serves no purpose here. Whenever the last call to fread() did not fail, feof() returns false I tried compiling your code posted on pastebin and received an error because of a missing bracket in your while statement. That's an easy fix. The larger issue is in the condition of the while loop. fscanf returns the number of input items converted and assigned on each call. When you modified your code to return two values, the condition in the while loop fscanf(inp, "%lf,%lf", &v1,&v2) == 1 would fail and the loop will not be entered. Please modify the while statement to (have included the missing "(" too).. while ( (fscanf(inp, "%lf, %lf", &v1, &v2) == 2) && (!feof(inp)) ) and you should be good to go!!! In addition it would be a good practice to include the return type of int for the main function.
common-pile/stackexchange_filtered
Android: build native GUI app with NDK? independent from the fact if it makes sense or not, if it is a good way to create Android apps or not: for (educational/personal/whatever) reasons I want to create an Android app with graphical user interface in C++ using the NDK. What I found so far are some information about the NDK, how to create native libraries and how to access them out of Java applications. But what I'm really looking for are some information how to create a View and to add graphical user interface elements to that View out of my C++ NDK app. Any ideas and hints how that can be done or where some more information/HOWTOs can be found regarding this? Use http://developer.android.com/reference/android/app/NativeActivity.html. That's the closest you'll get. but you don't have the UI elements in the NDK, you'll have to do it on your own. Requires Android 2.3+. look around for openGL examples. once you get an openGL view into your c++ code you can then render any kind UI of element your self. Juce is a fantastic C++ UI framework that works well on Android. It can be used under the GPL or a paid-for commercial licence. The community is fairly active and the author is very friendly and helpful. I found it relatively easy to build using the NDK tools on Windows. Caveat - it seems Android isn't a high priority platform for them, so some things are missing at time of writing (e.g. support for hardware buttons). Still, in my experience, the UI framework does work very well on Android, and that's what your question is about.
common-pile/stackexchange_filtered
How to change html (jade template) to use *.min js and css in production? I'm using Grunt to compile jade templates to html, uglify/concat js and minimize/concat css. During development I use the combination of connect and watch to serve my front-end and pick up changes automatically. In this I also use the 'source' js and css (and not the uglified/concatted/minified version). Now when I generate the production html, js and css I wonder what the best solution is to change the inclusions of the *.min js and css. To be more specific in my html I e.g. include: a.css b.css c.css a.js b.js for development this is fine, but when generating the production version I want: common-min.css common-min.js Of course I don't want to change the Jade templates manually so I'm looking for a better approach, probably with the use of some Grunt plugin. You can pass data into your template that indicates what environment you are in, and then switch what you're including based on that. // In your route: res.render("index", { env: "development" }); // maybe use NODE_ENV in here? // Then in your jade template: head if env == 'development' link(href="a.css", rel="stylesheet", type="text/css") link(href="b.css", rel="stylesheet", type="text/css") else link(href="min.css", rel="stylesheet", type="text/css") See the Jade docs, and search for "conditionals": http://jade-lang.com/reference While technically true this is not the right way to do it. Instead, use something like voila or mincer or connect-assets. @MartinWawrusch Why not provide an alternate answer? I'd like to see some examples of those other solutions. As for the "right" way, well... that's a matter of opinion. ;) As one of the many examples: https://github.com/pksunkara/voila - takes care of minification, md5 filenames, cdn support and does not require you to have if else blocks in your jade. And regarding the right way: Asset managers are pretty much industry standard after Rails 3 popularized them. Anyways, there are more important things than that ;-) @Marcel What you're looking for is a jade build block processor (or more commonly an HTML build block processor). Unfortunately, for jade there only appears to be a gulp plugin, and not one for grunt. https://www.npmjs.com/package/gulp-processjade This example may suit your needs. // build:js app.min.js script(src='app.js') // /build @Jakerella For each version, a production build is typically run once. So it's more effective to use a build server, task manager, or dependency manager; and less effective to dynamically generate the production version of the HTML page within the server's request handler. Don't use env with res.render() - logic used to build a page for production isn't needed when the entire server is built for production. This production logic also makes the request handler less modular, because it's coupled to the HTML page. Only build servers (ones dedicated to builds) should incorporate build logic. And, while the dynamically generated pages can be cached to avoid the repeated computation in rendering the production version of the HTML page, that's memory overhead that could be avoided.
common-pile/stackexchange_filtered
How to insert multiple list in SQL Server 2008 using c#? My table contains 10 columns. I need to insert a list using c#. I have stored the details of multiple members, for each count its has to insert the consecutive details in the same row. if (members.Count >= 1) { foreach (Members myList in members) { Command.Parameters.Add("first", SqlDbType.VarChar).Value = myList.first; Command.Parameters.Add("last", SqlDbType.VarChar).Value = myList.last; Command.Parameters.Add("age", SqlDbType.VarChar).Value = myList.age; } } Example : for count=1 the table looks like "fName1","lName1",21 for count=2 the table looks like "fName1","lName1",21,"fname2","lName2",21 please help on this. can you show the full code you are using? from your example count=2 do you mean it should insert into col1...col6 and for count=3 it will be col1...col9? If that is true it's a bad design. Each member should be on separate rows @user1671639 give us a pastebin of the code you are using, if you want a good answer. @user1671639 :: Can you post a sample list? I mean to say how the list looks before reaching the foreach loop portion. and based on that list give us how should the tabel will look like. The coding style looks ambiguous. Your foreach loop runs for - 'Members' in members. It makes hard to understand what are trying to do. Let me suggest you to refactor your code and let the class name be 'Member'. You can put members in db with ADO.Net (there are other ways too) as follows - using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand command = connection.CreateCommand()) { //select just schema of the table. command.CommandText = "select * from members where 1=2;"; using (SqlDataAdapter adapter = new SqlDataAdapter(command)) { using (SqlCommandBuilder builder = new SqlCommandBuilder(adapter)) { using (DataTable dt = new DataTable()) { foreach (Member item in memebers) { DataRow row = dt.NewRow(); row.SetField<string>("", item.FirstName); row.SetField<string>("", item.LastName); row.SetField<int>("", item.Age); // // number of SetField should be equal to number of selected columns. // dt.Rows.Add(row); } adapter.Update(dt); } } } } }
common-pile/stackexchange_filtered
Can native signers of one sign language identify other sign languages? I understand multiple spoken languages. If I hear someone speak (or see a writing in) English, I recognize that it's English not Latvian and interpret the sounds (or letters) as it's appropriate for the English language. Is that just as easy in sign languages? If a signer understands multiple sign languages (for example, ASL and Russian SL), can they nearly instantly recognize which one is used by someone else? Or could they misunderstand which language is used and think that some unknown signs are being shown until few sentences in? And can some signers identify some other sign languages that they don't know themselves? In spoken languages it's possible - don't understand French or Italian, but I can somewhat recognize these languages by sounds and flow when I hear them. Can ASL signers similarly see Dutch SL or BSL and understand that it's being used without knowing that language themselves? The reason for asking is that I am learning ASL instead of the local sign language due to accessibility of learning material. I wonder if signers will be able to identify it. If I hear a Russian say [xaraʃo] I can "hear" it as [haɹəʃoʊ] but I have no idea what it means. If I hear Kabardian [ɬ'əq'ʷ], I have no idea at all what I just heard. Are you asking if signers can identify "the same sign" in another language, even though they have no idea what it means? If a signer understands multiple sign languages, can they nearly instantly recognize which one is used by someone else? 2) Can some signers identify some other sign languages that they don't know themselves? @user6726 they're asking whether you can recognize which sign language the other person is using if you are fluent in more than one, and also whether you can recognize sign languages that you aren't fluent in if you're somewhat familiar with them (like I might recognize that Chinese is being spoken, despite not understanding a word). I assume the answer is "sure" to both, but I don't really know. @jknappen-ReinstateMonica I am aware that languages are different. I just don't understand how hard or easy it is to identify a sign language. Does it take a phrase? Or would it be 3 full sentences until one understands you are not making a lot of errors but actually telling something entirely else in a different language? In order to identify some sign language, you need to know at least something about it, otherwise you just constate "They are signing in an unknown sign language". Language identification works on really small snippets for written languages, so when you know the clues it should work already with a sentence or two for sign languages as well. But I am not aware about papers on "Sign language identification" P.S. I added the tag language-identification. Could you edit your first comment into the question to make it more clear what you are looking for? What do you mean by "recognize"? Are you really aiming at language identification, or are you asking about mutual intelligibility? @jknappen-ReinstateMonica I surely mean "identify", I didn't realize this could be mistaken as "understand". I had read all the other sign language questions on this site and knew that mutual intelligibility had already been discussed. Thank you for helping with tags and suggestions. I hope I rewrote my question a little bit better now. This is a specialized version of the question "can people identify languages that they do not know". For example, can a random English speaker identify some stream of speech as Moroccan Arabic, Riffian Berber, or Chukchi? I think the answer depends on when you are asking (the 70's versus now), because now it is easy to experience Riffian Berber speech from the comfort of your home (much harder to do with Chukchi). There is no possibility of correctly identifying Sakha as such language if you have never had any experience with the language. (You might correctly guess at random, or if you've heard Tuvan and Kazakh and can decide that the language isn't one of those, so you can non-randomly guess that it is Sakha). It depends on whether you have had any experience with the target language. Signed languages are not somehow special in that any ASL signer can recognize, without prior exposure, that so-and-so is using Tanzanian Sign Language vs. British Sign Language. Without any prior exposure, you might guess and be right, but the odds are against being right. However, if you know something about comparative sign linguistics, you might "guess" non-randomly (knowing that X is not British Sign Language, so it might be Australian Sign Language. Likewise one might guess based on knowledge of French Sign Language that X is Dutch, German or Russian Sign Language. This list of sign languages may give you an idea what the historical developments of different languages are. The main impediment to ASL signers being able to recognize Inuit Sign language is lack of exposure, just as people will have a hard time correctly identifying spoken Inuit. Thanks! I was also curious about the signers' ability to identify languages that they know. If I approach someone who knows English in Paris and start speaking English, they will almost instantly recognize the language and understand what I am saying. Would a signer in France recognize ASL within few moves if they know it? Or would it seem like a bunch of strange signs for a minute or two? And regarding the languages that one doesn't know: of course, it's tied to exposure, but I was curious if it works at all. Many people in western societies have an idea how French, German, Russian or Italian sounds like even if they don't speak it at all. Is it common for proficient signers to have an idea how ASL or BSL looks like even if they can't sign in it? @Džuris I'd make this concept you have in mind (of exposure without actual understanding, and its parallel in sign languages) more prominent in your question, since it doesn't seem to come across.
common-pile/stackexchange_filtered
Wordpress website stops working for a particular IP after updating a page Weirdest problem ever. I use wordpress (last version) for my website and I use WP-bakery page builder. It has worked without problems for years. All my plugins are updated to the latest version, except WP bakery page builder because i'm not paying for it. Today, i decided to update the website, and I go to the contact page of my website and change 1 word in the page and click "update". The website ends up showing a "timeout" and the website stopped working. "This site can’t be reached. Try: Checking the connection Checking the proxy and the firewall ERR_CONNECTION_TIMED_OUT" In opera the error is DNS_PROBE_FINISHED_NXDOMAIN Then I tried with a VPN and the website works, so I try to update the page again and "timeout" again and the website is down Then I changed the VPN ip again and my website is working on that new IP. I try to change a blog post, no problem, I add new pages with the testimonial plugin and no problem, then, thinking that everything is ok, i go to the contact page again and i change 1 word and boom... time out and the website is dead for that IP Now I run out of VPNs to test and I can't access my website anymore, but this problem is very strange. I tried https://www.isitdownrightnow.com/ and that website says that my site is up, but i can't access it anymore due to this change that produced the same awful result 3 or 4 times. Who knows about this mysterious issue and a potential solution? The following is the list of plugins i use: Akismet Contact Form 7 Cookie Notice Google Analytics for WordPress by MonsterInsights: Hello Dolly Hide Featured Image: Jivo Chat Maintenance and WP Maintenance mode: PageBuilder by Site Origin and WPBakery page builder: Read More without refresh and WP Show More: ShortPixel image optimizer: Show Hide Author: Simple Custom CSS: Slider Revolution: ThemesFlat by Themesflat.com: WP Downgrade | Specific core version: please list any security or cache related plugins that you have installed i added all the plugins used on my website @Scriptable Plugins look ok. Have you checked your hosting? could be becoming overloaded nothing has changed... no new hosting sorry im not suggesting you have changed anything or its a new host. alot of wordpress sites run on shared hosting and alot of wordpress sites are also targeted by bots to try and gain access to your website for malicious purposes. Many of my websites login pages are constantly under fire, putting heavy load on the server running it. I would suggest checking your servers resources and logs, and see if there is anything unusual happening I had to install security plugins to stop constant attacks on my websites I don't know why it happened, but I discovered that a rule of modsecurity blocked my IP whenever I attempted to update my page... Seems to be a security thing with wordpress to avoid attacks... This shows up in the server log. To solve it I removed the rule for my website... which may cause some security issues, but who cares about security. But I don't know where this blocking comes from...
common-pile/stackexchange_filtered
Image sequence training with CNN and RNN I'm making my first steps learning Deep Learning. I am trying to do Activity Recognition from images sequences (frames) of videos. As a result i am facing a problem with the training procedure. Firstly i need to determine the architecture of my images folders: Making Food -> p1 -> rgb_frame1.png,rgb_frame2.png ... rgb_frame200.png Making Food -> p2 -> rgb_frame1.png,rgb_frame2.png ... rgb_frame280.png ... ... ... Taking Medicine -> p1 -> rgb_frame1.png,rgb_frame2.png...rgbframe500.png etc.. So the problem is that each folder can have a different number of frames so I get confused both with the input shape of the model and the timesteps which I should use. I am creating a model (as you see bellow) with time distirbuted CNN(pre trained VGG16) and LSTM that takes an input all the frames of all classes with the coresponding labels (in the above example making food would be the coresponding label to p1_rgb_frame1 etc.) and the final shape of x_train is (9000,200,200,3) where 9000 coresponds to all frames from all classes, 200 is height & width and 3 the channel of images. I am reshaping this data to (9000,1,200,200,3) in order to be used as input to the model. I am wondering and worried that I do not pass a proper timestep, as a result a wrong training , i have val_acc ~ 98% but when testing with different dataset is much lower. Can you suggest another way to do it more efficient? x = base_model.output x = Flatten()(x) features = Dense(64, activation='relu')(x) conv_model = Model(inputs=base_model.input, outputs=features) for layer in base_model.layers: layer.trainable = False model = Sequential() model.add(TimeDistributed(conv_model, input_shape=(None,200,200,3))) model.add(LSTM(32, return_sequences=True)) model.add(LSTM(16)) The structure of your model isn't obviously bad as far as I can see. As far as the different number of frames issue goes, the solution is to simply not do that. Preprocess your data to take the same number of frames from each action. The deeper issue here is more likely just simple overfitting. You don't specify, but based off the fact that you are talking about hosting your training data on a single computer, I imagine that you don't have much training data, and your network is not learning the activities, but rather just learning to recognize your training data. Consider that VGG16 had about 1.2 million distinct training examples and was trained for weeks on top-end GPUs, just to distinguish 1000 classes of static images. Arguably, learning temporal aspects and activities should require a similar amount of training data. You had a good idea to start with VGG as a base and add onto it so your network doesn't have to relearn static image recognition features, but the conceptual leap from static images to dynamic videos that your network needs to learn is still a big one! How can I get the same number of frames but in the same way having the most useful ones,if I do not take them and let them different will be a problem? About your second statement , indeed i don't have much training data , do you suggest to train them into a classic 'Timedistirbuted Conv2d` layer instead of VGG? You shouldn't depend on knowing which frames are most "useful". This is kind of what your neural network is supposed to learn. Just space the frames out enough, say by 50 or 100 ms. As for your second question, unfortunately, changing the network type won't get rid of the underlying issue. You need more training data, not a fancier network.
common-pile/stackexchange_filtered
MySQL : quote or no quote implies different result with double I think I found a MySQL bug. I have a table : CREATE TABLE `bank` ( `id` int(10) unsigned NOT NULL, `operation_date` date NOT NULL, `value_date` date NOT NULL, `expense` double(10,2) DEFAULT NULL, `income` double(10,2) DEFAULT NULL, `label` varchar(255) NOT NULL, `balance` double(10,2) NOT NULL, `status` int(1) NOT NULL DEFAULT '0', `payment_id` int(10) unsigned DEFAULT NULL, `file_id` int(10) unsigned DEFAULT NULL, `linked_date` datetime DEFAULT NULL ) ENGINE=InnoDB AUTO_INCREMENT=1590 DEFAULT CHARSET=utf8; With a few raw of datas INSERT INTO `bank` (`id`, `operation_date`, `value_date`, `expense`, `income`, `label`, `balance`, `status`, `payment_id`, `file_id`, `linked_date`) VALUES (260, '2016-10-18', '2016-10-18', 0.00, 1308.95, 'VIR IPSEN PHARMA<PHONE_NUMBER> /INV/00059 18 4 2016', 119099.10, 1, 365, NULL, NULL), (262, '2016-10-18', '2016-10-18', -1749.60, 0.00, 'VIR DV_AC_CANDRAUD_146_AZERTY', 115599.90, 1, 367, NULL, NULL), (263, '2016-10-19', '2016-10-19', 0.00, 1920.00, 'VIR SARL FDI<PHONE_NUMBER>94595200000001 VIR DV-AC-FDAVID-29-UREHAB', 117519.90, 1, 461, NULL, NULL), (264, '2016-10-19', '2016-10-19', -850.00, 0.00, 'VIR DV_S_ECAMPO_167_4METRIS', 116669.90, 1, 368, NULL, NULL), (405, '2016-10-18', '2016-10-18', -1749.60, 0.00, 'VIR DV_AC_TSMITH_146_AZERTY', 117349.50, 1, 366, NULL, NULL), (1305, '2016-08-19', '2016-08-19', -114.00, 0.00, 'PAIEMENT CB 1808 ISLES LES MEL SNCF INTERNET CARTE 13841009', 155074.65, 0, NULL, NULL, NULL), (1306, '2016-08-22', '2016-08-22', -17.44, 0.00, 'PAIEMENT CB 1908 HELP UBER COM UBER FR AUG19 GR CARTE 13840928', 155057.21, 0, NULL, NULL, NULL), (1307, '2016-08-22', '2016-08-22', -25.00, 0.00, 'PAIEMENT CB 1908<PHONE_NUMBER>7 TYPEFORM SL CARTE 13840928', 155032.21, 0, NULL, NULL, NULL), (1308, '2016-08-22', '2016-08-22', -0.06, 0.00, 'VIR DV_S_SUPERMOTION_31_SAMSHIE', 122504.65, 0, NULL, NULL, NULL); If I run a query like below (without or without the quote), should the result not be the same? I tested it on 5.5.42 and 5.5.47-0+deb7u1. mysql> SELECT * FROM `bank` WHERE `expense` = -0.06 ORDER BY `expense` DESC; +------+----------------+------------+---------+--------+---------------------------------+-----------+--------+------------+---------+-------------+ | id | operation_date | value_date | expense | income | label | balance | status | payment_id | file_id | linked_date | +------+----------------+------------+---------+--------+---------------------------------+-----------+--------+------------+---------+-------------+ | 1308 | 2016-08-22 | 2016-08-22 | -0.06 | 0.00 | VIR DV_S_SUPERMOTION_31_SAMSHIE | 122504.65 | 0 | NULL | NULL | NULL | +------+----------------+------------+---------+--------+---------------------------------+-----------+--------+------------+---------+-------------+ 1 rows in set (0,00 sec) mysql> SELECT * FROM `bank` WHERE `expense` = '-0.06' ORDER BY `expense` DESC; Empty set (0,00 sec) '-0.06' will be treated as a string, which is different from -0.06, a number. Since expense is a numeric column, the string version ('-0.06') would be casted to something numeric, which is why it isn't matching. I agree and thank you for your answer. If you run the same query by replacing -0.06 with -17.44. It works in both case Convert the columns to DECIMAL(10,2) and check. Both cases should work. DECIMAL worked! I guess it is related to this problem : http://dev.mysql.com/doc/refman/5.7/en/problems-with-float.html Conclusion: Always use DECIMAL! @FlorianDavid I don't have an explanation for this behavior, though you can have a look at this Fiddle. You should absolutely be casting strings before trying to treat them as numbers, so the answer to your question is somewhat moot. float and double are approximate and not stored as exact values, so compare them with exact-value may have some problems, DECIMAL is correct way; @all Thank for your answers! (I am changing all DOUBLE to DECIMAL in my app) I am using PDO to interact with MySQL. PDO automatically add quote around float value... (eg no PDO::PARAM_FLOAT http://php.net/manual/en/pdo.constants.php)
common-pile/stackexchange_filtered
How do you convert between polar coordinates and cartesian coordinates assuming north is zero radians? I've been trying to make a simple physics engine for games. I am well aware that this is re-inventing the wheel but it's more of a learning exercise than anything else. I never expect it to be as complete as box2d for instance. I'm having issues with my implementation of 2d Vectors. The issue is related to the fact that in the game world I want to represent north as being zero radians and east as being 1/2 PI Radians, or 0 and 90 degrees respectively. However in mathematics (or maybe more specifically the Math class of Java), I believe trigonometry functions like sine and cosine assume that "east" is zero radians and I think north is 1/2 PI Radians? Anyway I've written a small version of my vector class that only demonstrates the faulty code. public class Vector { private final double x; private final double y; public Vector(double xIn, double yIn) { x = xIn; y = yIn; } public double getX() { return x; } public double getY() { return y; } public double getR() { return Math.sqrt((x * x) + (y * y)); } public double getTheta() { return Math.atan(y / x); } public double bearingTo(Vector target) { return (Math.atan2(target.getY() - y, target.getX() - x)); } public static Vector fromPolar(double magnitude, double angle) { return new Vector(magnitude * Math.cos(angle), magnitude * Math.sin(angle)); } } And here is the test code to demonstrate the issue: public class SOQuestion { public static void main(String[] args) { //This works just fine Vector origin = new Vector(0, 0); Vector target = new Vector(10, 10); double expected = Math.PI * 0.25; double actual = origin.bearingTo(target); System.out.println("Expected: " + expected); System.out.println("Actual: " + actual); //This doesn't work origin = new Vector(0, 0); target = new Vector(10, 0); expected = Math.PI * 0.5; //90 degrees, or east. actual = origin.bearingTo(target); //Of course this is going to be zero, because in mathematics right is zero System.out.println("Expected: " + expected); System.out.println("Actual: " + actual); //This doesn't work either Vector secondTest = Vector.fromPolar(100, Math.PI * 0.5); // set the vector to the cartesian coordinates of (100,0) System.out.println("X: " + secondTest.getX()); //X ends up being basically zero System.out.println("Y: " + secondTest.getY()); //Y ends up being 100 } } The requirements are: fromPolar(magnitude,angle) should return a vector with x and y initialized to the appropriate values assuming north is at zero radians and east is at 1/2 PI radians. for example fromPolar(10,PI) should construct a vector with x: 0 and y: -1 getTheta() should return a value greater than or equal to zero and less than 2 PI. Theta is the angular component of the vector it's called on. For example a vector with x:10 and y:10 would return a value of 1/4 PI when getTheta() is called. bearingTo(target) should return a value that is greater than or equal to zero and less than 2 PI. The value represents the bearing to another vector. The test code demonstrates that when you try to get the bearing of one point at (0,0) to another point at (10,0), it doesn't produce the intended result, it should be 90 degrees or 1/2 PI Radians. Likewise, trying to initialize a vector from polar coordinates sets the x and y coordinate to unexpected values. I'm trying to avoid saying "incorrect values" since it' not incorrect, it just doesn't meet the requirements. I've messed around with the code a lot, adding fractions of PI here or taking it away there, switching sine and cosine, but all of these things only fix parts of the problem and never the whole problem. Finally I made a version of this code that can be executed online http://tpcg.io/OYVB5Q Why do you want to use polar coordinates for a physics engine? There are loads of examples, but here's a simple one: Lets say you want to get the speed of a entity and display it on the HUD, simple get the magnitude of the velocity vector... To be clear, the physics engine doesn't do things in polar coordinates, but it's handy to have access to them. In trigonometry angles increase anti-clockwise with the 0-point on the x-axis and pointing towards +ve infinity, in navigation they increase clockwise from North. You write I believe trigonometry functions like sine and cosine assume that "east" is zero radians and I think south is 1/2 PI Radians? but I think the second part of your understanding is wrong. Which might account for errors in your code. The fact that they increase in opposite directions is definitely one part of the issue, and I am aware of this, but I don't know how to fix it. I'll fix the error in my question though, should North be 1/2 PI Radians then? I think it might be easier to convert to normal polar coordinates first, then just update the angle to point to where you want. I'm not sure how to do that correctly and that's why I'm asking. If you follow this link you'll see a solution I tried that works in one case but not another http://tpcg.io/x5thn7 Typical polar coordinates 0 points to the East and they go counter-clockwise. Your coordinates start at the North and probably go clockwise. The simplest way to fix you code is to first to the conversion between angles using this formula: flippedAngle = π/2 - originalAngle This formula is symmetrical in that it converts both ways between "your" and "standard" coordinates. So if you change your code to: public double bearingTo(Vector target) { return Math.PI/2 - (Math.atan2(target.getY() - y, target.getX() - x)); } public static Vector fromPolar(double magnitude, double angle) { double flippedAngle = Math.PI/2 - angle; return new Vector(magnitude * Math.cos(flippedAngle), magnitude * Math.sin(flippedAngle)); } It starts to work as your tests suggest. You can also apply some trigonometry knowledge to not do this Math.PI/2 - angle calculation but I'm not sure if this really makes the code clearer. If you want your "bearing" to be in the [0, 2*π] range (i.e. always non-negative), you can use this version of bearingTo (also fixed theta): public class Vector { private final double x; private final double y; public Vector(double xIn, double yIn) { x = xIn; y = yIn; } public double getX() { return x; } public double getY() { return y; } public double getR() { return Math.sqrt((x * x) + (y * y)); } public double getTheta() { return flippedAtan2(y, x); } public double bearingTo(Vector target) { return flippedAtan2(target.getY() - y, target.getX() - x); } public static Vector fromPolar(double magnitude, double angle) { double flippedAngle = flipAngle(angle); return new Vector(magnitude * Math.cos(flippedAngle), magnitude * Math.sin(flippedAngle)); } // flip the angle between 0 is the East + counter-clockwise and 0 is the North + clockwise // and vice versa private static double flipAngle(double angle) { return Math.PI / 2 - angle; } private static double flippedAtan2(double y, double x) { double angle = Math.atan2(y, x); double flippedAngle = flipAngle(angle); // additionally put the angle into [0; 2*Pi) range from its [-pi; +pi] range return (flippedAngle >= 0) ? flippedAngle : flippedAngle + 2 * Math.PI; } } Bearings cannot be negative, whereas the return value of bearingTo can. @meowgoesthedog, unfortunately OPs tests don't provide an explicit answer to the question of the expected range. But if this is really what OP is after I added another version of bearingTo Thank you for your answer, I will conduct unit tests later today to confirm your answer works for all cases :) @EstiaanJ, your question is not really well specified (only the simplest case) so I might misunderstood what you really want. Please, let me know if you need any further assistance. Yeah I didn't really specify. bearingTo() should return a positive value between and including 0 and to the limit of Tau, such that if you converted it to degrees it would be like a navigation bearing. @EstiaanJ, if that is the case as @meowgoesthedog correctly predicted - just use the second bearingTo in my answer that covers that. If I construct a Vector by calling Vector.fromPolar(10,Math.PI) the y coordinate is set to -10 as expected, but then calling getTheta() on that vector returns -1.57 odd which is -1/2 PI instead of the specified PI All the other methods appear to be correct. @EstiaanJ, I'm not used to that terminology. Could you specify the expected range for the Theta and I'll say how to fix your getTheta. It is particularly not clear to me how Theta is different from Bearing. Is it just bearing from (0,0)? Essentially yes. getTheta() should return a value between and including zero and the limit of tau. Theta is the angle component of the vector in polar form. r is the magnitude component of the vector in polar form, or the distance to the origin. @EstiaanJ, OK, try the updated code (copy of the whole Vector code) at the end of my answer.
common-pile/stackexchange_filtered
Why is direct money transfer to other people accounts so expensive? I see from a similar question that in the US and Canada wire transfer are even more expensive than in Europe where I live. But I am interested in the situation in Europe even though their cost is strange even outside Europe, after all they use the same infrastructure used by all the other payment systems. In order to send a wire transfer, the money backing it must be available at the sending bank's account at their respective national central banks. That would be a branch of the US Federal Reserve for US Dollars, and a national bank member of the European Central Bank for Euros. In essence, a wire transfer is an immediate adjustment on the books of the central bank. SWIFT is a "messaging system" over which banks communicate what adjustments to make but does not actually move money. Banks must have a positive balance by the end of the day, or else they must borrow cash at relatively high interest rates. In contrast, credit cards, ACH/SEPA payments, debit networks, etc. have a minimum 24 hour clearing cycle, thus the bank has at least a day to come up with the money, e.g. by selling investments or holding on to more cash from a previous day. The US Federal Reserve is paying 0.10% interest, which is tiny versus other investments. Worse, the European Central Bank's deposit interest rate is currently -0.50%. They charge banks 1/2 percent to keep that money around. In the US, there is a significant opportunity cost to having that cash immediately available, in the Eurozone, there is an actual cash cost. In both cases, the costs are charged back to the customers who use telegraphic transfers as expensive fees. If you make an international transfer between two countries in the EU it is not immediate, but it is even more expensive than a transfer within the country. @FluidCode You have the same problem as one of the other commenters in the previous post that you are getting multiple European payment systems confused, in part because banks don't use technical terms and automatically select what is most beneficial for them. Wires are always instant. If it's not instant, it's something like SEPA, a card-network based system (Visa Debit/Electron), or a third-party/national system. SEPA rules for immediate transfers between countries became effective recently, but they had no impact on the fees. @FluidCode If by "recently" you mean a decade ago, since there was a deadline to be on SEPA by December 2010. I well remember that my bank notified recently that by SEPA requirement the international transfer became immediate, but I won't try to prove it because it's pointless to keep discussing this point when the whole answer seems a lame excuse. Such are the accounting/borrowing costs that when you involve third parties like Visa or PayPal adding their fees the transfer is still cheaper? Does not add up.
common-pile/stackexchange_filtered
Solving Project Euler #12 with Matlab I am trying to solve Problem #12 of Project Euler with Matlab and this is what I came up with to find the number of divisors of a given number: function [Divisors] = ND(n) p = primes(n); %returns a row vector containing all the prime numbers less than or equal to n i = 1; count = 0; Divisors = 1; while n ~= 1 while rem(n, p(i)) == 0 %rem(a, b) returns the remainder after division of a by b count = count + 1; n = n / p(i); end Divisors = Divisors * (count + 1); i = i + 1; count = 0; end end After this, I created a function to evaluate the number of divisors of the product n * (n + 1) / 2 and when this product achieves a specific limit: function [solution] = Solution(limit) n = 1; product = 0; while(product < limit) if rem(n, 2) == 0 product = ND(n / 2) * ND(n + 1); else product = ND(n) * ND((n + 1) / 2); end n = n + 1; end solution = n * (n + 1) / 2; end I already know the answer and it's not what comes back from the function Solution. Could someone help me find what's wrong with the coding. When I run Solution(500) (500 is the limit specified in the problem), I get 76588876, but the correct answer should be: 76576500. The trick is quite simple while it also bothering me for a while: The iteration in you while loop is misplaced, which would cause the solution a little bigger than the true answer. function [solution] = Solution(limit) n = 1; product = 0; while(product < limit) n = n + 1; %%%But Here if rem(n, 2) == 0 product = ND(n / 2) * ND(n + 1); else product = ND(n) * ND((n + 1) / 2); end %n = n + 1; %%%Not Here end solution = n * (n + 1) / 2; end The output of Matlab 2015b: >> Solution(500) ans = 76576500
common-pile/stackexchange_filtered
Keep navigation on the top after background image I am really aware how to keep the navigation bar on the top by inserting position:fixed;top:0; in CSS. But, what I want is different from this one. What I want is when I insert a new div (for image only) before navigation bar. So, when I open the web, I'd like to see the image first before I scroll the page down. After I scroll down the image, we can see a navigation bar there. And also when I keep scrolling down after navigation bar, I want the navigation bar sticks on top of the page. The example of what I mean are here. So far what I have done is I have included .home before navigation bar. I have done is quite messy. Here are the coding below: .home { min-height:400px; } #header-center { margin: 0 auto; } #headerleft { float: left; margin: 20px; } #header, #top { height: 80px; background-color: #E0E0E1; color: #FFF; position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 9999; } #header p, #top p { color: #FFF; } #header h1, #top h1 { font-size: 20px; margin-top: 10px; letter-spacing: 0; } #header h1 a, #top h1 a { font-size: 25px; color: #FFF; text-decoration: none; } #header h1 a:hover, #top h1 a:hover { color: #FFF; } #headerleft h1 { font-family: Calibri sans-serif; font-size: 25px; letter-spacing: 1px; } #headerleft h1 a:hover { color: #CCC; } #nav { float: right; } #nav-icon img { display: none; } #nav ul li { float: left; list-style:none; } #nav ul li a { font-size: 20px; color: #FFF; margin: 0px; padding: 10px; text-decoration: none; float: left; font-family: 'alegreya_sansregular'; cursor: pointer; } #nav ul li a:hover { border-bottom: 4px double #FFF; } <div class="home"> <img src="assets/images/wallpaper.png" /> </div> <div id="header"> <div id="header-center"> <div id="headerleft"> <h1> <a href="#"> LOGO </a> </h1> </div> <div id="nav"> <a href="" id="nav-icon"> <img src="assets/images/navigation.png" alt="nav-menu"> </a> <ul> <li> <a class="link-nav" data-scroll-nav="0"> HOME </a> </li> <li> <a href="works"> WORKS </a> </li> <li> <a data-scroll-nav="1"> ABOUT </a> </li> <li> <a data-scroll-nav="2"> CONTACT </a> </li> </ul> </div> </div> </div> Can you tell me what's wrong with my code? Thanks. You can first set header to position:relative in css. Then you would add jquery or javascript to say - when you scroll past 400px vertical (y) position, change position:relative to position:fixed. That's usually how that works. To answer your comment, you can add a css style: .fixedPosition { position:fixed !important; top: 0; left: 0; } Then add jQuery (don't forget to put the library and the document ready function if needed): $(window).scroll(function () { var y = $(window).scrollTop(); if (y > 400) { $('#header').addClass('fixedPosition'); } else { $('#header').removeClass('fixedPosition'); } }); HERE'S A FIDDLE I appreciate your answer, and can you give me some javascript example where I can have a look at? Thanks. It works - you may need to add more content so that it has enough to scroll down with - but it should work. How about you set the header to be position: relative; by default, and then in javascript detect if it hits the viewport top: $(window).on("scroll", function(){ if (document.getElementById('sticky-header').getBoundingClientRect().top < 1){ $('#sticky-header').css({'position':'fixed','top':'0'}); } // add code for reverse when you scroll up // ... }); I appreciate your answer, and can you give me some javascript example where I can have a look at? Thanks.
common-pile/stackexchange_filtered
Why is the Trinity a Trinity? It's well established and accepted by most Christians that God is triune, consisting of the Father, Son, and Holy Spirit. However, while talking with a friend earlier about Wisdom (from Proverbs), I mentioned that Wisdom could almost be considered a fourth Person. This suddenly made me wonder why there are exactly three Persons. Is there any Biblical evidence as to why God "decided" to be a Trinity, as opposed to a Duinity or a Quardrinity? Barring that, what about a doctrine that even touches on this? Though I now call myself non-denominational, I grew up Wesleyan, so I'd prefer Protestant viewpoints, but a Catholic or Orthodox perspective is acceptable. Related: Do we know there are only three persons in the "Trinity"? This could very well be one of those things that you see a whole lot of varying opinions on; the Bible lacks direct theological statements, and so each sect large enough to have an "orthodoxy" is going to find different things; everything from a literal interpretation of the trinity to something as far from that as saying: "it's just a way to help us comprehend the incredibly inhuman nature of God that we could never understand as one being." An explanation from love and from physical science: http://supahbox.ddns.net/articles/why_god_is_a_trinity.html https://christianity.stackexchange.com/questions/2547/what-is-the-biblical-evidence-that-there-are-only-three-persons-in-the-trinity I wrote a comment under the question, that might interest El endia starman. Jonathan Edwards' Ontological Argument In his "Essay on the Trinity" (and private notebooks and public sermons), Jonathan Edwards suggested a form of ontological argument for each of the three persons of the Trinity. Anselm's argument starts from a definition of a hypothetical God who perfects all excellences and proceeds to show God must actually exist since existence is an excellence that God must have perfected. Edwards argues along the same lines for each Person of the Trinity: And this I suppose to be that blessed Trinity that we read of in the Holy Scriptures. The Father is the Deity subsisting in the prime, un-originated and most absolute manner, or the Deity in its direct existence. The Son is the Deity generated by God's understanding, or having an idea of Himself and subsisting in that idea. The Holy Ghost is the Deity subsisting in act, or the Divine essence flowing out and breathed forth in God's Infinite love to and delight in Himself. And I believe the whole Divine essence does truly and distinctly subsist both in the Divine idea and Divine love, and that each of them are properly distinct Persons. The Father perfects existence Edwards did not seem to make the ontological argument with respect to the Father (though it is that Person normally called simply "God"). Instead, he follows Aristotle in considering the Father to be the prime mover or cause (in all senses) of all that exists. If you've ever played the "why" game with a toddler (Q: "Why does the sun shine in the morning?" A: "Because the Earth rotates." Q: "Why does the Earth rotate?", etc.), you know that the ultimate answer is always God. (If you don't happen to believe in some prime being such as God, the ultimate answer must be "Because that's the way things are.") Even the Son, who is conceived by the Father, and the Spirit, who proceeds from the Father, depend on the Father for existence. The Son perfects understanding Edwards assumes that the Father's end is to enjoy Himself and that in order to accomplish that, He must have an "image" or idea of Himself. The image must be distinct from the Father; it must be the object of God's affection. If the image is worthy of God's infinite enjoyment, it must also be perfect in representing God. Fundamentally, the Father's imagination is so powerful that He creates the Son. In fact, Proverbs 8 describes how God fathered Wisdom, which is just another way to represent the understanding of God, before the Creation. The idea is not that different from what we mean by "a gleam in your father's eye". God contemplates Himself and the Son is that image. Unlike our imaginations, which remain safely in our minds without some sort of effort, God's understanding of Himself is made manifest. The Son existed before He was incarnated as Jesus because God has always been delighting in Himself. Edwards argues that a duplicity is necessary for God to be the object of His own delight. The Spirit perfects action Finally, the Spirit is the manifestation of God's own affection for Himself. Now it must be admitted that this is certainly a strange Person. But Edwards argues that this is exactly the sort of Person we see in the Bible. He concludes from 1 John 4:8, which states that God is love, that the embodiment of the love between the Father and the Son is the Spirit. We note, in passing, that Edwards affirms the filioque because the love, delight, honor, glory, and so on between the First and Second Persons is mutual. According to Edwards, these are not feelings, but actions. The interaction between Father and Son is also perfect, so like God's understanding of Himself, it too is manifest as the Third Person. The essay notes that Paul passes on grace, peace, and mercy from the Father and Son, but never the Spirit. In addition, the Father and Son express their affection for each other, but never for the Spirit. One solution to these puzzles is to conclude that the Spirit is God's love. Perichoresis In order to explain why at least two Persons must exist, Edwards notes the (then) common notion that "God is infinitely happy in the enjoyment of Himself". From that idea, he deduces: However, if God beholds Himself so as thence to have delight and joy in Himself He must become his own object. There must be a duplicity. There is God and the idea of God. The argument is philosophical, by the way, not grammatical, as it marries the ontological argument with the conception of God's self-enjoyment. Edwards was not the first to extrapolate that the Spirit is the action of love between the Father and the Son: If, as is properly understood, the Father is he who kisses, the Son he who is kissed, then it cannot be wrong to see in the kiss the Holy Spirit, for he is the imperturbable peace of the Father and the Son, their unshakable bond, their undivided love, their indivisible unity.—St. Bernard of Clairvaux, in Sermon 8, Sermons on the Song of Songs Of course, these are mere illustrations of the intimacy (perichoresis) that the members of the Trinity enjoy. Going back to Paul himself, Christians have wrestled with this great mystery. Conclusion Jonathan Edwards was the first to point out that he did not propose to make the mystery of the Trinity unmysterious. The degree you accept that ideas perfected become "real" is the degree you are likely to accept this formulation. However, it does insist on exactly three Persons since it requires God to be object, subject, and verb of the sentence: God delights in Himself. The conclusion (while initially striking) might imply that Edwards is making an argument from human linguistics. @Alypius: I encourage you to read Edwards' essay, which is deeply rooted in philosophy and the Scriptures. It can be difficult to read, but it's utterly fascinating. The conclusion is largely my own construction (with some guidance from a paper [PDF] that analyzed the orthodoxy of the view). As always, no image of the Trinity can hope to be accurate. I am not criticizing anything except your conclusion, which is (sorry--to put it a bit more strongly) pure speculation. I agree the conclusion is on pretty thin ice. Who's to say that subject, verb, and object are special? Why not add an indirect object, or an adjective? @Flimzy: I might be overly-clever with my illustration, but I believe the premise is sound and well grounded in ancient Christian theology. I've added a section on perichoresis which is very closely related to Edward's basic argument. Thank you for your summary of Edwards' argument. I wonder, however, if Edwards gave place--vis a vis the triune God--to the centrality of love in his thinking ("God IS love"). Personally, the concept that true love requires at least two persons and a mutually-felt and mutually-expressed feeling and action constitutes, in my thinking, a pretty good analogy for the triune Godhead. All analogies break down, of course. You expressed the same idea as mine in different words with your subject/verb/object analogy. Don Giving credit where credit is due: see my answer, Eric. Don Besides these three persons, no fourth in the divine nature can be asserted Says St. Thomas Aquinas. And why? Because of the "proceeds" The Three Persons of the Blessed Trinity are alike, except in their relation to one another These relations of origin one must understand not as a procession which inclines to what is without - for what proceeds thus is not co-essential with its principle - one must understand them as proceeding within. The relations are completed internally and nobody is going to add to them. Our existence, contrary to scientific opinion, is clearly just an accident (in the philosophical sense) of their love. But the most compelling argument (I think) that St. Thomas makes is that ... in God it is not possible that there be more than two Persons proceeding he says that if one person proceeds by way of the Intellect (the Word, i.e. the Son) or Love (the Holy Spirit) then they're cut off from the other two. And the only relationship that makes complete sense is to have one who does not proceed (God the Father), one who proceeds and is proceeded (God the Son) and one who proceeds from them both and is not proceeded (God the Holy Spirit) The Pocket Aquinas The Holy Spirit Proceeds from the Father and the Son As it turns out, the Trinitarian nature of God is actually an axiom. In mathematics, an axiom is a statement that is taken to be true without a proof. For example, the statement that a straight line can be drawn between any two points is one of the five axioms that comprise Euclid's Postulates. To most of us, this statement is obviously true, but it can't be proven as true using any simpler axioms. This is because it is actually assumed to be true and then the math is carried out from there on that basis. It is indeed entirely possible to assume that some statement is actually false and then go on from there, which is how the non-Euclidean geometries (elliptic and hyperbolic) were discovered - the parallel postulate was taken to be false and it was discovered that the resulting geometric systems were self-consistent. In this sense, the fact that God is a Trinity is true because it just is. God is uncreated and eternal, which means that He was always composed of three Persons - the Father, the Son, and the Holy Spirit. There are also no other gods, so the only god in existence is Yahweh, who is a Trinity. In effect, God couldn't have been anything else. This idea that such a complex characteristic could be an axiom can be somewhat unsatisfying, and indeed, I'm still coming to grips with it. However, it can help to take the axiom as false and see what comes of it, just like Janos Bolyai and Nicolai Lobachevsky decided to treat the Parallel Postulate as false and see what happens. One Person (Unitarian) - God has no need for anything and no reason to desire anything. He is by Himself, and this is perfectly fine with Him. There is therefore no reason to create a universe with angels and men. Two Persons (Duonitarian?) - The two Persons would have a relationship with each other, but there would be no concept of an "another" relationship. They would be wholly satisfied with each other, so there wouldn't be any reason for them to create a universe with angels and men. Three Persons (Trinitarian, included for completeness) - Multiple relationships exist for each Person, which makes it possible for each Person to desire more relationships, leading to the creation of a universe with angels and men that they can form more relationships with. Four or more Persons ("Quadritarian" and up) - Again, multiple relationships exist, but this time, there are too many. Any Person could leave or be separated and there would still exist multiple relationships among the other Persons. Loss means less here. By contrast, in a Trinity, if any Person leaves or is separated, the remainder is a Duo, and that has already been established as insufficient. In other words, if God was Unitarian or Duonitarian, the universe wouldn't have been created. On the other hand, four Persons or more is too many. Therefore, the Trinity is just right in that the concept of intimacy with multiple people exists and the loss of any Person (such as Jesus' death on the Cross, where He was forsaken by His Father) is a hugely significant event. Yahweh is a Trinity because the other options are insufficient. He didn't have to be a Trinity, but He is a Trinity. Its not that the axioms can't be proven , rather they are so trivial(not just obvious) that they don't require proof. Nevertheless proofs exist for axioms, reg your claim "Unitarian" going by your logic since God is the one he creates universe and everything in it so that the entire universe worships him alone. This satisfies your first point and hence God is not a trinity Give credit where credit is due: see my answer, El'endia Starman. Don It is important to remember that the Trinity as a doctrine was inductively defined. That is, the doctrine exists because it explains (most Christians would argue) the data present in the New Testament, namely that Yahweh, Jesus, and the Spirit all "are God," but that God is "one" (cf. Deut 6:4-5). In order to avoid sounding like polytheists, Christians had to come up with a way of reconciling their inductive, experiential belief that Jesus (and the Spirit) were "God," with the Second Temple Jewish ideal of monotheism. In other words, it's tautological—which is shown in your title "Why is the Trinity a Trinity?" Do you have any outside references for this? I don't know that there is "evidence" for what I said--most Church Doctrine is inductively reasoned from the scriptures. As is commonly observed, "Trinity" is not a biblical word, and the language of "God in three persons" wasn't coined until the second or third century CE. I'm not saying the Trinity isn't right, I'm just saying that it is descriptive, rather than prescriptive. This doctrine (that there are three Persons) was not "inductively defined". It was revealed by Christ. Exactly what Christian perspective is this answer from? I would guess "none", since you say "to avoid sounding like polytheists". Furthermore, this does not even answer the question of why the Trinity is a Trinity (I think it answers something like "why did Christians come up with the idea of the Trinity", not that it necessarily gets that answer right). We do not know. Without Divine revelation, we cannot know. We may never understand exactly "why" God is a Trinity of Persons, and the question might not make sense with respect to God. The very fact that God is a Trinity is divinely revealed knowledge. In Catholicism (and I would guess many other denominations), it is confessed that this fact can never be known unless it is revealed. From the Catechism: 237 The Trinity is a mystery of faith in the strict sense, one of the "mysteries that are hidden in God, which can never be known unless they are revealed by God". To be sure, God has left traces of his Trinitarian being in his work of creation and in his Revelation throughout the Old Testament. But his inmost Being as Holy Trinity is a mystery that is inaccessible to reason alone or even to Israel's faith before the Incarnation of God's Son and the sending of the Holy Spirit. Since the fact that God is a Trinity is "strictly" a mystery, the reason why God is a Trinity (if there is any reason) would also be a mystery that can never be known unless it is revealed. The question might not even be valid with respect to God. When we ask "why is it like that?" or "why did you do that?", we are typically (in the theological context) looking for something that might make reference to the purpose of a created thing, or the purpose behind doing something or choosing to be a certain way. But God is not created (and He had no "inner need" to create anything). God did not at some point, for some reason, choose to become a Trinity. He is, was, and always will be a Trinity. Furthermore, He was in no way forced to be a Trinity. A reason (or the idea of being forced, or a choice, etc.) in the relevant sense implies something that preceded God, and there is, of course, nothing that preceded God. Scripture describing Jesus being baptized by John the Baptist includes what look like explicit references to all three: God (the voice), Jesus(in the water), and the Spirit(descending as a dove). What it doesn't include is the trinity as a term. (Mark 1:10,11 and Matthew 3:16,17). Depending on how it's read/translated, it is either the Holy Spirit or a manifestation of the Father. (At which point I bow out). CS Lewis discusses this in Mere christianity! (excellent book) From what I remember: There is the 'Father.' The 'I AM that I AM' The prime mover, the ultimate reality, the fountain from which all flows. He just is. The son: Lewis talks about a thing being 'begotten not made': before our timeline begins, Jesus is 'the firstborn of all creation.' when you say 'Beget' you are saying that you are creating something like yourself, not unlike. When you 'make' something, you are creating something unlike yourself. Humans beget humans, humans make cars, televisions, etc. Lewis argues that he can only imagine that there must only be one begotten son of God because its inconceivable to think that there be more then one son. How would you differentiate between multiple sons? Therefore, only one begotten son. The spirit: Lewis asks: have you ever been in a meeting, or in a club where people walk away talking about the collective 'spirit' in the room? How, when united, multiple people of a like mind can form a unique atmosphere that takes the form of a distinct personality. Lewis argues that The Holy spirit is the realization of the unity of mind and spirit (and ultimately, love) between the first 2 persons of the trinity. (I would quote CS Lewis, but I don't have the book on me at the moment! hope this helps a bit) Just to note - this interpretation of Holy Spirit as love between Father and Son is popular in western christianity, however it would be totally rejected by Orthodox Christians. Is it? I never knew that... As a roman catholic, I know my churches doctrine is very similar to Orthodoxy... The Nicene creed (this version from the catholic new roman missal) is, to my knowledge, accepted by the major orthodox churches, and it reads "I believe in the Holy Spirit, the Lord, the giver of life, who proceeds from the Father and the Son," so my question to you is: what does proceeds mean then? I think that the main objection by orthodox Christians is the word from. From what I can tell, it is thought that the word 'from' implies a separation. @Drew: Actually the problem is the word Son which was added to the Latin translation of the Creed. Is there any Biblical evidence as to why God "decided" to be a Trinity, as opposed to a Duo or a Quartet? The Bible doesn't say much about transcendent nature of God and relations between Hypostases. It doesn't also say anything about God "deciding to be Trinity" or "why is God a Trinity". These are things beyoun human understanding. However God revealed himself as a Trinity (during the Baptism in Jordan or when Christ commanded to baptise in the name of the Father, and of the Son and of the Holy Spirit). @treehau5 I know. And that's why the Icon by saint Andrew called 'Visitation of Abraham' is meant to represent the mystery of Holy Trinity. I just thought that this interpretation can be a little controversial for reformed christians. But thanks for the supplement. FYI: I've asked a meta-question related to the most recent edit. Mark 1:10, 11 and Matthew 3:16,17 Why is it three and not any other number? The best answer I think is that God wanted it so naturally on the basis of his character, which can be concisely described as love. He picked an integer from the set of integers he invented such that the relationship of love could be fully modeled. You can see, citing Solomon whose description of Wisdom you have mentioned, scripture stating the nature of triune solidarity: With one, there is no manifestation of love: Whoever isolates himself seeks his own desire; he breaks out against all sound judgment. Prov 18:1 With two it is manifest but exclusive -- and with three it is full, dynamic, in flux. Amazing and strong. (Consider also the example of Father, Mother, and Child below): Two are better than one, because they have a good return for their labor: If either of them falls down, one can help the other up. But pity anyone who falls and has no one to help them up. Also, if two lie down together, they will keep warm. But how can one keep warm alone? Though one may be overpowered, two can defend themselves. A cord of three strands is not quickly broken. Ecc 4:9-12 I'm going to provide a bit of scripture but also use physical science as a demonstration of God's "choice for trinity". First, we know that the trinity is certainly consistent with scriptural context: "Let us make man in our image" - Gen 1:26, Hebrew "In the beginning, God [Elohim - Hebrew plural God] created the heavens and the earth" - Genesis 1:1 "In the beginning was the Word, and the Word was with God, and the Word was God" -John 1:1 "Therefore go and make disciples of all nations, baptizing them in the name of the Father and of the Son and of the Holy Spirit" -Matthew 28:19 "I am the God of Abraham, the God of Isaac, and the God of Jacob" -Matt 22:32; Ex 3:6 We see God's choice of 3 not only in scriptural doctrine but also the universe he chose to design according to his character: Nucleons (nuclear particles: protons + neutrons) are made of 3 quarks. Quarks are the "fundamental constituents of matter". Consider quantum chromodynamics -- quarks are described as red, green, or blue. Atoms are composed of 3 particles: proton (+), neutron (0), electron (-) Matter can be described in 3 macroscopic forms: solid, liquid, gas. (Plasma is effectively a gas of broken atoms) - E.g. Ice, Water, and Steam are all the same "thing" fundamentally. Father, Mother, Child: (familial) love does not exist without more than two subjects, yet is fundamentally sufficient at three. Four is not evil but there is no new role fulfilled with a second child. God is love; God is three, yet One. Noah's 3 sons propagated humanity in the earth. Ham Japheth Shem In my finite and imperfect way of thinking, I suggest that love (or Love) has to be central in any finite and imperfect formulation for the triune Godhead. In our conceptions of God, we image bearers have to be content with metaphors and analogies, since the map is not the territory (i.e., the metaphors and analogies are not the reality to which the metaphors and analogies point). All metaphors and analogies break down at some point. A soldier, for example, may be "a lion in battle" (or he may be lion-like in his battling skills), but he'll never be a lion. So it is with our descriptions of God. We do, however, have a key word in description The Three-In-One God whom we worship and serve, and that word is love. Where I enlist an analogy/metaphor is in thinking of the Triune God in terms of a husband and wife, who are co-equal (albeit in slightly different ways), and the love they have for one another. Their personhood is a given (or taken for granted--an axiom, if you will--thanks, @El'endia Starman), but the love which they share is LIKE a third person in that there is this bond between them which is vivified by loving feelings and actions. The Father loves the Son; the Son loves the Father; and the Spirit actuates that love relationship via affection and behavior. Interestingly, in the human love relationship between a husband and a wife there is unity in diversity, and that unity is expressed in the Bible as follows: "and the two shall be one flesh. Therefore, what God has joined together, man must not separate." Maybe @Jon Ericson is on the mark when he suggests the Triune God is like the grammatical "subject/object/verb." God is one person (i.e., one sentence) who is exists eternally in a love relationship between Father and Son, energized, if you will, by the Spirit. The Spirit, in a sense, binds the Godhead together? When you think about it, if marriage is a metaphor for Christ's relationship to the Church Universal, then the Spirit likewise is the "glue" which binds the Son to the Son's body, his church. In a sense, there is another three-in-one, which is a metaphor/analogy for THE Three-In-One. Hey, I gave it my best shot! A Theologian named Mike Reeves would very much agree. It's long but if you have a chance, listen to this audio series. First one: http://www.theologynetwork.org/christian-beliefs/doctrine-of-god/enjoying-the-trinity-1--a-delightfully-different.htm He has a book on the Trinity as well. Analogies for the Trinity always fail but my favorite is Edward's of music. The Father is the melody while the Son and Spirit harmonize all singing one song. No one would ever confuse it as three different songs or as just one singer. @JoshuaBigbee: Thanks for the link and the analogy! Don
common-pile/stackexchange_filtered
Cython C-level interface of package: *.pxd files are not found In a nutshell I try to compile a cython extension called extension2 that cimports a file extension from a self-created package. When building extension2, I get the error that extension.pxd is not found though this file is exactly at the sepcified path. Details I am building two packages involving cython, a package A and a package B that depends on A. A is a subpacke of a namespace package nsp. That is, the folder structure looks as follows: ├── nsp │ └── A | ├── extension.pxd | ├── extension.pyx │ └── __init__.py └── setup.py Here, setup.py reads as follows: from setuptools import setup from setuptools.extension import Extension # factory function def my_build_ext(pars): # import delayed: from setuptools.command.build_ext import build_ext as _build_ext # include_dirs adjusted: class build_ext(_build_ext): def finalize_options(self): _build_ext.finalize_options(self) # Prevent numpy from thinking it is still in its setup process: __builtins__.__NUMPY_SETUP__ = False import numpy self.include_dirs.append(numpy.get_include()) #object returned: return build_ext(pars) extensions = [Extension(nsp.A.extension, ['nsp/A/extension.cpp'])] setup( cmdclass={'build_ext' : my_build_ext}, setup_requires=['numpy'], install_requires=['numpy'], packages=['nsp.A'], ext_modules=extensions package_data={ 'nsp/A': ['*.pxd', '*.pyx'] }, ) The setup file is inspired by add-numpy-get-include-argument-to-setuptools-without-preinstalled-numpy and distributing-cython-modules. The cython files were already successfully transformed to .cpp files with another script. I install the the package A with pip install . in the directory of the setup.py. Everything works as desired, and I can find all files of the package under ...\Anaconda3\Lib\site-packages\nsp\A, including the *.pxd files. Now I seek to create a *.cpp file for an extension2 in order to package it later in the second package B. The file extension2.pxd reads from nsp.A.extension cimport mymethod The script to create the *.cpp file reads from distutils.core import setup, Extension from Cython.Build import cythonize import numpy as np import sys print(sys.executable) NAME = 'extension2' extensions = [Extension(NAME, [NAME+'.pyx'], include_dirs=[np.get_include()] ) ] setup(name=NAME, ext_modules = cythonize(extensions, language="c++", compiler_directives=compiler_directives), include_dirs=[np.get_include()] ) When I run this script with python myscript build_ext --inplace, I get an error indicating the pxd file is missing: from nsp.A.extension cimport mymethod ^ ------------------------------------------------------------ .\extension2.pxd:11:0: 'nsp\A\extension.pxd' not found However, this file exists exactly there. (sys.executable is the Anaconda3 folder that contains the installed package) How can I resolve the issue? Additional info I am using python 3.7 on Windows x64 And you are sure pip is the right pip? I.e. pip for python3.7 and not python 2? Otherwise, check the python path in setup.py @ead I am certain that I am using the correct Python installation. I have only one installation, and importing the compiled files (not the pxd) works well. For the same reason I believe the path in setup.py is correct. Cython does not support implicit namespace packages as of yet. That is, cython searches only subdirectories that contain a file init.*, whereby * can be anything from py, pyc, pyx, and pxd. I have created a bugtracker report for this issue, in case you want to follow up on whether the issue has been fixed in a newer version yet (I worked with Cython 0.29.14). Until then, a workaround is to create an empty file __init__.pxd in the folder nsp. This file should be ignored by python, as it is not a *.py file, and lets cython search the subdirectories for packages. The file structure then reads as follows: ├── nsp │ ├── __init__.pxd │ └── A | ├── extension.pxd | ├── extension.pyx │ └── __init__.py └── setup.py To install the additional file __init__.pxd in the namespace package, change the packages argument of setup(...) to packages=['nsp', 'nsp.A'] and the package_data argument to package_data={'': ['*.pxd', '*.pyx']}. Edit: The bug has been known to the cython developers and will be fixed in version 3. See Fix for cimport from PEP420 namespace.
common-pile/stackexchange_filtered
How to flip by Y venn diagramm? (venn.js) I have simple venn diagramm built with d3.js and venn.js: https://jsfiddle.net/rvuf1z5o/ var sets = [ {sets: ['F'], size: 3}, {sets: ['G'], size: 3}, {sets: ['C'], size: 3}, {sets: ['F','G'], size: 1}, {sets: ['F','C'], size: 1}, {sets: ['G','C'], size: 1}, {sets: ['F','G','C']} ]; var chart = venn.VennDiagram(); var div = d3.select("#venn").datum(sets).call(chart); I need to flip this chart by Y as shown in the picture: How can I do it using sets / chart object / svg attrs / css? Thank you for advice. It looks as though you can rearrange their positions by switching around what order you declare the sets. Working jsfiddle var sets = [ {sets: ['F'], size: 3}, {sets: ['G'], size: 3}, {sets: ['C'], size: 3}, {sets: ['G','C'], size: 1}, {sets: ['F','C'], size: 1}, {sets: ['F','G'], size: 1}, {sets: ['F','G','C']} ]; var chart = venn.VennDiagram(); var div = d3.select("#venn").datum(sets).call(chart); The modified code is at the bottom as I had to paste in venn.js Thank you for this simple answer.
common-pile/stackexchange_filtered
Dynamic UITableView with different number of images I want to develop a feed view with dynamic UITableViewCell having different number of images (upto 4). Refer the attached screenshot. Any library or help will be appreciated. Use a UITableViewCell per feed item, and a child UICollectionView to display the images. To achieve this, Create 4 view with number of images and based on your images data show hide view. inside main stackview Use two stackview side by side (each has two imageview). if left has one image then just hide bottom imageview. and if only one image then hide entire right stackview @PrashantTukadiya Does it work like this, bcz never tried. Is stack automatically covers the hidden part of image by other unhidden image?? You just need to set isHidden to true when you have two or three images and for one image you can setHidden to true for right side stackview Use UITableView, and each cell may contain either a UICollectionCell with a custom UICollectionViewLayout, or I would probably prefer a couple of nested UIStackViews: horizontal stack view -> two vertical stack views -> each two imageViews For UIImageViews not containing an image you would set isHidden to true, and thanks to UIStackView's default behaviour they would get hidden as if those imageView's weren't there. Thus you would get desired layout without a lot of effort. Sounds perfect. Thanks for the info, I was thinking of similar approach just needed to know if I am going in the right direction When only one image is available the first vertical stackview isn't taking full width of horizontal stackview https://prnt.sc/i71fbo @Rajesh I guess you'll have to set isHidden = true even on the second vertical stack view, not just on imageViews that are inside of it @MilanNosáľ It works @MilanNosáľ Only questioner can accept the answer. @Rajesh I thought it was you :D @MilanNosáľ, I was following the same approach. So, how should i give the layout constraints between 2 imageviews in vertical stack? I should give the height constraint or equal height constraint for those imageviews right? If so, when there is only 1 image, will that image cover the full height of vertical stackview? @MBN well, the answer depends on what you want to achieve.. if you want to have them the same height, you can just set distribution on the stackView to be .fillEqually... @MilanNosáľ, Yeah i used equal heights constraint and when hiding the second imageview, first imageview is taking the full height. It worked as i expected.Thank you. @MBN You're welcome... upvote would be nice ;)
common-pile/stackexchange_filtered
react library testing are not updating my screen I recently bumped into this weird problem. I am using react-testing-library and am trying to make a simple update. Whenever the user types in the correct name, they will be awarded 10 points and it will be logged on the screen. However, currently the new score doesn't get logged (I remain at the default score which is 0) and I also get the error saying: Cannot log after tests are done. Did you forget to wait for something async in your test? Attempted to log "Warning: An update to Pokemon inside a test was not wrapped in act(...). This is how my test code looks like //PokemonPage.test.js test.only("should have their score updated if they guess the name correctly", async () => { const guessedPokemon = "Pikachu"; jest.spyOn(global, "fetch").mockResolvedValue({ json: () => Promise.resolve({ name: "Pikachu", sprites: { other: { "official-artwork": { front_default: "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/25.png", }, }, }, }), }); render(<Pokemon pokemonTrainer={pokemonTrainer} />); expect(screen.getByText(/Score: 0/)).toBeInTheDocument(); await waitFor(() => screen.findByRole("img")); userEvent.type(await screen.findByRole("textbox"), guessedPokemon); await waitFor(() => userEvent.click(screen.getByRole("button"))) expect(screen.getByText(/Score: 10/)).toBeInTheDocument() }); This is the code it is supposed to call: //PokemonPage.js const handleChange = (e) => setValue(e.target.value); const handleSubmit = async (e) => { e.preventDefault(); pokemonRef.current = await getPokemon(); setPokemonList((prev) => [ ...prev, { name: pokemonRef.current.name, image: pokemonRef.current.image }, ]); updateScore(value) setValue('') }; const updateScore = async (guessedPokemonName) => { if (guessedPokemonName === pokemonList[pokemonList.length - 1].name) { setPokemonTrainerObject(prev => ({...prev, score: pokemonTrainerObject['score'] + 10 || 10 })) } }; Basically I am submitting the user input, and if it is corrent guessedPokemonName === pokemonList[pokemonList.length - 1].name then the user object will update the score. This is what I am trying to emulate with my test. I have tried to use the waitFor to hope that the code understands that the components needs to be updated but to no avail. Is there anyone out there that have encountered something similar? The warning from React, "Warning: An update to Pokemon inside a test was not wrapped in act(...)" means that it has detected a change to your state that is not accounted for in your testing. In this case, this warning is wrapped inside of a more explanatory message saying that this problem occurred after your test. In your code, you have await waitFor(() => userEvent.click(screen.getByRole("button"))). However, waitFor is meant to be used with an assertion. In other words it is meant to wait until an expectation is true -- not until an event is fired, because the firing of an event like this isn't asynchronous (the processing of it may be, but not the firing of it.) Instead, you should just fire the event, and then waitFor something you can test that shows the process is finished. For instance, you said "they will be awarded 10 points and it will be logged on the screen". So after your event, do a waitFor that looks for the message showing that they answered it correctly, which you are already doing in the next line. So try: userEvent.click(screen.getByRole("button")); await waitFor(() => { expect(screen.getByText(/Score: 10/)).toBeInTheDocument(); }); Or, even simpler, since findBy* methods use waitFor inside: userEvent.click(screen.getByRole("button")); await screen.findByText(/Score: 10/); PS You can learn more about that error message and some different approaches to fix it by reading Kent Dodds article on it, Fix the "not wrapped in act() warning Thank you sir! That worked perfectly! It seems like I misinterpreted how the test utils worked. I thought that the button would be where I resolved my promise. Thanks again! Great, glad to hear it. Please "accept" the answer then so others know it resolved your issue.
common-pile/stackexchange_filtered
python How to sort list of string by digit=string how to sort following python list nlist = [ "494=Deploy\00000001.inx", "19=Deploy\0000000144.exe", "2=Deploy\00000001_index.dat", "9=Deploy\0000001b_index.bin", "1=Deploy\00000001_index.bin", "7=Deploy\00000019_index.bin", "2=Deploy\00000001_Onedata.dat", "19=Deploy\000000024444.exe" ] to following sortedList = [ "1=Deploy\00000001_index.bin", "2=Deploy\00000001_index.dat", "2=Deploy\00000001_Onedata.dat", "7=Deploy\00000019_index.bin", "9=Deploy\0000001b_index.bin", "19=Deploy\0000000144.exe", "19=Deploy\000000024444.exe", "494=Deploy\00000001.inx", ] can it be possible to make it single liner sorted(nlist, key=lambda m: int(m.split('=')[0])) Thanks Avinash and Danidee sort the list and pass a key that splits the strings in the list on '=' and picks the numeric part, nlist.sort modifies the original list, if you want a new list you're better off with sorted() nlist.sort(key=lambda x: int(x.split('=')[0])) print(nlist) Output ['1=Deploy\x0000001_index.bin', '2=Deploy\x0000001_index.dat', '2=Deploy\x0000001_Onedata.dat', '7=Deploy\x0000019_index.bin', '9=Deploy\x000001b_index.bin', '19=Deploy\x000000144.exe', '19=Deploy\x00000024444.exe', '494=Deploy\x0000001.inx']
common-pile/stackexchange_filtered
svg images and making the background transparent How do you declare the background of an svg script image to be transparent? Please be more specific. In what kind of document is it inserted? What's the parent element? What is an "svg script image"? If you're viewing in a browser then the background should be transparent automatically. At least it is in FF4 and the latest version of Chrome, but not in some older browsers (e.g. http://petercollingridge.co.uk/data-visualisation/mouseover-effects-svgs). If you want the background to be semi-transparent then fill the space with a <rect> and set its opacity to a number between 0 and less than 1. Even easier method is to delete all the data that is used in the file content. For example, this is the file content before any change. <?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"> <svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="24.000000pt" height="24.000000pt" viewBox="0 0 24.000000 24.000000" preserveAspectRatio="xMidYMid meet"> After, the file content will be the following one. <?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"> <svg> <g transform="translate(0.000000,24.000000) scale(0.100000,-0.100000)" fill="#ff0000" stroke="none"> <path d=""/> </g> </svg>
common-pile/stackexchange_filtered
JDBC driver not found in Eclipse, but found when running standalone I am trying to acces PostgreSQL via jdbc. The code below does not run from Eclipse, but it does run from the command line. Any suggestion how I can run it as well from Eclipse? The postgresql-9.4.1211.jar is in the CLASSPATH, which is in a quite different spot than the package below. Windows 7, java <IP_ADDRESS>.b13, postgres 9.5.3, Eclipse 4.5.1 package PostTest; import java.sql.*; import java.util.logging.Level; import java.util.logging.Logger; public class Version { public static void main(String[] args) { Connection con = null; Statement st = null; ResultSet rs = null; String url = "jdbc:postgresql://localhost/nederland"; String user = "postgres"; String password = "Hallo Postgres!"; System.out.println ("Testing for driver"); try { Class.forName("org.postgresql.Driver"); // Success. System.out.println ("driver found"); } catch (ClassNotFoundException e) { // Fail. System.out.println ("driver lost"); } System.out.println ("Trying to connect"); try { con = DriverManager.getConnection(url, user, password); st = con.createStatement(); rs = st.executeQuery("SELECT VERSION()"); if (rs.next()) { System.out.println(rs.getString(1)); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(Version.class.getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } finally { try { if (rs != null) { rs.close(); } if (st != null) { st.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(Version.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } } } } When running from Eclipse I get: Testing for driver driver lost Trying to connect Oct 07, 2016 8:43:02 PM PostTest.Version main SEVERE: No suitable driver found for jdbc:postgresql://localhost/nederland java.sql.SQLException: No suitable driver found for jdbc:postgresql://localhost/nederland at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at PostTest.Version.main(Version.java:38) When running from the command line: D:\home\arnold\development\java\projects\PostTest\bin>java PostTest.Version Testing for driver driver found Trying to connect PostgreSQL 9.5.3, compiled by Visual C++ build 1800, 64-bit Did you check your BuildPath? If the PostgreSQL library is in your project (e.g. /lib folder), right click on it -> Build Path -> Add to Build Path. If the library is not in your project, right click in your project -> Build Path -> Configure Build Path... Then click in the Libraries tab and Add External JARs... Then select the postgresql-9.4.1211.jar file and click OK.
common-pile/stackexchange_filtered
Swift keyPath vs protocol I understand the basic idea of keyPaths but I do not understand its use cases. If you already know the type of the instance, you can access their properties easily. If you don’t, protocol already supports read-only, read-write properties. Can someone explain me what I am missing? Anything that we can’t do with protocols but keyPaths or when keypaths are better than protocols? Typical use case is KVO. If you already know the type of the instance, you can access their properties easily. If you don’t, protocol already supports read-only, read-write properties. Can someone explain me what I am missing? What you're missing is a sense of what's unknown. In both your sentences you speak of knowing what the instance's properties are. That's not the problem key paths solve. Key paths have nothing to do with knowing the type; they are not in any kind of opposition to types or protocols. On the contrary, before you can use a key path, you have to know exactly what the instance's properties are. Key paths are for when what is unknown is which property to access. They provide a way to pass a property reference so that someone else can be told to access that property. For example, here's a Person type: struct Person { let firstName : String let lastName : String } And here is a function that sorts an array of Persons by either the firstName or the lastName, without knowing which one to sort by: func sortArrayOfPersons(_ arr:[Person], by prop: KeyPath<Person, String>) -> [Person] { return arr.sorted { $0[keyPath:prop] < $1[keyPath:prop] } } A key path is how you tell this function what property to use as a basis for sorting.
common-pile/stackexchange_filtered
Returning the value of a class member pointer variable using 'this' pointer My scenario is , I want to return the value of class member variable m_ptr using this pointer. What I have tried is , #include <iostream> using namespace std; class Test{ int *m_ptr; public: Test():m_ptr(nullptr){ cout<<"Def constr"<<endl; } Test(int *a):m_ptr(a){ cout<<"Para constr"<<endl; } ~Test(){ cout<<"Destr "<<endl; delete m_ptr; } int getValue(){ return *m_ptr; } }; int main(){ Test obj(new int(34)); cout<<"Value -"<<obj.getValue()<<endl; return 0; } The console output is Para constr Value -34 Destr This is fine. What I am trying to do now is , I want to modify the getValue function to return the value of pointer variable m_ptr using this pointer like below . (only writing the getValue function) int getValue(){ return this->(*m_ptr); } But this throws the error as, [Error] expected unqualified-id before '(' token I am beginner in this c++ and I am not understanding the actual reason for this error. It will be helpful to explain what I am doing wrong here. Use return *(this->m_ptr); instead You maybe want return *(this->m_ptr);, but it's not clear why you want to put this into it when it's working fine to begin with. The right hand side of this-> has to be an actual member of the class Test. So you can do *(this->m_ptr) which accesses m_ptr and then dereferences, but not this->(*m_ptr) which would imply that (*m_ptr) itself is somehow a member of Test. @NathanPierson: That's an amazing explanation. As you told , I can start working with initial scenario but I was just curious about this one . The indirection operator is in the wrong place. this->m_ptr would be correct to access the member, and to indirect through that pointer, you put the indirection operator on the left side: return *this->m_ptr; Another good option . +1 for this. But could you please explain how this *this works here. For the another option @Nathan has explained. It would be nice to know about this also. Because this will print the address of the current object and if so then what is *this ? @VishnuCS In fact there is no *this because of the language's operator precedence rules. Because -> binds more tightly than *, the expression is equivalent to *(this->m_ptr); not (*this)->m_ptr;
common-pile/stackexchange_filtered
How to get range of rows using spark in Cassandra I have a table in cassandra whose structure is like this CREATE TABLE dmp.Table ( pid text PRIMARY KEY, day_count map<text, int>, first_seen map<text, timestamp>, last_seen map<text, timestamp>, usage_count map<text, int> } Now I'm trying to query it using spark-cassandra driver , So is there any where I can get the chunks of data. As in if I have 100 rows , I should be able to get 0-10 rows then 10 -20 and so on. CassandraJavaRDD<CassandraRow> cassandraRDD = CassandraJavaUtil.javaFunctions(javaSparkContext).cassandraTable(keySpaceName, tableName); I'm asking this as there is no column in my table where I can Query using IN clause to get range of rows. You can add an auto-incrementing ID coloumn -- see my DataFrame-ified Zip With Index solution. Then you can query by the newly-created id column: SELECT ... WHERE id >= 0 and id < 10; Etc. Hi thanks for the answer , but how to do the same using java ? Also for this to work I guess i have to read the entire table and thats where the problem lies , I cant read the entire table. Please suggest If Im wrong. @RahulKoshaley depends on what you mean by "read the entire table". In order to put add the id column, the executors have to read the entire table, but your driver application does not. This lets you "window" the data, and only read N number of rows in the driver at a time. Exactly how will I choose the N number of rows. ? It's in my answer -- just add an offset to choose which window: "SELECT ... WHERE id >= " + offset + " and id < " + (offset + 10) Sorry what I meant was after altering and adding an id column , how will I put value inside it. ? ie I have to read the entire table rows , and then put value in the Id column, as I cant select N rows (parts) with the existing table structure. Follow the link in my answer -- zipWithIndex is an RDD function built into Spark. In the link, that function is used to create an id column. The populating is done for you. Yes, entire table (RDD actually) gets read, but only a partition at a time and only in the executors. Thanks david , I will have to do the same in java. One last question , How is it that Only a partition gets read , is it due to the zipWithIndex function ? Basically, yes. In a nutshell, the code converts the DataFrame to an RDD using DataFrame.rdd, then runs zipWithIndex, which in Scala creates an RDD of tuples. You then convert this RDD back to a DataFrame by adding the new Long column to the original DataFrame.columns Yes -- that's how zipWithIndex works. Simplifying it, but each partition is "zipped" separately. The driver calculates the number of rows per partition, and therefore the starting offset of each partition. Executors are given a partition and a starting index and it applies it to that partition.
common-pile/stackexchange_filtered
Shortest path algorithm that passes through at least one of a particular type of vertex I have a graph with about 6500 vertices, some of which have the label 'c'. I need to devise an algorithm that finds the shortest path between any two of the vertices that includes AT LEAST ONE of these 'c' vertices. This is simple enough, but the problem is that the required complexity is O(ElogV) where E is the number of edges, and V is the number of vertices. I have already implemented Dijkstra's Algorithm using a min-heap, so I can find the general shortest path in O(ElogV), but I am having trouble extending the problem. Any suggestions? Note that calling Dijkstra's from source to c + c to destination iteratively does not fall within the complexity restraints, as it ends up being O(CElogV) Welcome to Stack Overflow! Unfortunately your question only contains requirements - it is not showing any efforts from your side to solve this problem yourself. Please add your attempts to this questions - as this site is not a free "we do your (home)work" service. Beyond that: please turn to the [help] to learn how/what to ask here. Thanks! Unfortunately, the failed approach in my 'note' was as far as I got :( Let G be your graph, with vertices v1...vn. Make a new graph that consists of two copies of your original vertices: v1..vn, v1'..vn'. In this new graph, let there be an edge between vi and vj or vi' and vj' if there's an edge between vi and vj in your original graph. Also let there be an edge between vi and vj' if there's an edge between vi and vj in your original graph, and vj' is labelled c. Then, given two vertices vi, vj, the shortest path between vi and vj' in the new graph is the shortest path between vi and vj in the original graph that passes through at least one vertex labelled c. Because the number of vertices in the new graph is doubled, and the number of edges at most tripled, the complexity doesn't change from O(VlogE) (where V and E are the number of vertices/edges in the original graph). Thank you so much for the suggestion! I'm currently implementing it to see how I go Update- I've implemented it and it works like a charm! Absolutely stoked, I don't think I could have ever come up with that idea on my own. Thanks heaps, mate Hey how to you solve the problem when we have a subset S of the vertex set V and we want all shortest paths from source to destination to pass through a vertex in S at least every 3 edges? @PaulHankin isn't this O(ElogV) instead of your suggested answer O(VlogE) If you have an undirected graph: Say you're searching for a shortest path between S and T. find all the shortest paths from S to any node using Dijkstra's algorithm find all the shortest paths from T to any node (same algorithm) iterate over all marked nodes c and find the shortest path S to c combined with c to T using previously calculated shortest paths.
common-pile/stackexchange_filtered
ScrollIntoView dont work properly if Scroll size is bigger than browser Window - Selenium? I have a Div which scroll is bigger than window (see image attached below), when I do scrollIntoView (written below 2 codes both gives same behaviour ) Div1 element , it is not working properly instead it Scroll to element but in middle (see image attached below), which leading element displaying half (see image attached below) . Note : In main Div multiple elements are present ex : Div2 ,Div3 and tried to scroll all this element but it scrolling middle of main div . Please help me how to handle this scenario . Tried Code : Code1 : ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", webElement); Code2 : Actions builder = new Actions(driver); builder.MoveToElement(webElement) .Build().Perform(); Share your HTML. . . @GirishBellamkonda, sorry to say I cannot provide HTML as it contains confidential data .......
common-pile/stackexchange_filtered
Issues running two PL2303 USB to Serial converters on a Raspberry Pi Zero W I'm having a bit of a problem building a little network-connected UPS monitor. I have two USB to Serial adapters of the pl2303 kind. Latest Raspbian and I'm running them off a tiny powered USB hub just to be safe. I set the port parameters on both /dev/ttyUSB0 and /dev/ttyUSB1 for NUT and each adapter and serial cable works when tested individually. When I connect both and try to start the NUT driver one of them always refuses to work with an error like this: pl2303 ttyUSB0: pl2303_set_control_lines - failed: -71 Sometimes I get other errors but always -71. I haven't really been able to find any useful information about this. I tried running modprobe -r pl2303 and modprobe pl2303 but it wasn't any real help. I have replaced my old USB hub with a powered ones because I assumed that it might have caused the issues but it didn't. Does anyone have any ideas? (Also, I only seem to find adapters of the pl2303 kind locally, even from different brands, which is annoying because the "just get another type of adapter" is not exactly easily doable at the moment) Thank you in advance! P.S.: the issue does not seem to be related to NUT, I can trigger the error by simply trying to set the baud rate on the device that has issues like stty -F /dev/ttyUSB1 2400. It also triggers the error in syslog. I found PL2303 USB to serial adpators good for Rpi3B. Test record. You might like to read my old post for reference. How many serial ports are on the Pi 3? - tlfong01 RpiSE, 2019apr19, Viewed 7k times WARNING to RpiZ/RpiZW users. I did annoyingly found that RpiZ/RpiZW's USB/serial drivers problematic, comparing with those of Rpi3B+. So I would suggest to test everything first on Rpi3/4, before moving on to RpiZ/RpiZW. End of Answer
common-pile/stackexchange_filtered
US Resident Buy and Sell outide of USA- Do I owe tax other than the income tax? I am a resident of USA. I purchase goods online from a supplier in the Philippines. My buyer is also based in the Philippines and is responsible for pick up from the supplier. Therefore, the inventory movement is from the supplier to the buyer (both in the Philippines). I pay income tax on taxable income [sales invoice minus cost of purchase]. Other than the income tax, do I owe other taxes in the US? I have no employees. I already know what taxes I owe in the Philippines. Thank you. If you sell retail then of course you must pay sales tax. US sales tax does not apply since the products are purchased from and sold to the Philippines. Seems unlikely that any other US tax would apply. Depending on the products, possibly some kind of excise tax.
common-pile/stackexchange_filtered
How to place one widget at top of the screen and other at the bottom in flutter? import 'package:flutter/material.dart'; class Example extends StatelessWidget { const Example({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: ListView(children: [ Column( children: [ Expanded(child: Text('Hello')), Expanded(child: Text('Nithya')) ], ) ]), ); } } I want whole page to be scrollable and widgets placed space between vertically. The tried using SingleChildScrollView instead of ListView but that also didn't work. I tried replacing Expanded with Flexible that also didn't work. How to place text widgets one at top and other at bottom. If there are only two widgets in your Column widget, then you can set MainAxisAlignment attribute to MainAxisAlignment.spaceBetween. You have to set this inside your Column Widget, above or below the children attribute. Refer below working code Explanation : you can use Scaffold root widget body property to make your whole screen as body... I have using Column widget to align our all body Widgets in a vertical direction. mainAxisAlignment: MainAxisAlignment.spaceBetween. Inside column MainAxisAlignment act as a vertical alignment. I have declared two text widgets inside Column.above code said to flutter that align my two text widgets one to top and another to bottom ... that's it you can take it as a template. if you need to make it scrollable you can wrap it with SingleChildScrollView Widget... @override Widget build(BuildContext context) { return Scaffold( body: Padding( padding: const EdgeInsets.all(20.0), child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: const [ Text( "Hello" ), Text( "Nithya" ), ], ), ), ), ); } You place the top and the bottom in a column. You fill between them with an Expanded and place the ListView in it: class MyWidget extends StatelessWidget { @override Widget build(BuildContext context) { return Column( children: [ Text('Top'), Expanded( child: ListView.builder( itemBuilder: (context, i) { return Text('Infinite! $i'); }, ), ), Text('Bottom'), ], ); } } first of all using the Expanded widget means that you reserve the available area of the screen and second to dock one text widget on top, and second, on the bottom, you should first reserve the full available height of the screen by wrapping it in the SizedBox widget second remove Expanded and third use MainAxisAlignment.spaceBetween in column I just bring some changes to your code like following ListView( children: [ SizedBox( height: MediaQuery.of(context).size.height, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: const [ Text('Hello'), Text('Nithya'), ], ), ) ], ), If you mean having the 2 widgets pinned to the top and bottom then use Stack. For example: class Example extends StatelessWidget { const Example({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: Stack( children: [ ListView( children: Colors.primaries.map((color) { return Container( color: color, height: 100, ); }).toList(), ), const Align( alignment: Alignment.topCenter, child: Text( 'Hello', style: TextStyle( fontSize: 70, ), ), ), const Align( alignment: Alignment.bottomCenter, child: Text( 'Nithya', style: TextStyle( fontSize: 70, ), ), ), ], ), ); } }
common-pile/stackexchange_filtered
d3.js code from javascript console to html page I'm learning to use d3.js with a tutorial. The following code is entered in the javascript console (Chrome) and it creates a line graph. How do now take this code and make it run in an html page? var lineData = [ { "x": 1, "y": 5}, { "x": 20, "y": 20}, { "x": 40, "y": 10}, { "x": 60, "y": 40}, { "x": 80, "y": 5}, { "x": 100, "y": 60}]; //This is the accessor function we talked about above var lineFunction = d3.svg.line() .x(function(d) { return d.x; }) .y(function(d) { return d.y; }) .interpolate("linear"); //The SVG Container var svgContainer = d3.select("body").append("svg") .attr("width", 200) .attr("height", 200); //The line SVG Path we draw var lineGraph = svgContainer.append("path") .attr("d", lineFunction(lineData)) .attr("stroke", "blue") .attr("stroke-width", 2) .attr("fill", "none"); Put the code in a script tag and put that tag at the end of the body. Create a file called yourfile.html. Add the basic tags like html, head and body. Include the d3 JavaScript in a script tag with src="http://d3js.org/d3.v3.min.js". Add your code above into another script and the end of the body tag. Open yourfile.html in a browser. All in all, your file may look like this: <!DOCTYPE html> <html> <head> <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> </head> <body> <script type="text/javascript"> var lineData = [ { "x": 1, "y": 5}, { "x": 20, "y": 20}, { "x": 40, "y": 10}, { "x": 60, "y": 40}, { "x": 80, "y": 5}, { "x": 100, "y": 60}]; //This is the accessor function we talked about above var lineFunction = d3.svg.line().x(function(d) { return d.x; }).y(function(d) { return d.y; }).interpolate("linear"); //The SVG Container var svgContainer = d3.select("body").append("svg").attr("width", 200).attr("height", 200); //The line SVG Path we draw var lineGraph = svgContainer.append("path").attr("d", lineFunction(lineData)).attr("stroke", "blue").attr("stroke-width", 2).attr("fill", "none"); </script> </body> </html> For more on setting up and getting started, this tutorial is a good reference. Yes, that did the job, thank you. I was linking to my local version of d3.v3.js, and that doesn't work. My local version of d3.v3.min.js works. Is there a difference between the two files other than no spaces, smaller size, etc?? No, they should be totally the same in their functionality. @Charlie...you need to add <meta charset="utf-8">. Read explanation here and here.
common-pile/stackexchange_filtered
What mechanism is available to rotate a metal piece on another metal piece? I am trying to find some type of mechanism where I can have a smooth but not too stiff rotation between two metal pieces. I was thinking of putting a shoulder screw through the pieces (the pieces will be side by side) and a nut at the end. A real world example I can think of is how when you're unfolding a ladder, the part that unfolds has a joint where rotation occurs. It's smooth and stiff enough that you can let go midway and the ladder wouldn't collapse inward, but not too stiff that you have to apply so much force to unfold the ladder. What do they use to do that? You have the right idea using a shoulder screw. In between the two pieces, use flat washers and a springy Belleville washer. A Belleville washer, also known as a coned-disc spring, conical spring washer, disc spring, Belleville spring or cupped spring washer, is a conical shell which can be loaded along its axis either statically or dynamically. A Belleville washer is a type of spring shaped like a washer. It is the frusto-conical shape that gives the washer its characteristic spring. You can even stack them if needed. They are available from McMaster-Carr. Thanks. I'm definitely gonna read more into this this type of washer. Haven't heard of it.
common-pile/stackexchange_filtered
Can anyone please explain what is geometric center of a graph $f(x)$? Can anyone please explain what is geometric center of a graph $f(x)$ ? What will be the geometric center of $f(x) = x^2$ for all $x \in [0 , 3]$? I do not think so. Focus does not exist for every graph. I think geometric center has some different meaning.@AlbusDumbledore Is this function restricted to some finite domain? Then it might be something like center of mass. But that's just a wild guess. Yes Yes... You are absolutely right . I forgot to give the restriction. @Andrei Can you tell me how to find that ?@Andrei Think of this the curve as made out of a metallic wire, with uniform length density $\lambda$. Then a small piece, of length $dl$ has a mass $dm=\lambda dl$. The total mass of the wire is then $$M=\int dm=\lambda\int dl$$ Since we are given the curve in terms of $x$, we rewrite the above equation as $$M=\lambda\int_0^3\sqrt{1+[f'(x)]^2}dx$$ Then the center of mass in the $x$ direction is $$\bar x=\frac 1M\int x dm=\frac{\int_0^3x\sqrt{1+[f'(x)]^2}dx}{\int_0^3\sqrt{1+[f'(x)]^2}dx}$$ Similarly, $$\bar y=\frac 1M=\int ydm=\frac{\int_0^3x^2\sqrt{1+[f'(x)]^2}dx}{\int_0^3\sqrt{1+[f'(x)]^2}dx}$$ So calculate $f'(x)$, then the three integrals, and you get the center. Notice that the center is independent of the mass density, so it's a geometric property of the curve.
common-pile/stackexchange_filtered
File encoding error in Python 3.6 with "UTF8" charset I receive an XML file with incoming orders encoded in UTF8: <?xml version="1.0" encoding="UTF-8"?> <Beleg xmlns="http://www.mauve.eu/MauveXml/2.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mauve.eu/MauveXml/2.0/ http://download.mauve.eu/schema/MauveXml_2_0.xsd" > And I run a Python 3.6 script to transform this XML file to a CSV file. In the script the command is soup = BeautifulSoup(open(xmlfile, encoding = 'utf-8'), 'xml') and 98% of the times the complete script is working fine. But, with some of the XML files it doesn't work until I manually change a text character like: ğ, ě etc. The error is as follows: Traceback (most recent call last): File "C:\Modification Python Scripts\Python Script23\test5\New Folder\xmlconvert-final.py", line 180, in <module> convertXMLtoCSV(xmlfile,path) File "C:\Modification Python Scripts\Python Script23\test5\New Folder\xmlconvert-final.py", line 152, in convertXMLtoCSV outputwriter.writerow(i) File "C:\Python36\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u202d' in position 83: character maps to <undefined> Any ideas? '\u202d' is Unicode LEFT-TO-RIGHT OVERRIDE, not "╩" U+202D is not the character that you are showing, it is the Left-to-right Direction Override. I'd like to see a full working example, including an XML file that throws this error. @Duncan link in the encodings section it's How to type in Microsoft Windows Alt +202D Edited and removed that mistake. @usr2564301 i can't publish the XML file, it's private data, not for public display. What do you mean by working example? In all the rest XML files the script works great as meant to. The character you showed in Windows is character 202 in the codepage 437. In Unicode that would be character "\u2569". What happened was that your Alt key sequence took only the 202 and ignore the rest. Anyway the point is that you have a character u202d which is giving you problems. I'm not asking for private data but for something we can test on our computers. You are referring to "an" XML file on which you use "your script". That is not much to go on for us. If you look at the traceback you'll see that the error is occurring in cp1252.py from which we can deduce you are writing the CSV file using codepage 1252. The character that is giving you problems is a pretty unusual unicode character and doesn't exist in any form in that codepage. That's why it is giving you an error: there is no way to encode the left to right direction override into codepage 1252. When you open the csv file you can specify an explicit encoding. If you don't have to use cp1252 then try explicitly setting it to utf-8 as that will accept any unicode text. If you do have to use cp1252 then set the errors parameter on the open call to ignore or replace the encoding errors. For example errors='replace' will replace the bad character with a question mark: with open('output_file_name', 'w', newline='', errors='replace') as csv_file: writer = csv.writer(csv_file) writer.writerow('my_utf8_string') Possible settings for errors are: 'strict': raise an exception in case of an encoding error 'replace': replace malformed data with a suitable replacement marker, such as '?' or '\ufffd' 'ignore': ignore malformed data and continue without further notice 'xmlcharrefreplace': replace with the appropriate XML character reference (for encoding only) 'backslashreplace': replace with backslashed escape sequences (for encoding only) In general when encoding unicode you should attempt to use utf-8 or utf-16 as they will allow you to encode everything without errors. Using any other encoding you may encounter characters than cannot be encoded so if you have to use a different encoding you must be prepared to handle those errors. This is the code i had: outputFile = open(filename, 'w', newline='', errors='replace') outputwriter = csv.writer(outputFile) so, i just added the " errors='replace'" and now the script is working with that XML file too. Thank you very much @Duncan
common-pile/stackexchange_filtered
Drupal: setting up a svn I'm setting up for the first time SVN for my Drupal website. (It is not connected to the Drupal repository but to synch the remote and local versions of my websites with a 3rd party SVN hosting service) The question is simple: I would prefer to not complicate too much the server path to my website.. i.e. /var/www/repository_name/trunk/mywebsite/ is a bit too long.. I would prefer to keep it simple as it is now: /var/www/mywebsite Should I maybe use symbolic links ? What's the professional way to setup SVN ? thanks cd /var/www svn co http://server/repository_name/trunk/mywebsite or cd /var/www svn co http://server/repository_name/trunk/mywebsites_name_in_repo mywebsite The website is not served directly from the repository. The website is served from either a working copy or an exported copy of the repository. Furthermore, the repository is not accessed directly, but only by means of an SVN client. A wokring copy always knows from which repository it as taken. In light of that, there is no need to keep the path to the repository short. All right thanks. I've actually thought the working copy have the same directory structure of the repository (i.e. trunk/) but I now see it is not true. Only the original files indeed.
common-pile/stackexchange_filtered
How can I add fastlane builds to Xcode's archive organizer? After setting up fastlane with mostly default settings I got an automated build and upload to iTunes Connect using gym's export_method: "app-store". This uploads files to iTunes connect, and leaves in the current directory *.app.dSYM.zip and *.ipa files. However, when I open Xcode's organizer I don't see a build archive for the uploaded files. Is it somehow possible to convert the files left by fastlane into an Xcode archive and have it appear in the organizer? Gym parameter documentation mentions alternatives for the export_method parameter: ad-hoc, package, enterprise, development, developer-id, but I have no idea what they mean or do. EDIT: Since Fastlane is placing files in a hardcoded path I opened an issue about this. If you don't pass a build_path or archive_path to gym it should default to placing your archive into ~/Library/Developer/Xcode/Archives/[date]. That is where Xcode looks for archives, so they should then be visible in the Organizer! Ah, good to know. The reason it's not working for me is I have set a custom path in Xcode.
common-pile/stackexchange_filtered
How can I send mail using python when there is two factor authentication(eg: outlook + duo mobile for otp) I have tried sending mail using smtp using the guide given here : https://realpython.com/python-send-email/ but the program was stuck without giving any output or error. After a bit of debugging I found that it was stuck at the login phase and I figured that it could be due to the two factor authentication hence I would like to know what can be done in this situation when the sender and receiver both are using Outlook. I tried searching on how we can send mail using python when there is two factor authentication but could not find any concrete answer. The goal is to send a mail(using python) from outlook account to another outlook account when there is two factor authentication enabled for log in.
common-pile/stackexchange_filtered
TwinCat Run Mode failing to start with adswarning 4131 I am trying to start a twincat project on my pc in order to debug it. I've disabled the EtherCAT device and isolated a CPU on my windows 10 with an 8-core ADM processor. After trying to start the run mode, I get a fatal error on the target system. With following message: 'TwinCat System' (10000): Sending ams command >> Init4 RTime: Start Interrupt: Ticker started >> AdsWarning: 4131 (0x1023, RTIME: Intel CPU required) << failed! I've searched the internet and am not able to find a solution to this problem. There seems to be little information about this. Anyone of you having an idea? Answering my own question, just in case anyone else would come across the same problem: make sure when you isolate a CPU to emulate the PLC on that you also check it as the default one to be used. Just isolating isn't enough, you have to explicitly indicate the one to use. Your answer appears to be right there in the message: Intel CPU required, but you stated you're trying to run it on an ADM (I assume AMD) processor. Hi Jim That is also what I thought, but I know someone who is able to run it on his computer which also uses an amd processor. It just feels strange that because the PLC uses an intel processor, that you cannot debug offline using any kind of processor...
common-pile/stackexchange_filtered
How can I change the name of a windows service? I have a windows service application developed in C#. The same service needs to be run with different config files. To run on these on the same machine I would need to change the name of the service. I can create multiple copies of the solution, but not sure how to change the names of the services. Thanks In your win service class that derives from ServiceBase, there is a property that is inherited that you can set called ServiceName. You could make an app.config, add a setting for the service name and have your win service class assign that property accordingly. That way each service name will be unique as long as you change the setting in the app.config. This example goes through it in a bit more detail should anyone need it: http://www.codeproject.com/Articles/21320/Multiple-Instance-NET-Windows-Service For Joel's link, the specifics of how to obtain the ServiceName from app.config from within the installer didn't work for me (probably out of date since it was written for .NET 2.0), but this solution worked fine: http://stackoverflow.com/questions/8516701/how-to-get-windows-service-name-from-app-config The configuration for Windows services are stored in the Registy, under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services... You will probably want to change both the name of the key (the "folder", and the real name of the service here) and the value "Display Name". It might be better to use a tool like SC.EXE to configure services, to avoid causing problems with bad Registry edits. Although SC can't rename a service in place, it does allow you to delete and create services (just be sure to get all the settings right!). Sorry if my question was bit confusing... I wanted to change the name of the service in the solution itself. How can it be done? Service name can also be edited via ProjectInstaller design mode. There is a property called ServiceName in the ServiceInstaller. Additionally, the name coming up in the EventLog is set in the Service design mode itself, through property ServiceName.
common-pile/stackexchange_filtered
Start cmd process call in a .NET MVC web project on IIS web server (not working!) Hi fellow software developers So I need to start a CMD process in my .NET MVC web project. This is my function that I pass the command I need to call: private void ExecuteCommandSync(string command) { System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command); // Hide the CMD window: procStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; // The following commands are needed to redirect the standard output. procStartInfo.UseShellExecute = true; // Now we create a process, assign its ProcessStartInfo and start it System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo = procStartInfo; proc.Start(); proc.WaitForExit(); } The command calls a program that starts a linear programming framework that solves a problem which takes 20 seconds to finish. The problem is that nothing happens when this function is called! It works fine outside the IIS, but not in IIS. The IIS web server runs on a Windows Server 2012. My web project is called from outside of our local network, where the web server is running, does some work, calls my synchronous method and waits for it to finish and ends by returning the result of the call as a JSON object. This question suggests that it might have something with user privileges. In the Application Pools for the web project in Advanced Settings -> Identity I have tried to change from ApplicaitonPoolIdentity to Local System (which has high privileges) but no luck (as explained here). Does anyone have any suggestions to how I can solve this problem? Any advice would be greatly appreciated. You don't get any errors? How are you debugging it? It's really hard to debug this problem! I'm not really getting any errors. You could try to do what's suggested here: http://stackoverflow.com/questions/4624113/start-a-net-process-as-a-different-user What happens sometimes when you call windows applications from within IIS is that the thread is blocked by a forms dialog containing an error message (which is never going to be displayed within IIS) 20 seconds might be causing a timeout either in IIS (request takes too long to process), or in the client (browser got bored and aborted the connection). @SamAxe I can conclude that a timeout does not happen as the whole thing takes under 1 second where it should take 20 seconds. you must run project pool under user have privilege's to execute exec.
common-pile/stackexchange_filtered
How to find identity and inverse for the group $(\mathbb{Z}, \ast)$, where $a \ast b = a+b-ab$ I'm trying to figure out how to find identity and inverse for the group defined as $(\mathbb{Z}, \ast)$, where $a \ast b = a+b-ab$? I've found that closure and the associative property are both true, but I don't know where to go from here. Any help in solving this would be appreciated? Isn't here something wrong with the definition? $1*b=1+b-1\cdot b=1$ for any $b\in\mathbb Z$. Then not a group. @Lehs Indeed: the original problem probably should have said "semigroup" or "monoid," but not group. This 'one' is worse than the real 'one'. The real one does not harm any element after it acts, but this one gobbles up everything it sees :P @daniella: Shouldn't it be $a*b=a+b+ab$? @Lehs That would not work either, since $-1$ wouldn't be invertible (same logic as you gave in the initial comment.) @rschwieb: Yes, of course... At the outset, I need to warn you that this operation does not make $\Bbb Z$ into a group. We'll see why shortly. Easy candidates for identity: If $e$ were the identity for $\ast$, then you'd need $e\ast e=e$, or in other words, $2e-e^2=e$. Can you see how this immediately narrows $e$ down to two possibilities? I'm sure you can do it: just rearrange the above equation and remember that $xy=0$ implies $x=0$ or $y=0$ in the integers. One of the two possibilities works as an identity for $\ast$, and one does not. The one that isn't the identity, call it $z$, satisfies $a\ast z=z$ for all $a\in \Bbb Z$. If $(\Bbb Z,\ast)$ were a group, you'd then cancel $z$ from both sides to conclude that $a=e$ for all $a$, but this is not true. Thus $z$ can't have an $\ast$ inverse. To correct the statement: You can say that $(\Bbb Z,\ast)$ is a monoid, and in fact the element $z$ above is usually called a "zero element," so that this is a monoid with zero element. For the identity, note that $$a*0=a+0-a\cdot 0 \\=a \\ = 0+a-0\cdot a \\ = 0*a $$ To find the inverse element, we need $a*b=0$. This means $$a+b-ab=0 \\ \implies a+b(1-a)=0 \\ \implies b(1-a)=-a \\ \implies b=-\frac{-a}{1-a} \\ \implies b = \frac{a}{a-1}$$ making $b=a^{-1}$. But there is a problem, because clearly $a$ cannot equal $1$, else you would be dividing by zero to get $a^{-1}$. Yet, $1$ is an element of your set. Are you sure this is a group?
common-pile/stackexchange_filtered
if object return empty, no div I only want to display the image div if the object returns an image, right now I'm outputting the image in my <div class="image">, however, if there's no image, then the <div class="image"> should not output: <div class="image"> <img src="{{item.logo}}" alt="{{item.title}}" title="{{item.title}}" /> </div> How about this? <div class="image" ng-if="item"> ... </div> See the documentation for ngIf. You could also use ng-show, which will merely hide the div instead of removing it completely. See the documentation for ngShow.
common-pile/stackexchange_filtered
Showing Overall Description on button click I have a UI where more than three div's are there which has the data's with different ids but with the common button called as "Read".I have displayed the messages in which I have kept the message body as a tiny(15) on this Read button it show me the entire body of the message.How to achieve this one way that I am trying to do is as follows: foreach (var item in Model.MyNote) { <div class="row"> @if (item.Owner.Roles.Any(cx => cx.RoleName == "Customer")) { <div class="panel"> <div class="row"> <div class="three columns"> <img src="@Request.Url.FormatAbsoluteUrl(@item.Owner.Personal.ImageURL)" /> <span style="text-align: center;"> @item.Owner.Personal.FirstName @item.Owner.Personal.LastName </span> </div> <div class="nine columns"> <input type="hidden"<EMAIL_ADDRESS>id="messid" /> <p<EMAIL_ADDRESS></p> <p class="parahide">@item.Description.ToTiny(15) </p> </div> @*<a href="@Url.Action("Read", "Appointment", new { @id = item.Id })" class="button" id="read">Read</a>*@ <button class="button" id="read">Read</button> </div> </div> } else if (item.Owner.Roles.Any(cx => cx.RoleName == "Professional")) { <div class="panel"> <div class="row"> <div class="nine columns"> <EMAIL_ADDRESS></p> </div> <div class="three columns"> <img src="@Request.Url.FormatAbsoluteUrl(@item.Owner.Professional.ImageURL)" /> <span style="text-align<EMAIL_ADDRESS> </div> </div> <a href="@Url.Action("Read", "Appointment", new { @id = item.Id })" class="button">Read</a> </div> } </div> <script type="text/javascript"> $(function () { $(".parahide1").hide(); $("#read").live('click',function () { $(".parahide").hide(); $(".parahide1").show(); }); }); </script> } This give the the result but it is showing the description of all the div's even if I click on the button of the first div. .live() is deprecated , use .on() instead no i am getting the same result what my thinking says that this foreach is looping for say 3 times but the element are having the same class at each time of execution of loop..so can we append something with the id in $(".parahide").hide(); $(".parahide1").show(); Try finding the classes in the parent of the current button like this - $(function () { $(".parahide1").hide(); $("#read").on('click',function () { $(this).parent().find(".parahide").hide(); $(this).parent().find(".parahide1").show(); }); }); Hence, only the divs present in the current button's parent will be hidden or shown! More on .parent() and .find() Also use .on() instead of .live() as live has been deprecated. Using on will require at least jquery 1.7. Since live is working, an older version of jquery is used and needs to be upgraded! Yep. And better to upgrade and use than use the deprecated one. can we do something like this $(".parahide1"+ @item.Id+ ").hide(); You can, but I don't think there's a need to if you use the above "parent" method. to differentiate the divs but parent is applied to the first element only not for others..why is it so? Not sure what you mean by "parent is applied"
common-pile/stackexchange_filtered
Derivative of $c^TX^TXc$ with respect to $X$ What is the derivative of $c^TX^TXc$ with respect to $X$? Here, all the entries are real and $X$ is a matrix while $c$ is a vector. I keep getting confused with the left and right multiplication. Hence, if I have these answers in both these angles, I might remember this better, based on the simple one or two line approach you would take. The following shows these results in the appendix of a book: \begin{gather*} \nabla _X a^T X^T X a = 2X a a^T\\ \nabla _X a^T X X^T a = 2 a a^T X \end{gather*} Let me know how we get there. i) what is your definition of derivative w.r.t. a matrix? usually the gradient w.r.t. a vector $x$ is considered to be a 'one form' (a scalar-valued linear function), i.e. it has the dimensions of $x^\top$, etc (so the answer would be $2cc^TX$) ii) likewise, that would be the map $Y\mapsto c^\top X^\top Y c$ What is $Y$? I did not mention any $Y$. Also page 679, in https://ccrma.stanford.edu/~dattorro/matrixcalc.pdf says it the other way around as $2Xcc^T$. Who is correct- you, or the book? you deleted that part of the question anyway, but probably your book uses the transpose definition. as for the other remark, we can talk about a function $x\mapsto f(x)$ where $x$ is not a previously defined variable; it is then a 'dummy' variable and what we're really interested in is $f$ and it's action on any $x$ Let's go back to the definition of derivative. Let $F : M_n(\mathbb{R}) \to M_n(\mathbb{R})$ be given by $$F(X) = Xcc^T X^T.$$ Fix $X \in M_n(\mathbb{R})$. Then for any $h \in M_n(\mathbb{R})$, $$ F(X+h) = (X+h)cc^T(X+h)^T = Xcc^T X + h cc^T X^T + X cc^T h^T + h cc^T h^T, $$ which is to say that in terms of your favourite matrix norm, $$ F(X+h) = F(X) + (h cc^T X^T + X cc^T h^T) + o(\|h\|). $$ Thus, by definition, the derivative $DF(X) : M_n(\mathbb{R}) \to M_n(\mathbb{R})$ of $F$ at $X$ is $$ DF(X)(h) = h cc^T X^T + X cc^T h^T. $$ Note the importance of the order of multiplication! In the same way, let $f : M_n(\mathbb{R}) \to \mathbb{R}$ be given by $$ f(X) = c^T X^T X c. $$ Fix $X \in M_n(\mathbb{R})$. Then for any $h \in M_n(\mathbb{R})$, $$ f(X+h) = c^T (X+h)^T (X+h) c = c^T X^T X c + c^T h^T X c + c^T X^T h c + c^T h^T h c, $$ so that $$ f(X+h) = f(X) + (c^T h^T X c + c^T X^T h c) + o(\|h\|), $$ and hence $$ Df(X)(h) = c^T h^T X c + c^T X^T h c = 2 c^T X^T h c, $$ where we used the fact that $c^T h^T X c$ is a scalar, so that $$ c^T h^T X c = (c^T h^T X c)^T = c^T X^T h c. $$ Now, in the case of $f : M_n(\mathbb{R}) \to \mathbb{R}$, if we view $M_n(\mathbb{R})$ as an inner product space with inner product $\DeclareMathOperator{\Tr}{Tr} \langle X,Y\rangle = \Tr(X^T Y)$, then $\nabla f (X)$ is the unique matrix in $M_n(\mathbb{R})$ such that $$ \forall h \in M_n(\mathbb{R}), \quad Df(X)(h) = \langle \nabla f(x),h\rangle := \Tr((\nabla f(x))^T h). $$ Now, let $C$ be the matrix with first column $c$ and everything else $0$. Check, then, that $$ Df(X)(h) = 2 c^T X^T h c = \Tr(2 C^T X^T h C) = \Tr(2 C C^T X^T h) = \langle 2 X C C^T, h\rangle, $$ so that once you convince yourself that $C C^T = c c^T$, $$ \nabla f(X) = 2 X C C^T = 2 X c c^T. $$ I have added an image from my book, to the above question. These results don't match yours..please let me know your thoughts. That said, thanks for the clear and elegant explanation as of till now as for exampe it says in the second case that the derivative is $2Xcc^T$ instead . @halms Is your first function a typo, then? Because $Xcc^T X^T$ isn't a scalar, so taking the gradient of $X \mapsto Xcc^T X^T$ doesn't make sense. oops..yes! corrected it. please focus on the second question (now-only existing question) onto what the book says, and the reasoning for it. I am trying to use this derivative in a larger calculation, but was not sure at how the appendix in the book arrived at it. there's another typo: 'Fix $X \in M_n(\mathbb{R})$. Then for any $X$...' You can do both questions simultaneously, as each of these functions is of the form $X\longmapsto F(X,X)$ for some $F$ bilinear continuous. Fact: If $(X,Y)\longmapsto F(X,Y)$ is bilinear and continuous in the sense that there exists $M>0$ such that $\|F(X,Y)\|\leq M \|X\|\|Y\|$, then $F$ is differentiable with derivative $$ dF_{(X,Y)}(H,K)=F(X,K)+F(H,Y). $$ Proof: the map $\theta:(H,K)\longmapsto F(X,K)+F(H,Y)$ is linear and continuous. Now $$ \|F(X+H,Y+K)-F(X,Y)-\theta(H,K)\|=\|F(H,K)\|\leq M\|H\|\|K\|\leq M (\|H\|^2+\|K\|^2). $$ So $$ \lim_{(H,K)\rightarrow (0,0)}\frac{F(X+H,Y+K)-F(X,Y)-\theta(H,K)}{\sqrt{\|H\|^2+\|K\|^2}}=0. $$ This proves, by definition, that $\theta$ is the derivative of $F$ at $(X,Y)$. QED. Consequence: with a bilinear continuous function $F$, the compostion $G(X):=F(X,X)$ si differentiable with derivative $$ dG_{X}(H)=F(X,H)+F(H,X). $$ Proof: chain rule, given that the derivative of the linear continuous map $\theta(X)=(X,X)$ is $\theta$ at every $X$. QED. Application: note that everything is continuous since we are in finite dimension. With the function $F_1(X,Y)=Xcc^TY^T\;$, we get $G_1(X)=Xcc^TX^T$. Hence $$ dG_{1_{X}}(H)=F_1(X,H)+F_1(H,X)=Xcc^TH^T+Hcc^TX^T. $$ With the function $F_2(X,Y)=c^TX^TYc\;$, we get $G_2(X)=c^TX^TXc$. Hence $$ dG_{2_{X}}(H)=F_2(X,H)+F_2(H,X)=c^TX^THc+c^TH^TXc. $$ Now to find the gradient and turn the answer into the form of the book, observe, e.g. for the second one, that $$ c^TX^THc=c^TH^TXc=\mbox{real number}=\mbox{Trace}(c^TX^THc)=\mbox{Trace}((Xcc^T)^TH) $$ hence $$ \nabla_X(c^TX^TXc)=2Xcc^T. $$
common-pile/stackexchange_filtered
Confucian Messianism, Mencius, etc Just picked up Popular Religious Movements and Heterodox Sects in Chinese History by Hubert Seiwert (In collaboration with Ma Xisha) and was kind of caught aback by the idea of Confucian messianism. Here's what the book says: Google Books Page 20 of the book: One of these elements, which gave Han Confucianism a particular religious flavour, was the expectation of a sage-emperor who would realize the coming of a new era in which the world will enjoy peace and prosperity. These ideas were not confined to the Confucians of the New Text School but were widespread among different schools of the Former Han. Especially the fangshi 方士 (“master of recipes,” “magicians”), who were closely related to the Huang-Lao teaching, promoted the idea of a golden age that would be inaugurated by an emperor who responds to the cosmic order by enacting the proper rituals and cultivating his personality.10 Confucian scholars of the Former Han shared these ideas. They seem to have been inspired by a prophecy already alluded to in the Book of Mencius, namely the appearance of a sage every five hundred years who would transmit the true teaching and thereby restore order to the world.11 The Han emperor Wudi apparently referred to this tradition when he deplored the fact that for five hundred years the erudites had not been able to bring back the principles of the ancient kings.12 Wudi regarded himself as the one who should reinstall the cosmic order and become the sage-emperor preordained by Heaven. This is the background of the various ritual measures that he enacted during his reign.13 The expectation of a sage-emperor who would bring about the ideal state of the world that supposedly had existed in high antiquity occupied the thought of the New Text scholars. It was this same expectation on which Wang Mang relied when he styled himself as the fulfilment of this expectation. Thus, the historical and political theories of Former Han Confucianism contained an element that could properly be called Confucian messianism. This Confucian messianism, of course, was intimately related to the belief in prophecies and omens popular with the New Text School. Following the failure of Wang Mang’s rule it lost much of its appeal and was eventually suspended. After the Han, messianic expectations no longer played a prominent role within the Confucian tradition.14 10 Cf. Anna K. Seidel, La divinisation de Lao Tseu dans le Taoïsme des Han (Publications de l’École Française d’Extrême Orient; 71), Paris: École Française d’Extrême-Orient, 1969, p. 25. 11 Mengzi yizhu 孟子譯注, 盡心章句, xia, Beijing: Zhonghua shuju, 1960, vol. 2, p. 344. 12 Hanshu 漢書, by Ban Gu 班固, Beijing: Zhonghua shuju, 1962 (1975), j. 56, p. 2496. 13 Cf. E.B. Ord, State sacrifices in the Former Han dynasty according to the official histories, Ph.D. thesis, University of California, 1987, pp. 112 ff. Mengzi talks of 尧 and 舜 a lot throughout 盡心章句 - I would imagine it has something to do with this...? What exactly is the prophecy being spoken of here, i.e.: the appearance of a sage every five hundred years who would transmit the true teaching and thereby restore order to the world in the original Chinese? Is there a name for this, so-called, prophecy? What is the Chinese for the sage-emperor? (圣王 (?) ) What is entailed in the idea of a golden age that would be inaugurated by an emperor who responds to the cosmic order by enacting the proper rituals and cultivating his personality? What did Wudi (武帝) do during his reign that is considered to fit into this prophecy? E.g.: Wudi regarded himself as the one who should reinstall the cosmic order and become the sage-emperor preordained by Heaven. This is the background of the various ritual measures that he enacted during his reign.13 (this question might be off topic for this site, sorry.) From 《孟子·公孙丑下》: 孟子去齐。充虞路问曰:「夫子若有不豫色然。前日虞闻诸夫子曰: 『君子不怨天,不尤人。』」 曰:「彼一时,此一时也。五百年必有王者兴,其间必有名世者。由周而来,七百有馀岁矣。以其数则过矣;以其时考之,则可矣。夫天未欲平治天下也;如欲平治天下,当今之世,舍我其谁也? 吾何为不豫哉!」 Mengzi was a very boastful person. I think the prophecy (actually more of a theory) 五百年必有王者兴 was something he made up to elevate himself to the savior (the One) of his time. He further talked about this prophesy of the 500 year cycle in 《孟子·尽心下》: 由尧舜至于汤,五百有余岁,若禹、皋陶,则见而知之。若汤,则闻而知之。由汤至于文王,五百有余岁,若伊尹、 莱朱,则见而知之;若文王,则闻而知之。由文王至于孔子,五百有余岁,若太公望、散宜生,则见而知之;若孔子,则闻而知之。由孔子而来至于今,百有余岁,去圣人之世若此其未远也。近圣人之居若此其甚也,然而无有乎尔,则亦无有乎尔! Mengzi listed the following nine sage emperors (圣王): Yao, Shun, Yu, Tang, Wen Wang, Wu Wang, Zhou Gong, Kongzi (素王) and Mengzi himself (舍我其谁). What is entailed in the idea of a golden age that would be inaugurated by an emperor who responds to the cosmic order by enacting the proper rituals and cultivating his personality? I don't know the exact source(s) it is referring to, but again in 《孟子·滕文公下》: 天下之生久矣,一治一乱。 The idea of 一治一乱 is simple: a period of peace and prosperity follows (and predates) a period of war and chaos. Whenever a new dynasty is established, the new ruler would employ theories such as 五德终始说 to claim his righteousness to reign. Bear in mind that China had just experienced a period of war in Jingdi's (the father of Wudi) time and was constantly under threat from neighboring forces, so whatever Wudi did, the prophesy was used to solidify his power. The use of the prophesy, however, was not limited to the rulers. Sima Qian employed the 500 year theory to express his ambition in his autobiography 《太史公自序》: 先人有言:「自周公卒 五百岁 而有孔子。孔子卒后至于今 五百岁,有能绍明世,正易传,继春秋,本诗书礼乐之际?」意在斯乎!意在斯乎!小子何敢让焉。 Notice his tone of voice was basically the same as that of Mengzi: in the present age, 500 years after Confucius (or Wen Wang before him), who else other than the Grand Historian is capable of producing something big and everlasting? We can see the profound influence the 500 year theory had on later Chinese intellectuals in poems such as 梅花重压帽檐偏,曳杖行歌意欲仙。後 五百年 君记取,断无人似放翁颠。 by the Song poet Lu You, or 满眼天机转化钧,天工人巧日争新。预支 五百年 新意,到了千年又觉陈。 by the Qing poet Zhao Yi. “ Mengzi was a very boastful person” - I also like how he claimed not to enjoy being argumentative (予岂好辩哉). Suuuuuure...:P
common-pile/stackexchange_filtered
SMSLib doesn't send SMS with E226 3G modem I would like to know if someone knows why I can't send sms with my E226 3g modem. I have configured the example class, I setted modem model, PIN and Smsc number. public class SendMessage { public void doIt() throws Exception { OutboundNotification outboundNotification = new OutboundNotification(); System.out.println("Example: Send message from a serial gsm modem."); System.out.println(Library.getLibraryDescription()); System.out.println("Version: " + Library.getLibraryVersion()); SerialModemGateway gateway = new SerialModemGateway("modem.com1", "COM4", 9600, "Huawei", "E226"); gateway.setInbound(true); gateway.setOutbound(true); gateway.setSimPin("1010"); // Explicit SMSC address set is required for some modems. // Below is for VODAFONE GREECE - be sure to set your own! gateway.setSmscNumber("+555181136200"); Service.getInstance().setOutboundMessageNotification(outboundNotification); Service.getInstance().addGateway(gateway); Service.getInstance().startService(); System.out.println(); System.out.println("Modem Information:"); System.out.println(" Manufacturer: " + gateway.getManufacturer()); System.out.println(" Model: " + gateway.getModel()); System.out.println(" Serial No: " + gateway.getSerialNo()); System.out.println(" SIM IMSI: " + gateway.getImsi()); System.out.println(" Signal Level: " + gateway.getSignalLevel() + " dBm"); System.out.println(" Battery Level: " + gateway.getBatteryLevel() + "%"); System.out.println(); // Send a message synchronously. OutboundMessage msg = new OutboundMessage("+556199655944", "Hello from SMSLib!"); Service.getInstance().sendMessage(msg); System.out.println(msg); // Or, send out a WAP SI message. //OutboundWapSIMessage wapMsg = new OutboundWapSIMessage("306974000000", new URL("http://www.smslib.org/"), "Visit SMSLib now!"); //Service.getInstance().sendMessage(wapMsg); //System.out.println(wapMsg); // You can also queue some asynchronous messages to see how the callbacks // are called... //msg = new OutboundMessage("309999999999", "Wrong number!"); //srv.queueMessage(msg, gateway.getGatewayId()); //msg = new OutboundMessage("308888888888", "Wrong number!"); //srv.queueMessage(msg, gateway.getGatewayId()); System.out.println("Now Sleeping - Hit <enter> to terminate."); System.in.read(); Service.getInstance().stopService(); } public class OutboundNotification implements IOutboundMessageNotification { public void process(AGateway gateway, OutboundMessage msg) { System.out.println("Outbound handler called from Gateway: " + gateway.getGatewayId()); System.out.println(msg); } } public static void main(String args[]) { SendMessage app = new SendMessage(); try { app.doIt(); } catch (Exception e) { e.printStackTrace(); } } } It outputs run: Example: Send message from a serial gsm modem. SMSLib: A Java API library for sending and receiving SMS via a GSM modem or other supported gateways. This software is distributed under the terms of the Apache v2.0 License. Web Site: http://smslib.org Version: 3.5.2 0 2012-06-28 19:08:32,652 [main] INFO org.smslib.Service - SMSLib: A Java API library for sending and receiving SMS via a GSM modem or other supported gateways. This software is distributed under the terms of the Apache v2.0 License. Web Site: http://smslib.org 3 2012-06-28 19:08:32,655 [main] INFO org.smslib.Service - Version: 3.5.2 3 2012-06-28 19:08:32,655 [main] INFO org.smslib.Service - JRE Version: 1.7.0_05 5 2012-06-28 19:08:32,657 [main] INFO org.smslib.Service - JRE Impl Version: 23.1-b03 Exception in thread "Thread-3" java.lang.ExceptionInInitializerError 5 2012-06-28 19:08:32,657 [main] INFO org.smslib.Service - O/S: Windows 7 / amd64 / 6.1 8 2012-06-28 19:08:32,660 [main] DEBUG org.smslib.threading.AServiceThread - Initialized. 8 2012-06-28 19:08:32,660 [NotifyQueueManager] DEBUG org.smslib.threading.AServiceThread - Running... 8 2012-06-28 19:08:32,660 [NotifyQueueManager] DEBUG org.smslib.notify.NotifyQueueManager$NotificationQueueManager - NotifyQueueManager running... 9 2012-06-28 19:08:32,661 [main] INFO org.smslib.queues.DefaultQueueManager - Queue directory not defined. Queued messages will not be saved to filesystem. 9 2012-06-28 19:08:32,661 [main] DEBUG org.smslib.threading.AServiceThread - Initialized. 10 2012-06-28 19:08:32,662 [DelayQueueManager] DEBUG org.smslib.threading.AServiceThread - Running... 10 2012-06-28 19:08:32,662 [DelayQueueManager] DEBUG org.smslib.queues.AbstractQueueManager$DelayQueueManager - DelayQueueManager running... 10 2012-06-28 19:08:32,662 [main] DEBUG org.smslib.threading.AServiceThread - Initialized. at org.smslib.modem.SerialModemDriver.connectPort(SerialModemDriver.java:69) at org.smslib.modem.AModemDriver.connect(AModemDriver.java:114) 10 2012-06-28 19:08:32,662 [WatchDog] DEBUG org.smslib.threading.AServiceThread - Running... at org.smslib.modem.ModemGateway.startGateway(ModemGateway.java:189) 11 2012-06-28 19:08:32,663 [Thread-3] INFO org.smslib.modem.ModemGateway - GTW: modem.com1: Starting gateway, using Huawei E226 AT Handler. at org.smslib.Service$1Starter.run(Service.java:276) Caused by: java.lang.RuntimeException: CommPortIdentifier class not found 11 2012-06-28 19:08:32,663 [Thread-3] INFO org.smslib.modem.SerialModemDriver - GTW: modem.com1: Opening: COM4 @9600 at org.smslib.helper.CommPortIdentifier.<clinit>(CommPortIdentifier.java:76) ... 4 more 15010 2012-06-28 19:08:47,662 [WatchDog] DEBUG org.smslib.threading.AServiceThread - Running... 30011 2012-06-28 19:09:02,663 [WatchDog] DEBUG org.smslib.threading.AServiceThread - Running... 45012 2012-06-28 19:09:17,664 [WatchDog] DEBUG org.smslib.threading.AServiceThread - Running... 60012 2012-06-28 19:09:32,664 [WatchDog] DEBUG org.smslib.threading.AServiceThread - Running... 75013 2012-06-28 19:09:47,665 [WatchDog] DEBUG org.smslib.threading.AServiceThread - Running... 90014 2012-06-28 19:10:02,666 [WatchDog] DEBUG org.smslib.threading.AServiceThread - Running... That's all I get for hours. Any idea why doesn't work? You're missing javax.comm. The situation with javax.comm on Windows is a bit of a mess, the smslib installation instructions suggest to use rxtx instead and point to Cloudhopper's page for a Windows version. Get that library, add it as a dependency to your project and you should be all set. I have tried javacomm but It doesn't support Win 7 64 bits, the rxtx library from cloudhopper's page has a 64 bits version which works well. Thank you I've the same problem but in my case i already had do all this steps, So, if you know another issue that can cause this please share me it. @MuhammedRefaat please create a new question for your problem, don't tack it to some other question as a comment. Read the how to ask posting to understand how to create a good question that without doubt will be answered quickly. Good luck! Caused by: java.lang.RuntimeException: CommPortIdentifier class not found You are missing a library, whichever one contains CommPortIdentifier. Figure out which library you need and include it in the classpath. What's your suggestion if i include all the libraries and still have the same problem? You are missing comm library.There are two libraries which you can resolve this. Here is the Code Snippet which throws this error: try { classCommPortIdentifier = Class.forName("javax.comm.CommPortIdentifier"); } catch (ClassNotFoundException e1) { try { classCommPortIdentifier = Class.forName("gnu.io.CommPortIdentifier"); } catch (ClassNotFoundException e2) { throw new RuntimeException("CommPortIdentifier class not found"); } } So, make sure either javax.comm.CommPortIdentifier of gnu.io.CommPortIdentifier classes are in your class path.Also make sure you add native rxtxSerial.dll to {jre}/bin/ gnu.io.CommPortIdentifier is from rxtx library which has new packaging convension. There was package name change recently and therefore you will get confused in using RxTx library. Please get some idea from above code and make things clear to you Here is what is mentioned on the site: RXTX 2.1 Is the main development branch for RXTX. The namespace used is gnu.io.. Unless you have any specific reasons, this is the recommended download. If you need to be compatible with javax.comm.* then download RXTX 2.0, but note that not much development effort is provided for this branch so you will be missing out on all the fixes that the main branch is getting.* I've the same mentioned problem but i made all the required steps and the problem still exists, even i try your snippet and ran correctly without catching anything, would use suggest me another solution please? Are you getting any exceptions? then please post it. No, i don't, it runs normally What is your environment? Is it Linux or Windows?
common-pile/stackexchange_filtered