qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
292,621
I've downloaded the Windows 7 `.vhd` from Microsoft's site. I created a virtual PC from that `.vhd`. It runs OK, but the welcome screen want a password for one of the accounts (admin and administrator). I've tried guessing a few passwords but with no luck... Anyone knows the correct password?
2011/06/03
[ "https://superuser.com/questions/292621", "https://superuser.com", "https://superuser.com/users/82407/" ]
Note the new password might be > > Login Instructions > > Login Information (for Windows Vista, 7, 8 VMs): > IEUser, Passw0rd! > > > If you downloaded from <http://www.modern.ie/en-us/virtualization-tools#downloads> see <https://modernievirt.blob.core.windows.net/vhd/virtualmachine_instructions_2013-07-22.pdf>
Here it is: Passw0rd! As the following image shows: ![enter image description here](https://i.stack.imgur.com/2RwWM.png)
25,266,989
I am trying to submit form which is in primefaces dialog `<p:dialog/>`. ``` <h:form> <h:inputHidden value="123" id="domesticTransferId" /> <p:commandButton action="#{domesticTransactionsController.addFirstSignerSignToTransaction}" id="domesticTransferFirstSignerSign" value="#{msg['label.FirstSignerSignature']}" icon="ui-icon-print" styleClass="myButton" > </p:commandButton> </h:form> ``` It is not calling method that I am expecting to be called. ``` public String addFirstSignerSignToTransaction() { try { System.out.println("DomesticTransactionsController.addFirstSignerSignToTransaction()"); } catch(Exception e) { } return null; } ```
2014/08/12
[ "https://Stackoverflow.com/questions/25266989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/791195/" ]
Your command button must be : ``` <p:commandButton action="#{domesticTransactionsController.addFirstSignerSignToTransaction()}" id="domesticTransferFirstSignerSign" value="#{msg['label.FirstSignerSignature']}" icon="ui-icon-print" styleClass="myButton" > ``` You forgot to add () at the end of the method name.
Try with this: ``` public String addFirstSignerSignToTransaction(ActionEvent event){ System.out.println("DomesticTransactionsController.addFirstSignerSignToTransaction()"); return ""; } ``` Check that ManagedBean is javax.faces.bean.ManagedBean
186,084
Just this - How do you add a timer to a C# console application? It would be great if you could supply some example coding.
2008/10/09
[ "https://Stackoverflow.com/questions/186084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3535708/" ]
Or using Rx, short and sweet: ``` static void Main() { Observable.Interval(TimeSpan.FromSeconds(10)).Subscribe(t => Console.WriteLine("I am called... {0}", t)); for (; ; ) { } } ```
Use the PowerConsole project on Github at <https://github.com/bigabdoul/PowerConsole> or the equivalent NuGet package at <https://www.nuget.org/packages/PowerConsole>. It elegantly handles timers in a reusable fashion. Take a look at this sample code: ``` using PowerConsole; namespace PowerConsoleTest { class Program { static readonly SmartConsole MyConsole = SmartConsole.Default; static void Main() { RunTimers(); } public static void RunTimers() { // CAUTION: SmartConsole is not thread safe! // Spawn multiple timers carefully when accessing // simultaneously members of the SmartConsole class. MyConsole.WriteInfo("\nWelcome to the Timers demo!\n") // SetTimeout is called only once after the provided delay and // is automatically removed by the TimerManager class .SetTimeout(e => { // this action is called back after 5.5 seconds; the name // of the timer is useful should we want to clear it // before this action gets executed e.Console.Write("\n").WriteError("Time out occured after 5.5 seconds! " + "Timer has been automatically disposed.\n"); // the next statement will make the current instance of // SmartConsole throw an exception on the next prompt attempt // e.Console.CancelRequested = true; // use 5500 or any other value not multiple of 1000 to // reduce write collision risk with the next timer }, millisecondsDelay: 5500, name: "SampleTimeout") .SetInterval(e => { if (e.Ticks == 1) { e.Console.WriteLine(); } e.Console.Write($"\rFirst timer tick: ", System.ConsoleColor.White) .WriteInfo(e.TicksToSecondsElapsed()); if (e.Ticks > 4) { // we could remove the previous timeout: // e.Console.ClearTimeout("SampleTimeout"); } }, millisecondsInterval: 1000, "EverySecond") // we can add as many timers as we want (or the computer's resources permit) .SetInterval(e => { if (e.Ticks == 1 || e.Ticks == 3) // 1.5 or 4.5 seconds to avoid write collision { e.Console.WriteSuccess("\nSecond timer is active...\n"); } else if (e.Ticks == 5) { e.Console.WriteWarning("\nSecond timer is disposing...\n"); // doesn't dispose the timer // e.Timer.Stop(); // clean up if we no longer need it e.DisposeTimer(); } else { System.Diagnostics.Trace.WriteLine($"Second timer tick: {e.Ticks}"); } }, 1500) .Prompt("\nPress Enter to stop the timers: ") // makes sure that any remaining timer is disposed off .ClearTimers() .WriteSuccess("Timers cleared!\n"); } } } ```
13,511,565
just feeling that i'm wasting loops here = CPU time, and was wondering if there's a way to optimize this code, or just minimize it. Basically what the code does is, goes trough every controls inside the editOkkInfo control. checking if the current control is an textbox, if yes, then it will perform some stuff, if no it will jumps to next if-statement. This next statement checks if we have counted 14 times(since i only have 14 textboxes), if not 14, then the loop continues, if counted 14, then the loop breaks. Any help is appreciated, thanks in advance, and here is the code, cheers. ``` iterate = 0; foreach (System.Web.UI.Control ctrl in this.editOkkInfo.Controls) { if (ctrl is TextBox) { tb = (TextBox)this.FindControl(ctrl.ClientID.ToString()); tb.Text = dt.DefaultView[0][iterate++].ToString(); } if (iterate == 14) break; } ```
2012/11/22
[ "https://Stackoverflow.com/questions/13511565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1670729/" ]
There is no need to use `FindControl`, as you already have the control. Just cast it: ``` iterate = 0; foreach (System.Web.UI.Control ctrl in this.editOkkInfo.Controls) { if (ctrl is TextBox) { tb = (TextBox)ctrl; tb.Text = dt.DefaultView[0][iterate++].ToString(); } if (iterate == 14) break; } ``` An additional readability improvement will do away with the looping over all controls and the `is` test: ``` foreach (TextBox ctrl in this.editOkkInfo.Controls) { ctrl.Text = dt.DefaultView[0][iterate++].ToString(); if (iterate == 14) break; } ```
I have seen one faster way to find all controls of specific type rather than looping. This seems more efficient. [Using linq to get list of web controls of certain type in a web page](https://stackoverflow.com/questions/3613561/using-linq-to-get-list-of-web-controls-of-certain-type-in-a-web-page) Hope that helps Milind
8,405,412
Maybe I'm not understanding something, but can somebody explain to me why the following code is behaving the way it is: ``` /^[1-9]\d*(\.\d{2})?$/.test('0.50') === false; /^\.\d+$/.test('0.50') === false; /^([1-9]\d*(\.\d{2})?)|(\.\d+)$/.test('0.50') === true; // <-- WTF? ``` What's going on here? As you can see the 3rd expression is composed of the first two joined by the `|` operator. Since each one tests `false`, isn't `false | false == false` ? Or am I missing a basic concept with regular expressions? I've tried this in the browser, and with nodejs. Same result either way.
2011/12/06
[ "https://Stackoverflow.com/questions/8405412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115049/" ]
This is because of precedence of operators. Your expression is `^[1-9][0-9]*(\.\d{2})?` or `\.\d+$`. If you do the following: ``` /^([1-9][0-9]*(\.\d{2})?)$|^(\.\d+)$/.test('0.50') ``` you will get `false` as you expect. (Note extra $ and ^ at the boundaries). More details: in your second part of last expression you no longer require `.` to be the first character.
Yeah, but that isn't false | false. I'll add some more parentheses to make it clear what the third regex is evaluating as: ``` /(^([1-9]\d*(\.\d{2})?))|((\.\d+)$)/.test('0.50') === true; // <-- WTF? ```
856,318
I am trying to host two seperate domains on one IP address. I want to be able to determine from the STARTTLS command which certificate was being requested and forward to a different mail server based on the domain. This doesn't seem to be possible from the RFCs, but is there any other way something like this can be achieved on the single IP address?
2017/06/16
[ "https://serverfault.com/questions/856318", "https://serverfault.com", "https://serverfault.com/users/-1/" ]
[According to the documentation](http://www.postfix.org/TLS_README.html), Postfix sends SNI information in the TLS handshake after `STARTTLS` command, at least in the case where TLSA records are published in DNS: > > When usable TLSA records are obtained for the remote SMTP server the Postfix SMTP client sends the SNI TLS extension in its SSL client hello message. This may help the remote SMTP server live up to its promise to provide a certificate that matches its TLSA records. > > > I'm not sure if this is sufficient, but it suggests that SNI can and should be used with `STARTTLS`; if some senders are not doing this, I would consider them broken. Further, [this IETF draft](https://tools.ietf.org/id/draft-ietf-dane-srv-03.xml#tls) specifies that SNI shall be used: > > The client uses the DNSSEC validation status of the SRV query in its server certificate identity checks. (The TLSA validation status does not affect the server certificate identity checks.) It SHALL use the Server Name Indication extension (TLS SNI) or its functional equivalent in the relevant application protocol... > > >
You don't need SNI for this. Most MTAs support routing based on domain. For example [postfix has a transport map](http://www.postfix.org/transport.5.html). You'd make a map something like: ``` foo.com smtp:[mail.foo.com] bar.com smtp:[mail.bar.com] ```
30,999,820
How to retrieve `int` value from `List` that is biggest number on it but still smaller than `X` value to which i am comparing. ``` Value = 10 Example one: List = {1,4,6,8}; => number 8 biggest on list and smaller than 10 Example two: List = {1,15,17,20}; => number 1 biggest on list and smaller than 10 ``` I was trying using Linq but no success so far.
2015/06/23
[ "https://Stackoverflow.com/questions/30999820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1606426/" ]
You can just restrict the values you use to get the "Max" by using a `Where` clause: ``` return myList.Where(x => x < 10).Max(); ```
You can use [`Where`](https://msdn.microsoft.com/en-us/library/system.linq.enumerable.where%28v=vs.100%29.aspx) to filter your values which less than `10` and use [`Max`](https://msdn.microsoft.com/en-us/library/system.linq.enumerable.max%28v=vs.100%29.aspx) to get maximum values in them like; ``` var list = new List<int>{1, 15, 17, 20}; list.Where(s => s < 10).Max().Dump(); ``` ![enter image description here](https://i.stack.imgur.com/2ttwC.png)
60,768
In the Brexit negotiations there have been various pledges and demands that the final agreement will "not compromise [UK] sovereignty". E.g: * [Brexit fishing fury: Boris warned fishing compromise is step to forfeiting UK sovereignty](https://www.express.co.uk/news/politics/1368010/Brexit-fishing-news-Boris-Johnson-trade-deal-fishermen-latest-sovereignty-update-vn) * Rob Butler, who represents Aylesbury, [said the UK should not sign up to](https://www.bbc.co.uk/news/live/uk-politics-55211021) “any agreement that compromises our sovereignty". What does it mean to "compromise sovereignty"? Surely in any agreement both the EU and the UK will promise to do some things and not do others. Isn't any such agreement a compromise over things that a sovereign state can do? **Edit:** In response to answers so far. This is not a question about European policy or what the government or EU are thinking. Its about the narrow question of what this phrase actually means, if anything. There seems to be a split here between what I will call "practical sovereignty" and "legal sovereignty". Practical sovereignty seems to be defined as the ability to get things done and make decisions in the best interests of the people of the UK, while legal sovereignty seems to be defined as the freedom to make laws without being restricted by other countries, regardless of the practical impact. The conflict between the two stems from the [hegemonic effect](https://en.wikipedia.org/wiki/Brussels_effect) of having the EU next door.
2020/12/07
[ "https://politics.stackexchange.com/questions/60768", "https://politics.stackexchange.com", "https://politics.stackexchange.com/users/13141/" ]
I once heard Harold Wilson argue that if you organised the World Cup, in doing so you "lost a little bit of sovereignty" (this was in late 1966). He was not opposed to doing so but just pointing out that - yes membership of the EU would involve loss of sovereignty, but so did our organising the World Cup, which in any case England won". For all countries of the world to retain 100% of their sovereignty, one might argue that there would have to be a prohibition on all international trade. But on another level "sovereignty" is like beauty - it is in the eye of the beholder. Above all Boris Johnson has to avoid any **appearance** of loss of sovereignty - whatever that might be - free movement of people, subject to ECJ jurisdiction, obligation to follow EU rules etc. The anti-EU opinion in the UK substantially coalesces around symbols like the EU flag, the EU anthem, the right of "foreigners" to work in "our country" and take "our jobs". But whatever "deal" is agreed, even a "no deal", the UK remains part of a geo-political European economic zone. That much is inevitable. And since the EU is more than seven times the size of the UK, the latter will always be a junior partner so long as it is not a member of the EU. (A similar position in which Canada finds itself in relation to the US). This leaves the EU with the opportunity to exercise hegemonic control over the UK, which infringes sovereignty every bit as much as membership of the EU would. The UK cannot change its geography, and it cannot change its neighbours. And this thing has much much further to run. We shall most likely see British ministers and officials going back and forth to Brussels for meetings far more than was ever the case when we were full members. And then there is the vexed question of Scotland. Almost certainly the SNP will win next May's election by a landslide, and it will be extremely difficult to avoid granting another referendum, with a strong possibility that Scotland will leave the UK. And all the time public opinion in the UK will be in fluctuation. We have effectively given up a settled EU membership, as a united UK for a "neverendum of referendums". If Scotland and the rest of the UK break apart, it arguably has an effect on UK sovereignty too.
After the Tudors and up until 1689 there was a political struggle between the King and the English Parliament which ended with the "Glorious Revolution" and the recognition of Parliamentary sovereignty. This meant that what is now the UK Parliament was the highest legal authority. Acts passed by parliament cannot be abrogated or disapplied by the executive. Indeed the executive government's freedom of action can be constrained by Parliamentary legislation and Parliament can pass legislation putting the executive under a legal duty to act in certain ways. It is a key feature of EU law that it regards itself as sovereign and, when the UK joined the EC (as it was then) the UK - as it committed to do in the treaty - passed legislation - the European Communities Act 1972 - making EU law part of UK law and providing that any new EU law would automatically be part of UK law. The meant that Parliament lost its sovereignty because a UK government minister could go to Brussels and - if he could persuade ministers of other member states in the Council of Ministers - he could create EC law which overrode any law passed by the UK Parliament. In the early days, as EC law and the EC institutions were developing, it was not really appreciated (or, if it was, it was not publicly acknowledged) that there was a loss of *UK* sovereignty. Yes the EC Council of Minsters could override the UK Parliament but only if the UK minster agreed (there had to be unanimity) so the UK, taken as a whole, could not have laws thrust upon it which it did not want. As time went on it came to be understood that there was a loss of sovereignty because the need for unanimity meant that if the UK came to the view that a law which the UK had previously agreed to was no longer suitable, the UK could not get it removed or changed without the agreement of the other ministers. The loss of sovereignty came to public attention particularly with the *Factortame* litigation. Many UK fishermen had lost their livelihoods as a result of the EC Common Fisheries Policy. The UK Parliament passed the Merchant Shipping Act 1988 - a measure designed to prevent non-UK fishermen from using UK fishing quota by the device of operating through a UK registered company. The Act of Parliament was eventually declared ineffective - because contrary to EU law - [in a series of court cases stretching over 11 years from 1989 to 2000](https://en.wikipedia.org/wiki/R_(Factortame_Ltd)_v_Secretary_of_State_for_Transport). Beyond the Council of Ministers, other EU institutions also grew in the power they exercised. The introduction of qualified majority voting reduced the ability of any member state to veto legislation, the EU Commission became more powerful in proposing legislation and the Court of Justice of The European Union (CJEU) was an "activist" court which created new laws such as the "dual vigilance" system established the in *Francovich* case., So legal sovereignty - the ability ultimately to make its own decisions - was lost by the UK. The other aspect is territorial sovereignty. If the UK regains the ability to make its own decisions that sovereignty is limited if the writ of the UK does not extend to all its territory. The 10 mile limit is important here because up to the 10 mile limit the waters are British territorial waters. But beyond the territorial waters within the 200 mile limit by international convention each country is responsible for fishing so having control of this is important to the idea of sovereignty too. Of course if the UK were, just as an example, to sign a 20 year treaty giving EU member states unlimited access to fish British waters, the UK would still technically be sovereign - it would have taken a sovereign decision to sign. But in practical terms people tend to feel that long terms commitments giving up a large amount of control involve the giving up of a degree of sovereignty in a practical (even if not in a theoretical) sense. **Other uses of the term "practical sovereignty"** I have also noticed that the phrase *practical sovereignty* was used by Remainers in the debate over Brexit as a counter to points about sovereignty made by Brexiteers. Those in favour of the UK exiting the EU had a variety of reasons for being of that view but one prominent argument was about sovereignty and democracy - that the democratically elected representatives of the people of the UK should have the final say on the laws which govern the UK. It is clearly the case that membership of the EU involves loss of a nation state's sovereignty in the normal technical legal sense (at least within certain areas) because that is a fundamental principle of EU law. "Yes we have given up sovereignty but hey look how living standards have improved" might not be perceived as a universally attractive way of putting the counter-argument so many Remainers put the counter argument in terms of sovereignty by saying that sovereignty has not so much been given up as "pooled". Essentially the idea is that by lending part of their sovereignty to the EU the member states become part of a large body which a lot more influence and power on the world stage. This can then be tied in to the idea that it is all very well the UK making sovereign *decisions* about international affairs but that it not much good in practice if the UK does not have the power/influence to carry those decisions into effect - the UK would have more "practical sovereignty" if it acts on the international stage as part of the EU.
62,157,695
Is there any sort of Maven plugin that allows me to copy the class files for a dependency into the target\classes folder for my project? Currently I have to manually open the jar file that has the dependencies extract the package that I need to copy over and then copy it into the target\class folder for my project. I need a way to do those ideally within the pom.xml file but I haven't been able to find a solution that works. Any help would be appreciated, Thanks.
2020/06/02
[ "https://Stackoverflow.com/questions/62157695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13667190/" ]
This sounds like a terrible idea. If you want to include unpacked dependencies into your project, use the maven assembly plugin or the maven shade plugin.
below is the example to use of assembly pulgin and it works for me below is the child pom plugin ``` <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>3.4.2</version> <configuration> <archive> <manifest> <mainClass>my parent package statup class</mainClass> </manifest> </archive> </configuration> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> ``` Parent pom plugin ``` <build> <pluginManagement> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </pluginManagement> </build> ```
491,681
I would like to have an `enumerate` list, **with the numbers expressed in unary**. That is, "1" would be represented as `•`, "3" as `•••`, and "8" as `•••••|•••`. I'm able to print the dots already, and that's working fine: ``` \newcommand{\xxdot}{\textbullet} % The dot character to use \newcounter{loopcntr} % A one-off counter for \forloop \newcommand{\xxdots}[1]{% Print #1 dots in a row \ifthenelse{#1>5}{% If there are more than five, break them into groups \xxdots{5}\textpipe\xxdots{\number\numexpr#1-5\relax}% By printing five, then a pipe, then the rest }{% Otherwise, just print that many dots \forloop{loopcntr}{0}{\value{loopcntr}<#1}{\xxdot}% }% } \newcommand{\xdots}[1]{\textnormal{\xxdots{#1}}} % Wrap it in textnormal style ``` However, I have no idea how to make `enumerate` use this. Based on [this answer](https://tex.stackexchange.com/a/2292/169121), I tried redefining `\theenumi`: ``` \renewcommand\theenumi{\xdots{\arabic{enumi}}} ``` But this went badly wrong: ``` ! Illegal parameter number in definition of \@currentlabel. <to be read again> 1 l.376 ^^I\item My text here ... You meant to type ## instead of #, right? Or maybe a } was forgotten somewhere earlier, and things are all screwed up? I'm going to assume that you meant ##. ``` How can I apply my unary-printing code to the `enumerate` label? EDIT: Based on [this answer](https://tex.stackexchange.com/a/124983/169121), I tried this: ``` \newcommand*\unary[1]{\expandafter\@unary\csname c@#1\endcsname} \newcommand*\@unary[1]{\xdots{\the\numexpr#1\relax}} ``` And it seems to work! As in, this produces the correct output: ``` \newcounter{test} \setcounter{test}{8} \unary{test} ``` However, the MWE still throws a bunch of errors. MWE follows: ``` \documentclass{article} \usepackage{forloop} \usepackage{tipa} \usepackage[T1]{fontenc} \newcommand{\xxdot}{\textbullet} % The dot character to use \newcounter{loopcntr} % A one-off counter for \forloop \newcommand{\xxdots}[1]{% Print #1 dots in a row \ifthenelse{#1>5}{% If there are more than five, break them into groups \xxdots{5}\textpipe\xxdots{\number\numexpr#1-5\relax}% By printing five, then a pipe, then the rest }{% Otherwise, just print that many dots \forloop{loopcntr}{0}{\value{loopcntr}<#1}{\xxdot}% }% } \newcommand{\xdots}[1]{\textnormal{\xxdots{#1}}} % Wrap it in textnormal style \makeatletter \newcommand*\unary[1]{\expandafter\@unary\csname c@#1\endcsname} \newcommand*\@unary[1]{\xdots{\the\numexpr#1\relax}} \makeatother %\renewcommand\theenumi{\unary{enumi}} % This crashes and burns \begin{document} Unary works normally: \xdots{1}, \xdots{3}, \xdots{8}. It even works with a counter. \newcounter{test} \setcounter{test}{8} \unary{test} But in a list: \begin{enumerate} \item My text here my text here \item More text more text \item Even more text \end{enumerate} \end{document} ```
2019/05/20
[ "https://tex.stackexchange.com/questions/491681", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/169121/" ]
The `enumitem` package is your friend. You can define a new list style, which I have called `unerate`, and then make this list style use your `\unary` code. To achieve this it is enough to add the following lines to your code: ``` \let\realItem\item \newcommand\unerateItem{\refstepcounter{uneratei}\realItem[\unary{uneratei}]} \usepackage{enumitem} \newlist{unerate}{enumerate}{1} \setlist[unerate]{label=\alph*, before=\let\item\unerateItem } ``` So this redefines `\item` to be `\unerateItem` and this, in turn, uses the "real" `\item` with `\unary` applied to the list environment counter, which is called `uneratei`. With this in place, the code ``` \begin{unerate} \item My text here my text here \item More text more text \item Even more text \item Even more text \item Even more text \item Even more text \item Even more text \item Even more text \end{unerate} ``` produces: [![enter image description here](https://i.stack.imgur.com/GNMpp.png)](https://i.stack.imgur.com/GNMpp.png) Here is the full code: ``` \documentclass{article} \usepackage{forloop} \usepackage{tipa} \usepackage[T1]{fontenc} \newcommand{\xxdot}{\textbullet} % The dot character to use \newcounter{loopcntr} % A one-off counter for \forloop \newcommand{\xxdots}[1]{% Print #1 dots in a row \ifthenelse{#1>5}{% If there are more than five, break them into groups \xxdots{5}\textpipe\xxdots{\number\numexpr#1-5\relax}% By printing five, then a pipe, then the rest }{% Otherwise, just print that many dots \forloop{loopcntr}{0}{\value{loopcntr}<#1}{\xxdot}% }% } \newcommand{\xdots}[1]{\textnormal{\xxdots{#1}}} % Wrap it in textnormal style \makeatletter \newcommand*\unary[1]{\expandafter\@unary\csname c@#1\endcsname} \newcommand*\@unary[1]{\xdots{\the\numexpr#1\relax}} \makeatother \let\realItem\item \newcommand\unerateItem{\refstepcounter{uneratei}\realItem[\unary{uneratei}]} \usepackage{enumitem} \newlist{unerate}{enumerate}{1} \setlist[unerate]{label=\alph*, before=\let\item\unerateItem } \begin{document} \begin{unerate} \item My text here my text here \item More text more text \item Even more text \item Even more text \item Even more text \item Even more text \item Even more text \item Even more text \end{unerate} \end{document} ``` You can now use `enumitem` to style these environments to your heart's content. The code above will not let you nest `unerate` environments. If this is required let me know and I will update it - it's not difficult, but requires a little extra work.
Here's an expandable `\unifive` macro: ```latex \documentclass{article} \usepackage{xparse,enumitem,tipa} \usepackage{showframe} \ExplSyntaxOn \NewExpandableDocumentCommand{\unifive}{m} {% #1 should be an integer \draconis_unifive:n { #1 } } \cs_new:Nn \draconis_unifive:n { \int_compare:nTF { #1 > 5 } { \unifivefive \draconis_unifive:e { \int_eval:n { #1 - 5 } } } { \prg_replicate:nn { #1 } { \unifiveone } } } \cs_generate_variant:Nn \draconis_unifive:n { e } \NewDocumentCommand{\unifivefive}{} { \unifiveone\unifiveone\unifiveone \unifiveone\unifiveone\unifivebar } \NewDocumentCommand{\unifiveone}{}{\textbullet} \NewDocumentCommand{\unifivebar}{}{\textpipe} \ExplSyntaxOff \makeatletter \newcommand{\unifivecount}[1]{\expandafter\@unifivecount\csname c@#1\endcsname} \newcommand{\@unifivecount}[1]{\unifive{#1}} \AddEnumerateCounter{\unifivecount}{\@unifivecount}{\unifive{10}} \makeatother \newlist{unerate}{enumerate}{1} \setlist[unerate]{label=\unifivecount*,leftmargin=*} \begin{document} \begin{unerate} \item My text here my text here \item More text more text \item Even more text \item Even more text \item Even more text \item Even more text \item Even more text \item Even more text \item Even more text \item Even more text \end{unerate} \unifive{42} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/fe8J9.png)](https://i.stack.imgur.com/fe8J9.png)
30,345,134
I am getting the following exception in Android Studio plugin Android Support. To get out of this error, I updated the Android Studio to 14.1, but studio just builds the app but not runs it. ``` null java.lang.NullPointerException at java.io.File.<init>(File.java:277) at com.android.sdklib.internal.avd.AvdManager.parseAvdInfo(AvdManager.java:1616) at com.android.sdklib.internal.avd.AvdManager.buildAvdList(AvdManager.java:1577) at com.android.sdklib.internal.avd.AvdManager.<init>(AvdManager.java:350) at com.android.sdklib.internal.avd.AvdManager.getInstance(AvdManager.java:373) at org.jetbrains.android.facet.AndroidFacet.getAvdManager(AndroidFacet.java:585) at org.jetbrains.android.facet.AndroidFacet.getAvdManagerSilently(AndroidFacet.java:571) at org.jetbrains.android.run.DeviceChooser.<init>(DeviceChooser.java:143) at org.jetbrains.android.run.ExtendedDeviceChooserDialog.<init>(ExtendedDeviceChooserDialog.java:80) at org.jetbrains.android.run.AndroidRunningState.execute(AndroidRunningState.java:263) at com.intellij.execution.runners.DefaultProgramRunner.doExecute(DefaultProgramRunner.java:38) at org.jetbrains.android.run.AndroidDebugRunner.doExec(AndroidDebugRunner.java:144) at org.jetbrains.android.run.AndroidDebugRunner.doExecute(AndroidDebugRunner.java:135) at com.intellij.execution.runners.GenericProgramRunner$1.execute(GenericProgramRunner.java:48) at com.intellij.execution.impl.ExecutionManagerImpl$2.run(ExecutionManagerImpl.java:208) at com.intellij.openapi.project.DumbServiceImpl.runWhenSmart(DumbServiceImpl.java:95) at com.intellij.execution.impl.ExecutionManagerImpl$1$1.run(ExecutionManagerImpl.java:172) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:744) at java.awt.EventQueue.access$400(EventQueue.java:97) at java.awt.EventQueue$3.run(EventQueue.java:697) at java.awt.EventQueue$3.run(EventQueue.java:691) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75) at java.awt.EventQueue.dispatchEvent(EventQueue.java:714) at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:697) at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:524) at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:335) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93) at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) ```
2015/05/20
[ "https://Stackoverflow.com/questions/30345134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2738452/" ]
I Slove it by this step you should delete this file that you can do it . go to the path :"C:\Users\Administrator.android\avd" and delete all the avd folders files . try again ,you can get it.
### Why this happens ``` at com.android.sdklib.internal.avd.AvdManager.parseAvdInfo(AvdManager.java:1616) ``` The error seems to be in Android SDK library [Android Virtual Device Manager](https://developer.android.com/tools/help/avd-manager.html). It tries to open a file, and some argument in File constructor is null. ### Solution: > > I installed the needed plugins again..and it works > > > ### What else can be done in similar situations: 1. Plugin damaged -> reinstall the plugin. 2. SDK damaged -> reinstall Android SDK. 3. Wrong version used -> check the used version or update Android SDK.
1,930,062
My friend had an interview at Cambridge. He was asked the following question, and was stumped: > > I fly to Chicago. The plane trip is $8$ hours. I look at the time and then set my watch back $6$ hours. Knowing that the Earth rotates $360^\circ$ in $24$ hours, what is the radius of the Earth? > > >
2016/09/17
[ "https://math.stackexchange.com/questions/1930062", "https://math.stackexchange.com", "https://math.stackexchange.com/users/279340/" ]
There is not enough information in the question to get anywhere near an estimate of the earth's radius. Even if we assume that "setting your watch back 6 hours" means that the difference in *longitude* between the two points is exactly 90°, the question still doesn't specify the **latitude** of the two cities. And, of course, to get from a question where all the givens are *time* to an answer with the dimension of *length*, we would need to know the (ground) **speed** of the plane too. To see concretely how there is too little information, Some *other* possible scenarios with a plane that flies with the same ground speed (and on the same earth) would be: > > You fly from Frankfurt am Main to Santiago de Chile. It takes 15 hours, and when you arrive you set your watch back 6 hours. > > > or > > You fly from Stockholm to Lagos. It takes 8 hours, and when you arrive you set your watch back 1 hour. > > > or even > > You fly from Nuuk to Comodoro Rivadavia. It takes 15 hours, and when you arrive you set your watch back 1 hour. > > > If the problem was solvable with the given information, there would need to be a method that gave the *same* radius of the earth when given the inputs $(8,6)$ as for $(15,6)$ and $(8,1)$ and $(15,1)$. [Distance sources](http://www.gcmap.com/mapui?P=cbg-ord,+fra-scl,+arn-los,+goh-crd).
My guess is that the interviewer was not expecting to get an exact answer, but was looking to see how confident your friend was at making their own approximations and working using those. For example, here are two guestimates that, if correct, would provide the information that is needed as previous answers have pointed out: * Chicago and England have similar climates so there's probably not too much difference in latitude. They aren't close to the equator and aren't close to the pole, so let's guess about halfway between. i.e. latitude of 45 degrees. * I know that military jets go supersonic, but you're probably talking about a commercial jet here and they don't. Let's guess about half the speed of sound: i.e. about 150m/s Note that these estimates are incredibly crude, but they're reasoned and would have given your friend something to do that the interviewer could have judged. p.s. A good source to emulate for this sort of crude estimation is the xkcd [What If?](https://what-if.xkcd.com/4/) articles, which use guesses like these to insight into situations much further from normal human experience.
332,474
I've just installed Ubuntu 12.04 yesterday, and i'm having problems watching video's on YouTube. Once I get to full screen the frame rate drops to 16fps. My PC runs the latest games on very high, so I don't think my hardware would be a problem. I'm using Chromium, but Firefox has the same issue. Other flash based streaming videos work fine (like twitch.tv). It's the same low frame rate between HTML5 and Flash. Basically it's a Youtube problem and not a flash issue.
2013/08/14
[ "https://askubuntu.com/questions/332474", "https://askubuntu.com", "https://askubuntu.com/users/184001/" ]
Sadly Adobe Flash 11.2 has a blacklist of graphics cards which it will not allow to use hardware acceleration, even with a good card, so it's just luck if yours is supported and on the white list... You could try installing MiniTube and gstreamer0.10-ffmpeg which allows you to search and play YouTube videos full screen using system codecs instead of the flash player...
Maybe this helps, but I'm not sure. Switch to full screen and click the right mouse button and then click on Configurations and try to activate or deactivate graphic acceleration. I once had problems with YouTube and this solved it.
40,349,038
I have a UIView at my view controller. And I want to draw some labels programmatically at the screen. So I thought I can subclass it and at that class to the UIView. My code: ``` import Foundation import UIKit class MainBottomView : UIView{ required init?(coder aDecoder: NSCoder) { super.init(frame: UIScreen.main.bounds); generateLabel(CGRect(x: 5, y: 363, width: 310, height: 62),tekst: "") return; } func generateLabel(_ fr: CGRect,tekst: String){ let l = UILabel(frame: fr) l.backgroundColor = UIColor(red: (21/255.0),green: (185/255.0),blue:(201/255.0),alpha:1) l.textAlignment = NSTextAlignment.center l.text = tekst l.textColor = UIColor.white l.font = UIFont(name: "HelveticaNeue", size: 23) self.addSubview(l) } } ``` But it crashes at the required init? row. I don't know why this is happening. Or did I use subclassing at the wrong way? Thank you very much!
2016/10/31
[ "https://Stackoverflow.com/questions/40349038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4477850/" ]
If you’d like to create conformance profiles by scratch, or by generating rules from existing messages then I recommend you use the HL7 Soup tool. They have a video on the subject here that will cover how to create the rules, and get you started. <http://www.hl7soup.com/ValidateHighlightAndCompare.html> Once you’ve created the profile it can be exported to others.
To build conformance profiles from scratch or from existing messages, you may take a look at Caristix Conformance (<http://caristix.com/hl7-tools/conformance/scope-hl7-interfaces/>). Once you have the conformance profile set, you can compare it with another profile (or set of messages) an get a gap analysis report. This tool is much easier to use than Messaging Workbench. Disclaimer: I'm part of the team developing this tool.
136,359
I have the below screen that shows a list of items. The list can sometimes be long and sometimes short. When the list is long, the UI looks okay, but when it is short, the screen looks a little boring. Is there any suggestion to improve the display in this scenario? [![Display of two phone mockups; one has only two items, the other has many](https://i.stack.imgur.com/fU5tq.png)](https://i.stack.imgur.com/fU5tq.png) Context: * This is an app for a IOT device. * This screen comes in the middle of the user guide/on-board screens.
2021/01/18
[ "https://ux.stackexchange.com/questions/136359", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/141727/" ]
### The first screen isn't "boring," it's "focused." A user will be task-driven and goal-oriented during this setup process. Rather than looking to be entertained or stimulated (as with a news or social media application), they're trying to get a task completed. If the user happens to see fewer options during this step, it will actually help them complete their tasks easier.
A footer after the final list item (with, say, the number of results) may help indicate that the user has seen all the possible results. [![mockup with a list footer appended after the results.](https://i.stack.imgur.com/1HpQf.png)](https://i.stack.imgur.com/1HpQf.png) (Please excuse my art skills)
50,275,945
I create an Angular app that search students from API. It works fine but it calls API every time an input value is changed. I've done a research that I need something called debounce ,but I don't know how to implement this in my app. **App.component.html** ``` <div class="container"> <h1 class="mt-5 mb-5 text-center">Student</h1> <div class="form-group"> <input class="form-control form-control-lg" type="text" [(ngModel)]=q (keyup)=search() placeholder="Search student by id or firstname or lastname"> </div> <hr> <table class="table table-striped mt-5"> <thead class="thead-dark"> <tr> <th scope="col" class="text-center" style="width: 10%;">ID</th> <th scope="col" class="text-center" style="width: 30%;">Name</th> <th scope="col" style="width: 30%;">E-mail</th> <th scope="col" style="width: 30%;">Phone</th> </tr> </thead> <tbody> <tr *ngFor="let result of results"> <th scope="row">{{result.stu_id}}</th> <td>{{result.stu_fname}} {{result.stu_lname}}</td> <td>{{result.stu_email}}</td> <td>{{result.stu_phonenumber}}</td> </tr> </tbody> </table> </div> ``` **App.component.ts** ``` import { Component} from '@angular/core'; import { Http,Response } from '@angular/http'; import { Subject, Observable } from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { results; q = ''; constructor(private http:Http) { } search() { this.http.get("https://www.example.com/search/?q="+this.q) .subscribe( (res:Response) => { const studentResult = res.json(); console.log(studentResult); if(studentResult.success) { this.results = studentResult.data; } else { this.results = []; } } ) } } ``` **Screenshot** [![Screenshot](https://i.stack.imgur.com/mt9mt.png)](https://i.stack.imgur.com/mt9mt.png) I've tried something like this but it's error **Property debounceTime does not exist on type Subject<{}>** ``` mySubject = new Subject(); constructor(private http:Http) { this.mySubject .debounceTime(5000) .subscribe(val => { //do what you want }); } ``` and this's also not work. **Property 'fromEvent' does not exist on type 'typeof Observable'** ``` Observable.fromEvent<KeyboardEvent>(this.getNativeElement(this.term), 'keyup') ``` So, what's the correct way to implement this ? Thank you.
2018/05/10
[ "https://Stackoverflow.com/questions/50275945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If you are using angular 6 and rxjs 6, try this: Notice the `.pipe(debounceTime(1000))` before your `subscribe` ``` import { debounceTime } from 'rxjs/operators'; search() { this.http.get("https://www.example.com/search/?q="+this.q) .pipe(debounceTime(1000)) .subscribe( (res:Response) => { const studentResult = res.json(); console.log(studentResult); if(studentResult.success) { this.results = studentResult.data; } else { this.results = []; } } ) } ```
user.component.html ``` <input type="text" #userNameRef class="form-control" name="userName" > <!-- template-driven --> <form [formGroup]="regiForm"> email: <input formControlName="emailId"> <!-- formControl --> </form> ``` user.component.ts ``` import { fromEvent } from 'rxjs'; import { switchMap,debounceTime, map } from 'rxjs/operators'; @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.css'] }) export class UserComponent implements OnInit { constructor(private userService : UserService) { } @ViewChild('userNameRef') userNameRef : ElementRef; emailId = new FormControl(); regiForm: FormGroup = this.formBuilder.group({ emailId: this.bookId }); ngOnInit() { fromEvent(this.userNameRef.nativeElement,"keyup").pipe( debounceTime(3000), map((userName : any) =>userName.target.value ) ).subscribe(res =>{ console.log("User Name is :"+ res); } ); //--------------For HTTP Call------------------ fromEvent(this.userNameRef.nativeElement,"keyup").pipe( debounceTime(3000), switchMap((userName : any) =>{ return this.userService.search(userName.target.value) }) ).subscribe(res =>{ console.log("User Name is :"+ res); } ); ---------- // For formControl this.emailId.valueChanges.pipe( debounceTime(3000), switchMap(emailid => { console.log(emailid); return this.userService.search(emailid); }) ).subscribe(res => { console.log(res); }); } ``` **\*Note: make sure that your input element is not present in *ngIf Block.***
7,388,397
Hi please help me out in getting regular expression for the following requirement I have string type as ``` String vStr = "Every 1 nature(s) - Universe: (Air,Earth,Water sea,Fire)"; String sStr = "Every 1 form(s) - Earth: (Air,Fire) "; ``` from these strings after using regex I need to get values as `"Air,Earth,Water sea,Fire"` and `"Air,Fire"` that means after ``` String vStrRegex ="Air,Earth,Water sea,Fire"; String sStrRegex ="Air,Fire"; ``` All the strings that are input will be seperated by `":"` and values needed are inside brackets always Thanks
2011/09/12
[ "https://Stackoverflow.com/questions/7388397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11114/" ]
The regular expression would be something like this: ``` : \((.*?)\) ``` Spelt out: ``` Pattern p = Pattern.compile(": \\((.*?)\\)"); Matcher m = p.matcher(vStr); // ... String result = m.group(1); ``` This will capture the content of the parentheses as the first capture group.
If you have each string separately, try this expression: `\(([^\(]*)\)\s*$` This would get you the content of the last pair of brackets, as group 1. If the strings are concatenated by `:` try to split them first.
31,175,158
Example I have 10 textbox and each has the same attribute with different value, say for example they have an attribute `data-same` with different value and I have something like this in my code `$('#test').each(function(){ $(this).val(); });` and I want to filter the result using the attribute of each textbox. How would I do it? I was thinking on doing something like this `$('#test').each(function(){ $('[data-same="val1"]',this).val(); });` but I'm not sure about it.
2015/07/02
[ "https://Stackoverflow.com/questions/31175158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Use [**attr()**](http://api.jquery.com/attr/) ``` $('#test').each(function(){ var attributeValue = $(this).attr('data-same'); //do whatever you want with the value }); ``` Also, your code indicates you have the same ID for multiple elements. Avoid that and use classes or attributes instead. ``` $('[data-same]').each(function(){ var attributeValue = $(this).attr('data-same'); //do whatever you want with the value }); ``` See [Why is it a bad thing to have multiple HTML elements with the same id attribute?](https://stackoverflow.com/questions/7505350/why-is-it-a-bad-thing-to-have-multiple-html-elements-with-the-same-id-attribute)
Ok If my assumption is correct you want to get all the `textbox` with same attribute then below code will work and I would suggest keep an unique `id`: to each elements and you can try with `classname` instead say `class="test"`: ``` var sameTextBox=[]; $('.test').each(function(){ //change this selector to class if($(this).attr('data-same')=="somevalue") //otherwise you can try //if($(this).data('same')=="somevalue") { sameTextBox.push($(this)); } }); ```
39,500,556
In this program after rolling a die "x" amount of times (userInput) I'm wanting to count the number of times each number occurs. I tried making an else if that would add one to each random number occurrence but it only seems to work with the last random number, maybe it's because the if isn't in the while loop? I'm not sure how I would add the ifss and else ifs in the while loop... Perhaps I'm over-complicating this ``` System.out.println("Enter the number of times a 6 sided die " + "should\nbe rolled"); Random r = new Random(); int numberOfRolls = userInput.nextInt(); int randomRoll; int timesRolled = 0; if (numberOfRolls <= 0) { System.out.println("Nope, that's below zero"); System.exit(0); } do { timesRolled++; randomRoll = r.nextInt(6) + 1; System.out.println(randomRoll + " was rolled"); } while (numberOfRolls > timesRolled); int numberOne = 0; int numberTwo = 0; int numberThree = 0; int numberFour = 0; int numberFive = 0; int numberSix = 0; if (randomRoll == 1) { numberOne ++; } else if (randomRoll == 2) { numberTwo ++; } else if (randomRoll == 3) { numberThree ++; } else if (randomRoll == 4) { numberFour ++; } else if (randomRoll == 5) { numberFive ++; } else if (randomRoll == 6) { numberSix ++; } System.out.println(" One: " +numberOne+ "\n Two: " +numberTwo+ "\n Three: " +numberThree+ "\n Four: " +numberFour+ "\n Five: " +numberFive+ "\n Six: " +numberSix); } ``` **The output is:** ``` > Enter the number of times a 6 sided die should be rolled 3 2 was rolled 5 was rolled 1 was rolled One: 1 Two: 0 Three: 0 Four: 0 Five: 0 Six: 0 ```
2016/09/14
[ "https://Stackoverflow.com/questions/39500556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6832979/" ]
No need for jQuery, use a [`Array.forEach()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) like this: ``` var dates = []; var clientCosts = []; $.ajax({ url: 'inc/wip-data.php', dataType: 'json' }).done(function(data) { data.forEach(function(item) { dates.push(item.date); clientCosts.push(item.clientCostsTotal); }); }); ``` For a more functional approach, you might want to try using [`Array.reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) which gives you the ability to generate multiple result arrays while still iterating through the source data only once. Here's a function implemented using `.reduce()` that will take any array structured like you have it and collate those results into a result. This function is generic, would work for any property names defined in the source. ```js function collate(d) { return d.reduce(function(prev, cur, index) { var ret = {}; for (var prop in cur) { if (index === 0) { ret[prop] = []; } else { ret[prop] = prev[prop]; } ret[prop].push(cur[prop]); } return ret; }, {}); } var data = [{ "date": "2015-10", "clientCostsTotal": "0.00" }, { "date": "2015-11", "clientCostsTotal": "0.00" }, { "date": "2016-01", "clientCostsTotal": "0.00" }, { "date": "2016-02", "clientCostsTotal": "0.00" }, { "date": "2016-03", "clientCostsTotal": "0.00" }, { "date": "2016-04", "clientCostsTotal": "27962.50" }, { "date": "2016-05", "clientCostsTotal": "174060.00" }, { "date": "2016-06", "clientCostsTotal": "309000.00" }, { "date": "2016-07", "clientCostsTotal": "502261.50" }, { "date": "2016-08", "clientCostsTotal": "7598.00" }, { "date": "2016-12", "clientCostsTotal": "0.00" }]; var reduced = collate(data); console.log(reduced.date, reduced.clientCostsTotal); ```
My preference is to use lodash for operations involving arrays. The [lodash api has a function called map](https://lodash.com/docs/4.15.0#map) which meets your requirements nicely. Here is an example: ``` var jsonArray = [ { "date": "2015-10", "clientCostsTotal": "0.00" }, { "date": "2015-11", "clientCostsTotal": "0.00" }, { "date": "2016-01", "clientCostsTotal": "0.00" }]; var dateValues = _.map(jsonArray, 'date'); var clientTotalCostValues = _.map(jsonArray, 'clientCostsTotal'); console.log('dateValues = ', dateValues); console.log('clientTotalCostValues = ', clientTotalCostValues ); ``` Outputs the following: ``` dateValues = ["2015-10", "2015-11", "2016-01"] clientTotalCostValues = ["0.00", "0.00", "0.00"] ``` You can test it out quickly for yourself by going to the [lodash api docs page](https://lodash.com/docs/) open your browsers dev tools and paste my code snippet into the console and hit enter.
6,944,910
Given the code: ``` uint Function(uint value) { return value * 0x123456D; } ``` Inputting the value 0x300 yields the result 0x69D04700. This is only the lower 32 bits of the result. Given the result 0x69D04700 and the factor 0x123456D, is it possible to retrieve all numbers such that (value \* 0x123456D) & 0xFFFFFFFF = 0x69D04700 in a fast way? Edit: The code I show is pseudocode - I can't widen the return type.
2011/08/04
[ "https://Stackoverflow.com/questions/6944910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/553294/" ]
What you need is modular division, which can be computed with a version of Euclid's algorithm. In this case the result is 768. This is very fast -- time (log *n*)2 even for a naive implementation. (If you needed to work with large numbers I could give references to better algorithms.) See [extended Euclidean algorithm](http://en.wikipedia.org/wiki/Modular_multiplicative_inverse#Extended_Euclidean_Algorithm) for a sketch of how to implement this.
Your function: ``` uint Function(uint value) { return value * 0x123456D; } ``` multiplies in `uint` (which works just like the integers modulo `2**64` in so-called `unchecked` context) by an *odd* number. Such an odd number has a unique inverse, modulo `2**64`. In this case it is `0xE2D68C65u`, because as you may check (C# syntax): ``` unchecked(0x123456Du * 0xE2D68C65u) == 1u ``` This multiplication is associative and commutative. So your "reverse" method is: ``` uint UndoFunction(uint value) { return value * 0xE2D68C65u; } ``` (`unckecked` context assumed). For any input `x`, both `UndoFunction(Function(x))` and `Function(UndoFunction(x))` give you back the original `x`. --- PS! To find the modular inverse `0xE2D68C65u`, I used something other than .NET. Actually GP/PARI like Charles in his answer. In GP, you can do `1/Mod(19088749, 2^32)` or `Mod(19088749, 2^32)^-1`. It uses decimal notation by default.
16,825,305
So I have a bunch of files like: ``` Aaron Lewis - Country Boy.cdg Aaron Lewis - Country Boy.mp3 Adele - Rolling In The Deep.cdg Adele - Rolling In The Deep.mp3 Adele - Set Fire To The Rain.cdg Adele - Set Fire To The Rain.mp3 Band Perry - Better Dig Two.cdg Band Perry - Better Dig Two.mp3 Band Perry - Pioneer.cdg Band Perry - Pioneer.mp3 ``` and I need to have the leading whitespace removed in bash or fish script.
2013/05/29
[ "https://Stackoverflow.com/questions/16825305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2418049/" ]
To remove the leading white space char in the file names you provided you can use: ``` IFS=$'\n' for f in $(find . -type f -name ' *') do mv $f ${f/\.\/ /\.\/} done ``` This: * changes the IFS to only be newline characters; this way it does not choke on the whitespaces in the file names. * finds all files starting with a whitespace in the current directory. * moves each file to a file name without the leading whitespace, using `bash` substring substitution.
`cat <file> | sed -e 's/^[ ]*//'` should do the trick. Capture stdout and write to a file.
11,692,575
I have an app working that is `GPS` based. It has many activities and all use the `GPS`. For example, one activity shows the distance to a location, another shows the speed and direction. I set up and call `requestLocationUpdates()` in `onCreate()` and call `removeUpdates()` in `onPause()`. This all works but the `GPS` blinks and has to re-acquire when switching activities. I did a test and if I put the `removeUpdates()` in `onStop()` instead of in `onPause()` there is no blinking. Apparently `onStop()` is called after the new activity starts which explains the lack of blinking. I have read the posts on this subject and there seems to be a difference of opinion. However, it looks like I should use `onStop()` and am wondering if there is any reason I should not. The second issue is that there is no `onResume()` code so there is no `GPS` after a back-arrow or after turning the screen off and on. I should fix this. Right now my `onCreate()` code creates the location manager and basically has all my code in it. It looks like following the life cycle flow chart that I should move the `removeUpdates()` to onStop and move the creation of the lm and ll to `onStart()`. Is this correct? Here is my `onCreate()` code: ``` @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.set); textView1 = (TextView)findViewById(R.id.textView1); lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); ll = new mylocationlistener(); lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll); } ``` Here is my onPause code: ``` @Override protected void onPause() { super.onPause(); if(lm != null) { lm.removeUpdates(ll); } ll = null; lm = null; } ``` So I think I should just change the onPause() to onStop() and make onStart() this: ``` @Override public void onStart() { super.onStart(); lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); ll = new mylocationlistener(); lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll); } ``` And my onCreate code as this; ``` @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.set); textView1 = (TextView)findViewById(R.id.textView1); } ``` This said, I am kind of new to all this and this is my first application so I would like to know what I am missing here.
2012/07/27
[ "https://Stackoverflow.com/questions/11692575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1510255/" ]
I've done something similar to your app, except that I've delegated the GPS functionality to a service which stops the GPS when no activities are bound to it and starts it when an activity binds to it. I bind to the service in the onStarts and unbind in the onStops. Logging the on.. methods when I switch activities gives a sequence like this: ``` FIRST Activity onCreate FIRST Activity onStart FIRST Activity onResume FIRST Activity onPause SECOND Activity onCreate SECOND Activity onStart SECOND Activity onResume FIRST Activity onStop ``` If done it via a service so that I've only got one LocationManager to control, you could either take the same approach, or requestUpdates in the onStarts() and remove them in the onStops()
First of all I'd suggest following good read about [location strategies](http://developer.android.com/guide/topics/location/strategies.html). If you just want a one-time location fix you need to make it a bit more independent from the activity life cycle because acquiring the GPS location can take longer than the user switches your activities. So don't stop the request in onPause or onStop. You could use a special location query handler that lives as a singleton instance in your Application object (create a derivative of Application for that). Tell that location handler to get a fresh fix if necessary in your activities' onStart or onResume method for example. Let the handler keep the latest and best location data which can be immediately used as needed. You could query for the first time a NETWORK\_PROVIDER location because this should be faster than GPS and you immediately have something to work with even though it's not accurate. On top of that you'd also get a location in case the user turned off the GPS module. However, that depends on how accurate the result has to be. You could also create a local service that queries the GPS location and waits for its result to come. When the result is there you can notify your currently running activity via a local broadcast intent. In any case, you can get the last known location with locationManager.getLastKnownLocation
45,367,609
I want to add the plugin in the maven project. I want it to be added to build only when I build the project for testing purpose. I found that `<scope>` can be used for dependency as shown below ``` <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback</artifactId> <version>0.5</version> <scope>test</scope> </dependency> ``` As you can see here `<scope>test</scope>`is used. I want similar thing for plugin. For example this is my plugin code snipplet ``` <build> <plugins> <plugin> <groupId>org.jibx</groupId> <artifactId>jibx-maven-plugin</artifactId> <version>1.2.4</version> <executions> <execution> <goals> <goal>bind</goal> </goals> </execution> </executions> </plugin> </plugins> </build> ```
2017/07/28
[ "https://Stackoverflow.com/questions/45367609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4185515/" ]
**Swift 4.2 , XCode 10 , ios 12 , 2018 Answer** ``` self.children.forEach{$0.willMove(toParent: nil);$0.view.removeFromSuperview();$0.removeFromParent()} ``` Hope it is helpful to someone
``` if self.childViewControllers.count > 0{ let viewControllers:[UIViewController] = self.childViewControllers for viewContoller in viewControllers{ viewContoller.willMove(toParentViewController: nil) viewContoller.view.removeFromSuperview() viewContoller.removeFromParentViewController() } } ```
3,649,662
In my project i have used master page.In one particular page , i want a function to be executed on page unload(javascript event) event of that particular page.To achieve this i have written ``` $('body').bind('unload',function() { alert('hello'); } ); ``` But this is not working.This function is not getting called when i move to other page. How should i achieve this.
2010/09/06
[ "https://Stackoverflow.com/questions/3649662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/340183/" ]
Well, I suppose its a problem when writing the question but your code should be: ``` $(window).bind('unload',function() { alert('hello'); }); ``` You are missing the ending ); and the event should be bound to the window... [Edit: Added the bind to the window instead of `'body'`]
``` $(window).bind("unload", function(){ alert(123); }); ``` worked for me :)
5,161,850
I'm being forced to send data via GET (query string) to another server. ``` For example: http://myserver.com/blah?data=%7B%22date%22%3A%222011-03-01T23%3A46%3A43.707Z%22%2C%22str%22%3A%22test%20string%22%2C%22arr%22%3A%5B%22a%22%2C%22b%22%2C%22c%22%5D%7D ``` It's a JSON encoded string. However, anyone with half a brain can see that and decode it to get the underlying data. 1. I understand that the query string is limited in length 2. I don't have a choice about using GET vs PUT/POST Is there a way for me to encode a lot of data in a much shorter string that can be decrypted from the server? (using javascript) I suppose HTTPS doesn't actually resolve this since the data is in the uri?
2011/03/01
[ "https://Stackoverflow.com/questions/5161850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302064/" ]
HTTPS resolves it -- even the data in the HTTP header (including the URI) is protected, since the whole connection happens over an SSL channel. There is one exception: the host name will be exposed if the client uses a proxy, since it is transmitted in the clear in the CONNECT request.
* HTTPS is indeed a solution for protecting your data. It first creates a secure connection to the server (via TLS) using IP address and port. -then all the HTTP packets are sent over this connection encrypted. ( [Is GET data also encrypted in HTTPS?](https://stackoverflow.com/questions/4143196/is-get-data-also-encrypted-in-https)) * The practical limit for URL length seems to be somewhat around 1000 chars ( [What is the maximum length of a URL in different browsers?](https://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-an-url)) * And there are quite a couple of compression snippets around... ( [JavaScript implementation of Gzip](https://stackoverflow.com/questions/294297/javascript-implementation-of-gzip))
53,862,521
Suppose I have the following data frame: ``` 0 1 2 new NaN NaN new one one a b c NaN NaN NaN ``` How would I get the number of unique (non-NaN) values in a row, such as: ``` 0 1 2 _num_unique_values new NaN NaN 1 new one one 2 a b c 3 NaN NaN NaN 0 ``` I suppose it would be something along the lines of: ``` df['_num_unique_values'] = len(set(df.loc.tolist())) ?? ```
2018/12/20
[ "https://Stackoverflow.com/questions/53862521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Just use nunique(axis=1). ``` import numpy as np import pandas as pd data={0:['new','new','a',np.nan], 1:[np.nan,'one','b', np.nan], 2:[np.nan,np.nan,'c',np.nan]} df = pd.DataFrame(data) # print(df.nunique(axis=1)) df['num_unique'] = df.nunique(axis=1) ```
A more abstract solution: ``` df['num_uniq']=df.nunique(axis=1) ```
51,359,783
I am trying to convert JSON to CSV file, that I can use for further analysis. Issue with my structure is that I have quite some nested dict/lists when I convert my JSON file. I tried to use pandas `json_normalize()`, but it only flattens first level. ``` import json import pandas as pd from pandas.io.json import json_normalize from cs import CloudStack api_key = xxxx secret = xxxx endpoint = xxxx cs = CloudStack(endpoint=endpoint, key=api_key, secret=secret) virtual_machines = cs.virtMach() test = json_normalize(virtual_machines["virtualmachine"]) test.to_csv("test.csv", sep="|", index=False) ``` Any idea how to flatter whole JSON file, so I can create single line input to CSV file for single (in this case virtual machine) entry? I have tried couple of solutions posted here, but my result was always only first level was flattened. This is sample JSON (in this case, I still get "securitygroup" and "nic" output as JSON format: ``` { "count": 13, "virtualmachine": [ { "id": "1082e2ed-ff66-40b1-a41b-26061afd4a0b", "name": "test-2", "displayname": "test-2", "securitygroup": [ { "id": "9e649fbc-3e64-4395-9629-5e1215b34e58", "name": "test", "tags": [] } ], "nic": [ { "id": "79568b14-b377-4d4f-b024-87dc22492b8e", "networkid": "05c0e278-7ab4-4a6d-aa9c-3158620b6471" }, { "id": "3d7f2818-1f19-46e7-aa98-956526c5b1ad", "networkid": "b4648cfd-0795-43fc-9e50-6ee9ddefc5bd" "traffictype": "Guest" } ], "hypervisor": "KVM", "affinitygroup": [], "isdynamicallyscalable": false } ] } ```
2018/07/16
[ "https://Stackoverflow.com/questions/51359783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3668922/" ]
I used the following function (details can be found [here](https://towardsdatascience.com/flattening-json-objects-in-python-f5343c794b10)): ``` def flatten_data(y): out = {} def flatten(x, name=''): if type(x) is dict: for a in x: flatten(x[a], name + a + '_') elif type(x) is list: i = 0 for a in x: flatten(a, name + str(i) + '_') i += 1 else: out[name[:-1]] = x flatten(y) return out ``` This unfortunately completely flattens whole JSON, meaning that if you have multi-level JSON (many nested dictionaries), it might flatten everything into single line with tons of columns. What I used, in the end, was `json_normalize()` and specified structure that I required. A nice example of how to do it that way can be found [here](https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#normalization).
In case anyone else finds themselves here and is looking for a solution better suited to subsequent programmatic treatment: Flattening the lists creates the need to process the headings for list lengths etc. I wanted a solution where if there are 2 lists of e.g. 2 elements then there would be four rows generated yielding each valid potential data row (see below for actual examples): ``` class MapFlattener: def __init__(self): self.headings = [] self.rows = [] def add_rows(self, headings, rows): self.headings = [*self.headings, *headings] if self.rows: new_rows = [] for base_row in self.rows: for row in rows: new_rows.append([*base_row, *row]) self.rows = new_rows else: self.rows = rows def __call__(self, mapping): for heading, value in mapping.items(): if isinstance(value, Mapping): sub_headings, sub_rows = MapFlattener()(value) sub_headings = [f'{heading}:{sub_heading}' for sub_heading in sub_headings] self.add_rows(sub_headings, sub_rows) continue if isinstance(value, list): self.add_rows([heading], [[e] for e in value]) continue self.add_rows([heading], [[value]]) return self.headings, self.rows def map_flatten(mapping): return MapFlattener()(mapping) ``` This creates output more in line with relational data: ``` In [22]: map_flatten({'l': [1,2]}) Out[22]: (['l'], [[1], [2]]) In [23]: map_flatten({'l': [1,2], 'n': 7}) Out[23]: (['l', 'n'], [[1, 7], [2, 7]]) In [24]: map_flatten({'l': [1,2], 'n': 7, 'o': {'a': 1, 'b': 2}}) Out[24]: (['l', 'n', 'o:a', 'o:b'], [[1, 7, 1, 2], [2, 7, 1, 2]]) In [25]: map_flatten({'top': {'middle': {'bottom': [0, 1]}, 'ml': ['A', 'B']}, 'l': ['a', 'b']}) Out[25]: (['top:middle:bottom', 'top:ml', 'l'], [[0, 'A', 'a'], [0, 'A', 'b'], [0, 'B', 'a'], [0, 'B', 'b'], [1, 'A', 'a'], [1, 'A', 'b'], [1, 'B', 'a'], [1, 'B', 'b']]) ``` This is particularly useful if you are using the csv in spreadsheets etc. and need to process the flattened data.
46,544,118
``` NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-type"]; [request setHTTPBody:jsonData]; // configure NSURLSessionConfiguration with request timeout NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration]; // set request timeout defaultConfigObject.timeoutIntervalForRequest = 120.0; // create NSURLSession object // Working fine with below instance of default session but its taking a lot of time to fetch response. //NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject]; NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]]; // set NSURLSessionDataTask @try { NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { // }]; [dataTask resume]; } ```
2017/10/03
[ "https://Stackoverflow.com/questions/46544118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4011722/" ]
The task never completes because it never gets started. You have to manually start the data task using its resume() method. And Don't use the dataTask object inside the try block.
``` if ([self checkNetworkStatus]) { @try { // Create the data and url NSString *encryptedString = [self createRequest:userContext objectType:deviceObjectType projectType:projectId]; NSDictionary *dictRequest = @{REQ_KEY_REQUEST: encryptedString}; requestString = [JSONHelper dictionaryToJson:dictRequest]; NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@Data",globals.API_Base_URL]]; // Create Request NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0]; request.HTTPMethod = @"POST"; // For Post [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; int strLength = (int)requestString.length; [request setValue:[NSString stringWithFormat:@"%d", strLength] forHTTPHeaderField:@"Content-Length"]; NSData *dataRequest = [requestString dataUsingEncoding:NSUTF8StringEncoding]; request.HTTPBody = dataRequest;`enter code here` id delegateValue = self; NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:delegateValue delegateQueue:[NSOperationQueue mainQueue]]; //NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *responseData, NSURLResponse *response, NSError *error) { // ... [self destroyNetworkCache]; // [[NSURLCache sharedURLCache] storeCachedResponse:nil forRequest:urlReq]; [[NSURLCache sharedURLCache] removeAllCachedResponses]; dispatch_async(dispatch_get_main_queue(), ^(void) { if (! error) { [self parseResponse:responseData forObjectType:deviceObjectType andTag:tag withDelegate:del]; } else { NSString *errMsg = error.description; if (errMsg.length <= 0) { errMsg = NSLocalizedString(@"msg_network_error", @"msg_network_error"); } else if (errMsg.length > 0 && [errMsg rangeOfString:@"timed out"].length != 0) { errMsg = NSLocalizedString(@"msg_request_timed_out", @"msg_request_timed_out"); } else if ([self checkForURLDomainError:errMsg]) { errMsg = NSLocalizedString(@"msg_network_error", @"msg_network_error"); } if (tag < 0) { if ([del conformsToProtocol:@protocol(WTConnectionServiceDelegate)]) { if ([del respondsToSelector:@selector(wtConnectionService:forObjectType:didFailedWithError:)]) { [del wtConnectionService:nil forObjectType:deviceObjectType didFailedWithError:errMsg]; return; } } } else { if ([del conformsToProtocol:@protocol(WTConnectionServiceDelegate)]) { if ([del respondsToSelector:@selector(wtConnectionService:forObjectType:andTag:didFailedWithError:)]) { [del wtConnectionService:nil forObjectType:deviceObjectType andTag:tag didFailedWithError:errMsg]; return; } } } } }); }]; [task resume]; } @catch (NSException *exception) { [self handleException:exception]; } @finally { } } Below Is delegate methods -(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]); } -(void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error{ } ```
26,228,674
I am writing a program that reads from multiple audio and video devices and writes the data to suitable containers (such as mpeg). I have wrote the code in Linux, but now I have to write another version for windows as well. This is how I wrote it in Linux: ``` initialize the devices (audio: ALSA, video: V4L2) get the file descriptors mainloop select on file descriptors respond to the proper device ``` Unfortunately my expertise is only for Linux and I have never used windows SDK. I don't know what the right paradigm is. Do people do it the same way with the fds and select? In that case is there a way to get a fd from directshow? Oh and one last thing, I am bound to use only one thread for all of this. So the solution with multiple threads running at the same time and each handling one device is not admissible. The code in Linux currently runs on one thread as well. It is also preferred that the code should be written in c++. Thank you. **Second Thoughts** There is only one question asked here and that is: How can one get the file descriptor of the video/audio device from DirectShow library. People who have worked with V4L2 and ALSA, I am looking for the same thing in DirectShow.
2014/10/07
[ "https://Stackoverflow.com/questions/26228674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2308801/" ]
Roman is an expert in these topics and I don't think you'll find a better answer. To add to Roman's answer, you would do something like this in DirectShow: ``` Enumerate video/audio capture devices/select capture device Construct DirectShow graph Add video and audio capture source filters to graph Add 2 sample grabbers to graph Configure sample grabber callbacks Connect capture source filters to samples grabbers Add renderers to graph (This could be a null renderer or a video/audio renderer) Connect sample grabbers to renderers Play graph Run the event loop DirectShow will invoke the callbacks per media sample traversing the graph. ``` Your graph would typically look like this: ``` callback | Video capture -- sample grabber -- renderer Audio capture -- sample grabber -- renderer | callback ``` As Roman said, there are many samples in the SDK showing how to * enumerate capture sources * use/configure the sample grabber * write an application in which you construct and play a graph On the topic of threading, you'll be writing the code for the main application thread, and DirectShow will handle the internal thread management. However note that if your callback function is processing intensive, it may interfere with playback since (From [MSDN](http://msdn.microsoft.com/en-us/library/windows/desktop/dd376992(v=vs.85).aspx)): > > The data processing thread blocks until the callback method returns. If the callback does not return quickly, it can interfere with playback. > > > This may or may not be important depending on your application requirements. If it is important you could e.g. pass the data to another thread for processing. The result of blocking the data processing thread is that you'll get lower framerates in the case of video.
Windows offers several APIs for video and audio, which happens because older APIs were replaced with [supposed] descendants, however older APIs remained operational to maintain compatibility with existing applications. Audio APIs: `waveInXxx` family of functions, DirectSound, DirectShow, WASAPI Video APIs: Video for Windows, DirectShow, Media Foundation Video/audio APIs with support for video+audio streams and files: Video for Windows, DirectShow, Media Foundation All mentioned above offer certain functions, interfaces, methods, extensibility, compatibility options. I don't think fd, fds and select applies to any of the mentioned. For specific reasons one might prefer to use a combination of APIs, for example it is only WASAPI to give fine control over audio capture, however it is audio only API. Audio compression and production of media files, esp. video-enabled, is typically handled by DirectShow and Media Foundation. Video and audio devices don't have file descriptors. In DirectShow and Media Foundation you obtain interfaces/objects of respective capture device and then you can discover device capabilities such as supported formats in API specific way. Then you can either obtain the captured data or connect the capture component to another object such as encoding or presenting the data. Since file descriptors are not a part of the story in Windows, your question becomes basically unclear. Apparently you are asking for some guidelines from those familiar with both Linux and Windows development on how to implement in Windows what you are already doing in Linux, however I am afraid you will have to end up doing it in regular Windows way, how Windows API suggest and demonstrate in documentation and samples. -- DirectShow and Media Foundation APIs are covering the entire media processing pipeline steps: capture, processing, presentation. In DirectShow you build your pipeline using components "filters" connected together (MF has a similar concept) and then the higher level application controls their operation without touching actual data. The filters exchange with data without reporting to the application for every chunk of data streamed. This is why you might have a hard time finding a possibility to "get a raw frame". DirectShow design assumes that raw frames are passed between filters and are not sent to the calling application. Getting a raw frame is trivial for a connected filter, you are expected to express all media data processing needs in terms of DirectShow filters, stock or customized. Those who - for whatever reason - want to extract this media data stream from DirectShow pipeline often use so called Sample Grabber Filter (tens of questions on OS and MSDN forums), which is a stock filter easy to deal with capable to accept a callback function and report every piece of data streamed through. This filter is the easiest way to extract a frame from capture device with access to raw data. DirectShow and Media Foundation standard video capture capabilities are based on supporting analog video capture devices that exist in Windows through WDM driver. For them the APIs have a respective component/filter created and available which can be connected within the pipeline. Because DirectShow is relatively easily extensible, it is possible to put other devices into the same form factor of video capture filter, and this can cover third party capture devices available through SDKs, virtual cameras etc. Once they are put into DirectShow filter, they are available to other DirectShow-compatible applications, in particular basically seeing no difference whether it is an actual camera or just a software thing.
13,529
Suppose there is a doctor who wants a patient to cancel a planned abortion for the patient's safety. What should this doctor say? Can an English speaker please help me to fix the following sentence so that it would sound more natural? > > Please don't abort the baby, **you have to bear the baby** for your own safety. > > >
2013/11/23
[ "https://ell.stackexchange.com/questions/13529", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/2436/" ]
Instead of "bear the baby", you can say "carry the baby to term". This means to carry the baby until it's ready to be born. Unlike your phrase, it doesn't describe the birth itself. *Term* is short for *full term*. From [Collins](http://www.collinsdictionary.com/dictionary/english/term): > > **term**. *Also called:* **full term.** the period at which childbirth is imminent > > > *Carry* may be replaced with *bring*, but *carry* is more common.
As a doctor I would add the reason: For reasons of your own safety you should not think of abortion.
39,937,971
I am trying to call JavaScript `reset()` function by using button `onclick` method. The code is embedded in PHP as follows : ``` <?php echo "<form>"; echo "<input type='text' name='keyword'>"; echo "<input type='button' value='Clear' onclick='<script>reset();</script>'>"; echo "</form>"; ?> ``` The clear button is not working.
2016/10/08
[ "https://Stackoverflow.com/questions/39937971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3262077/" ]
ok i fixed it so the problem is that the parent fragmentstatepager loads fragmentA + fragmentB into memory, then the child fragmentstatepagers load there own childfragmentA + childfragmentB so we now have 2 parents and 4 children, onPrepareOptionsMenu is called from the child fragments so the the first is loaded childfragmentA(child of fragmentA) and then childFragmentA(child of fragmentB) is loaded and steals the search view, my 'fix' for this is probably a little crude i'm self taught and i'm not very aware of how to manage memory or if its bad to keep hold of references etc, i digress, in the parent fragment i check which fragment is visible using ``` setMenuVisibility(final boolean visible) ``` and in there i set a public static boolean and check for it in my childfragments and it works flawlessly for me as mentioned this is probably a terrible thing to do hopefully someone here can give a better solution ***check which parent is visible*** ``` public static boolean tabFragOneVisible; @Override public void setUserVisibleHint(boolean isVisible){ super.setUserVisibleHint(isVisible); if(!isVisible){ tabFragOneVisible = false; }else{ tabFragOneVisible = true; } } ``` ***check if parent is visible hook up search view*** ``` @Override public void onPrepareOptionsMenu(Menu menu) { // need to check if fragment is visible if (tabFragOne.tabFragOneVisible) { SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView(); SearchManager searchManager = (SearchManager) getActivity() .getSystemService(getActivity().SEARCH_SERVICE); searchView.setSearchableInfo(searchManager .getSearchableInfo(getActivity().getComponentName())); // searchView.setOnQueryTextListener(null); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { showResults(newText); return false; } }); } else{ } super.onPrepareOptionsMenu(menu); } ```
Maybe, it'll still help someone struggling to make one SearchView work for multiple Fragments. I found that onQueryTextListener would work on Fragment 1 (where the SearchView is initially created) but would not fire on Fragment 2,3, etc. Fragments 2 worked when onPrepareOptionsMenu is overridden and onViewCreated includes a setHasOptionsMenu(true). For example: ``` @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setHasOptionsMenu(true); ...the rest of your code goes here... } @Override public void onPrepareOptionsMenu(Menu menu) { MenuItem item = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) item.getActionView(); searchView.setOnQueryTextListener(this); super.onPrepareOptionsMenu(menu); } @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { Toast.makeText(getActivity(),"It Worked!!",Toast.LENGTH_SHORT).show(); return true; } ```
2,879,711
I want to be able to call a global function from an imported class, for example In file PetStore.py ``` class AnimalSound(object): def __init__(self): if 'makenoise' in globals(): self.makenoise = globals()['makenoise'] else: self.makenoise = lambda: 'meow' def __str__(self): return self.makenoise() ``` Then when I test in the Python Interpreter ``` >>> def makenoise(): ... return 'bark' ... >>> from PetStore import AnimalSound >>> sound = AnimalSound() >>> sound.makenoise() 'meow' ``` I get a 'meow' instead of 'bark'. I have tried using the solutions provided in [python-how-to-make-a-cross-module-variable](https://stackoverflow.com/questions/142545/python-how-to-make-a-cross-module-variable) with no luck.
2010/05/21
[ "https://Stackoverflow.com/questions/2879711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126406/" ]
The `globals()` call returns the globals of the module in which the call is *lexically* located; there is no intrinsic "dynamic scoping" in Python -- it's lexically scoped, like just about every modern language. The solid, proper way to obtain the effect you desire is to explicitly pass to the initializer of `AnimalSound` the callable it's supposed to use to "make noise": i.e., the class should be ``` class AnimalSound(object): def __init__(self, makenoise=lambda: 'meow'): self.makenoise = makenoise def __str__(self): return self.makenoise() ``` and the call should be ``` sound = AnimalSound(makenoise) ``` There are practicable but less-sound solutions, such as the caller passing its own `globals()` (but that needlessly constrains the name of the callable!), or even (shudder) communicating via covert channels like the other answer advocates (that would be a potential disaster if you had two instantiations of `AnimalSound` built according to the same principle in two separate modules, etc, etc). But, "explicit is better than implicit", and clean, safe, overt communication leads to clean, safe, robust system architectures: I earnestly recommend you choose this route.
"Global" scope in Python is Module scope. ``` import PetStore PetStore.makenoise = makenoise ```
26,812,595
I have the following piece of python code that I just can't get to work the way I want to. Here's the code: ``` l = [['#' for _ in range(10)] for _ in range(10)] o = ['\n'.join(r) for r in l] print ''.join(r for r in o) ``` Here's the current program output: ``` # # # # # # # # # ## # # # # # # # # ## # # # # # # # # ## # # # # # # # # ## # # # # # # # # ## # # # # # # # # ## # # # # # # # # ## # # # # # # # # ## # # # # # # # # ## # # # # # # # # # ``` Here's what I want the program to output: ``` ########## ########## ########## ########## ########## ########## ########## ########## ########## ########## ``` How can I change to code to have the desired output?
2014/11/08
[ "https://Stackoverflow.com/questions/26812595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3500191/" ]
You simply join in the wrong order: ``` l = [['#' for _ in range(10)] for _ in range(10)] o = [''.join(r) for r in l] # join the columns print '\n'.join(r for r in o) # join the rows ``` Or more easy to read: ``` '\n'.join((''.join(r) for r in l)) ``` Or without `l`: ``` (('#' * 10 + '\n') * 10)[:-1] ``` Or even: ``` '''########## ########## ########## ########## ########## ########## ########## ########## ########## ##########''' ```
try this: ``` for x in range(1,11): print "#"*10 ``` output: ``` ########## ########## ########## ########## ########## ########## ########## ########## ########## ########## ``` explanation: if you multiply a string with a number, it will produce the number of repeating string Demo: ``` >>> "a"*10 'aaaaaaaaaa' >>> "b"*6 'bbbbbb' >>> ```
64,374,423
I have a table with the total number of secondary IDs per each principal ID. So I need to generate a second table in which each row correspond to the combination of primary ID and Secondary ID. For example if for primary ID1 I have 5 as the number of secondary ids I would need 5 rows, each with the same Primary ID and the second ID going from 1 to 5. Doing this with a loop takes a lot of time so I was wondering if there is a more efficient way of doing this without involving loops. Visual example: **Table** ![enter image description here](https://i.stack.imgur.com/JRCZW.png) **Table Output** ![enter image description here](https://i.stack.imgur.com/yHPaV.png)
2020/10/15
[ "https://Stackoverflow.com/questions/64374423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14456915/" ]
try this example : html : ``` <div class="test" ng-controller="Ctrl"> <div ng-repeat="division in divisions | orderBy:['group','sub']">{{division.group}}-{{division.sub}}</div> <div> ``` js : ``` var app = angular.module('app', []); function Ctrl($scope) { $scope.divisions = [{'group':1,'sub':1}, {'group':2,'sub':10}, {'group':1,'sub':2},{'group':1,'sub':20},{'group':2,'sub':1},{'group':2,'sub':11}]; } ```
alright what i did to solve this is that i moved the sort function to the front when i GET the data from the JSON repsonse. ``` $http({ method: 'Get', url: "https://xxxxxxx.azurewebsites.net/api/team/" + id_company }) .success(function (data) { var neworder = []; function CustomOrder(item) { switch (item) { case 'player': return 1; case 'coach': return 2; case 'waterboy': return 3; } } angular.forEach(data, function (item) { neworder.push(item); }); neworder.sort(function (a, b) { return (CustomOrder(a.Role) > CustomOrder(b.Role) ? 1 : -1); }); $scope.Team = neworder; }); ``` after i just run the filter without the sort function; ``` <div ng-repeat="person in Team | myOrder:'Role'> <h2 ng-show="item.Role_CHANGED">{{item.Role}}</h2> <p>{{person.Name}}</p> </div> app.filter('myOrder', function () { return function (list, group_by) { var filtered = []; var prev_item = null; var group_changed = false; var new_field = group_by + '_CHANGED'; angular.forEach(list, function (item) { group_changed = false; if (prev_item !== null) { if (prev_item[group_by] !== item[group_by]) { group_changed = true; } } else { group_changed = true; } if (group_changed) { item[new_field] = true; } else { item[new_field] = false; } filtered.push(item); prev_item = item; }); return filtered; }; }) ``` it's a bit of a work-around but it did the job just to be complete, if you just want to sort the ng-repeat in a filter and no need for the lables. you can just do this: ``` <div ng-repeat="person in Team | Sorter:'Role'> <p>{{person.Name}}</p> </div> app.filter('Sorter', function () { function CustomOrder(item) { switch (item) { case 'player': return 1; case 'coach': return 2; case 'waterboy': return 3; } } return function (items, field) { var filtered = []; angular.forEach(items, function (item) { filtered.push(item); }); filtered.sort(function (a, b) { return (CustomOrder(a.Role) > CustomOrder(b.Role) ? 1 : -1); }); return filtered; }; }); ```
38,993,071
I'm trying to achieve something where the answer is already given for. But it's in `c#` and I don't have any knowledge what-so-ever over `c#` so I'm looking for a vb.net alternative. I made a `class` called `BomItem` which has several properties like quantity, description etc. I add these `BomItems` into a `List(of BomItem)` but now I would like to sort them according to a property. How can you sort the items based on the `ItemNumber` property? Here is the [link](https://stackoverflow.com/questions/3309188/how-to-sort-a-listt-by-a-property-in-the-object) to the `c#` solution I found. My class code ``` Public Class BomItem Public Property ItemNumber As String Public Property Description As String Public Property Quantity As Double Public Property Material As String Public Property Certificate As String End Class ``` How I add the `BomRow` objects ``` _NewBomList.Add(New BomItem() With { .ItemNumber = oRow.ItemNumber, .Description = oPropSet.Item("Description").Value, .Quantity = oRow.TotalQuantity, .Material = oPropSet.Item("Material").Value, .Certificate = CustomPropertySet.Item("Cert.").Value}) ``` Comparer ``` Public Class NaturalSort Implements IComparer Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compare ' [1] Validate the arguments. Dim s1 As String = x If s1 = Nothing Then Return 0 End If Dim s2 As String = y If s2 = Nothing Then Return 0 End If Dim len1 As Integer = s1.Length Dim len2 As Integer = s2.Length Dim marker1 As Integer = 0 Dim marker2 As Integer = 0 ' [2] Loop over both Strings. While marker1 < len1 And marker2 < len2 ' [3] Get Chars. Dim ch1 As Char = s1(marker1) Dim ch2 As Char = s2(marker2) Dim space1(len1) As Char Dim loc1 As Integer = 0 Dim space2(len2) As Char Dim loc2 As Integer = 0 ' [4] Collect digits for String one. Do space1(loc1) = ch1 loc1 += 1 marker1 += 1 If marker1 < len1 Then ch1 = s1(marker1) Else Exit Do End If Loop While Char.IsDigit(ch1) = Char.IsDigit(space1(0)) ' [5] Collect digits for String two. Do space2(loc2) = ch2 loc2 += 1 marker2 += 1 If marker2 < len2 Then ch2 = s2(marker2) Else Exit Do End If Loop While Char.IsDigit(ch2) = Char.IsDigit(space2(0)) ' [6] Convert to Strings. Dim str1 = New String(space1) Dim str2 = New String(space2) ' [7] Parse Strings into Integers. Dim result As Integer If Char.IsDigit(space1(0)) And Char.IsDigit(space2(0)) Then Dim thisNumericChunk = Integer.Parse(str1) Dim thatNumericChunk = Integer.Parse(str2) result = thisNumericChunk.CompareTo(thatNumericChunk) Else result = str1.CompareTo(str2) End If ' [8] Return result if not equal. If Not result = 0 Then Return result End If End While ' [9] Compare lengths. Return len1 - len2 End Function End Class ```
2016/08/17
[ "https://Stackoverflow.com/questions/38993071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6071727/" ]
Use [LINQ](https://msdn.microsoft.com/de-de/library/bb763068.aspx) [OrderBy](https://msdn.microsoft.com/de-de/library/bb882684.aspx): ``` _NewBomList.OrderBy(Function(bi) bi.ItemNumber) ``` and for descending: ``` _NewBomList.OrderByDescending(Function(bi) bi.ItemNumber) ``` If you want a numeric order in your string you have to convert it to an integer first: ``` _NewBomList.OrderBy(Function(bi) Integer.Parse(bi.ItemNumber)) ``` **Edit:** To provide a custom `IComparer` for the OrderBy extension you have to create a class which implements `IComparer(Of String)` where String are your `ItemNumbers` to compare: ``` Class ItemNumberComparer Implements IComparer(Of String) Public Function Compare(String x, String y) Dim ix As String() = x.Split("."C) Dim iy As String() = y.Split("."C) Dim maxLen As Integer = Math.Max(ix.Length, iy.Length) For i As Integer = 0 To maxLen - 2 If ix.Length >= i AndAlso iy.Length >= i Then If Integer.Parse(ix(i)) < Integer.Parse(iy(i)) Then Return -1 'If x.i is LT y.i it must be smaller at all ElseIf Integer.Parse(ix(i)) > Integer.Parse(iy(i)) Then Return 1 'If x.i is GT y.i it must be bigger all End If End If Next 'This code is only executed if x and y differ at last number or have different ´number of dots If ix.Length = iy.Length Then Return Integer.Parse(ix(ix.Length - 1)).CompareTo(Integer.Parse(iy(iy.Length - 1))) 'Only last number differs Else Return ix.Length.CompareTo(iy.Length) 'The number with more dots is smaller End If End Function End Class ``` Call syntax: ``` Dim comparer = new ItemNumberComparer() _NewBomList.OrderByDescending(Function(bi) bi.ItemNumber, comparer) ```
This C# code from that other thread: ``` List<Order> SortedList = objListOrder.OrderBy(o=>o.OrderDate).ToList(); ``` equates to this VB code: ``` List(Of Order) SortedList = objListOrder.OrderBy(Function(o) o.OrderDate).ToList() ``` As you can see, very little changes. You just have to know the syntax for generics and lambda expressions. You should be aware, though, that this code does NOT sort your list. It sorts the items in the list and then adds them to a new list in that order. This is perfectly fine for many applications but if you're using that same list elsewhere then you won't see the new order there. While there are a few variations, one way to actually sort the list in place is like this: ``` objListOrder.Sort(Function(o1, o2) o1.OrderDate.CompareTo(o2.OrderDate)) ```
30,915,008
I have the following HTML input boxes: ``` <form> <input type="text" name="1" id="1" disabled> <input type="text" name="2" id="2" disabled> <input type="text" name="3" id="3" disabled> <input type="text" name="4" id="4" disabled> <input type="submit" name="submit" value="submit> </form> ``` Next I am trying to use javascript to undisable all my input boxes upon a user clicking my div. JavaScript: ``` <script> $('#edit').click(function(){ $('input[]').prop('disabled', false); }); </script> ``` Can someone please show me where I am going wrong, thanks
2015/06/18
[ "https://Stackoverflow.com/questions/30915008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4983280/" ]
The error is the selector, try: ``` $('input').prop('disabled', false); ```
Try this: ``` $('input:text').prop('disabled', false); ``` Or ``` $('input[type=text]').prop('disabled', false); ```
62,474,393
``` $response = Http::withHeaders([ 'Authorization' => 'Basic '. base64_encode(env('CLIENT_ID').':'.env('CLIENT_SECRET')), 'Content-Type' => 'application/x-www-form-urlencoded' ])->post('https://accounts.spotify.com/api/token', [ 'code' => trim($code), 'redirect_uri' => env('REDIRECT_URI'), 'grant_type' => 'authorization_code', ]); print_r($response->json()); ``` This return code: > > [error] => unsupported\_grant\_type [error\_description] => grant\_type parameter is missing > when i want to get access token. > > >
2020/06/19
[ "https://Stackoverflow.com/questions/62474393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13220584/" ]
Every time you construct a new instance of this class, you are overriding the field. Really a better name than `INSTANCE` would be `LAST_CREATED_INSTANCE`. That said, given that the field is not declared [`volatile`](https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-8.3.1.4), a write to that field does not have guaranteed visibility across threads. So it is more like `SOMEWHAT_RECENTLY_CREATED_INSTANCE`. So yes, it's bad. I can't see any situation where the implementation as presented would be an optimal solution. --- Singleton implementations in Java have been discussed at length already. There should be no real reason why you should have to devise your own, except as an exercise. See Item 3 of Josh Bloch's *Effective Java*, excerpts of which are here: [What is an efficient way to implement a singleton pattern in Java?](https://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java) (though I would advise reading the whole book)
One way to avoid leaking `this` in a constructor is with a static factory method. Also, as Michael has pointed out, `INSTANCE` should be volatile. ``` public class Foo { private static volatile Foo INSTANCE; private Foo() { // ... } private static Foo create() { // This should probably be synchronized for atomicity // but that's for another question Foo newInstance = new Foo(); INSTANCE = newInstance; return newInstance; } } ``` Note that this is not a singleton, nor is the original code.
743,024
In Vim, one *searches* for newlines as `\n`, but newlines in the replacement-string must be entered as `\r`. I understand that there are [reasons for this behavior](https://stackoverflow.com/q/71417/1858225), but for my purposes I just find it irritating. I want to be able to use `\n` to mean (essentially) the same thing in both a search pattern and in a replacement string: specifically, in a search pattern it should match newlines, and in a replacement string it should insert newlines. Is there a way to get this behavior? I don't think simple remappings will work, since the substitute command needs to be parsed in order to determine whether `\n` is part of the search pattern or the replacement string.
2014/04/17
[ "https://superuser.com/questions/743024", "https://superuser.com", "https://superuser.com/users/199803/" ]
You have to hook into the command-line; either when executing it via `<CR>`, or immediately when you enter a `\n`. With `:help c_CTRL-\_e`, you can evaluate a function and modify the command-line. Here's a demo that you can build upon and improve (the check for a substitution is simplistic right now): ``` cnoremap n <C-\>eTranslateBackslashN()<CR> function! TranslateBackslashN() if getcmdtype() ==# ':' && getcmdline() =~# 's/.*/.*\\$' " Improve this! return getcmdline() . 'r' endif return getcmdline() . 'n' endfunction ```
Alternate answer using a plugin (this is the solution I have decided to use, although it only works with Vim 7.4+): Using [Enchanted Vim](https://github.com/coot/EnchantedVim), put `let g:VeryMagicSubstituteNormalise = 1` in your `.vimrc`. (This plugin uses the [CRDispatcher](https://github.com/coot/CRDispatcher) plugin, which allows text-substitutions in commands *after* the Enter key has been pressed but *before* the command is actually executed. So no remapping of `\n` is required, and the substitution is invisible to the user, making `\n` appear to have the same "meaning" in both contexts.)
28,688,288
I'm pretty new to C++ but I couldn't find a workaround for this online, I feel like there might be an interesting, elegant solution possible for this. I'm ultimately trying to code a leapfrog algorithm for planetary motion. I've defined a class called planet ``` Planet(double mass, double x0, double x1, double v0, double v1) ``` and I've got an array storing information for 4 different planets: ``` Planet planets[] = { Planet(2.0, -0.5, 0, -0.94, 0.65), Planet(1.0, -0.6, -0.2, 1.86, 0.7), Planet(1.0, 0.5, 1.0, -0.44, -1.40), Planet(0.4, 0.6, 0.3, 1.15, -1.50) }; ``` I'm going to want to calculate the force due to gravity of each planet on every other planet. This involves implementing the mathematical equation for the force on planet i: F\_i= sum over i!=j of [(G*m\_i*m\_j)/r\_ij], where i and j denote two planets, j being incremented each time, and r\_ij the distance between the two. Before I start thinking about that as a whole, I was testing if I could use a for loop to select a particular planet from the array, and a particular component from that planet, and print that. That works fine via ``` for(int i=0; i<4; ++i){ cout << planets[i].getvx() << "\n"; } ``` However, I wanted to try exclude a particular planet, say I was computing the force on j where j=2. ``` for(int i=0; (i<j || i>j) && i<4; ++i){ cout << planets[i].getvx() << "\n"; } ``` This loop terminates at 2, only printing the v0 value (as defined via the class) for p[0] and p[1], not p[3] as well as I'd have liked. Likewise, j=1 only prints v0 for p[0] and p[1]. Is there a convenient way to put a condition within the for loop which meets my needs or should I rethink my approach?
2015/02/24
[ "https://Stackoverflow.com/questions/28688288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4309330/" ]
Why not try this ``` for(int i=0; i<4 ; ++i) { if( i != j ) cout << planets[i].getvx() << "\n"; } ``` This is the simplest method I could think of without trying anything complex. You just have to check whether `i` is equal to `j` inside the loop. If `i` is not equal to `j`, then give output. If you don't want this, then you can use `continue` like it has been suggested in the other answers. ``` for(int i=0; i<4 ; ++i) { if ( i == j ) continue; cout << planets[i].getvx() << "\n"; } ```
Use the keyword [continue](http://www.tutorialspoint.com/cplusplus/cpp_continue_statement.htm) inside for loop. It forces the next iteration of the loop ``` if(i==j) continue; ```
47,384,501
I have a list like this: ``` [(0, 1), (0, 2), (0, 3), (1, 4), (1, 6), (1, 7), (1, 9)] ``` That I need to convert to a tuple that looks like this: ``` [(0, [1, 2, 3]), (1, [4, 6, 7, 9])] ``` This is the code I have: ``` friends = open(file_name).read().splitlines() network = [] friends = [tuple(int(y) for y in x.split(' ')) for x in friends] return friends ```
2017/11/20
[ "https://Stackoverflow.com/questions/47384501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8968784/" ]
Use table-cell as display property ``` .footer-links, .built-with { display: table-cell; max-width: 40%; height: 100%; border: 2px solid black; } ``` I think , it'll horizontally aligned these boxes
this is based off of obsidian ages answer since it wasn't updated to match my exact question. I edited `.footer-above` to 1400px since `width:100%` with code doesn't scale as viewport width changes. Also, it should be `align-items: flex-start;` on `container` class, since i want a baseline at the top of parent div ```css .footer-above { width: 1400px; height: 200px; background-color: #aaa; padding-top: 30px; padding-bottom: 30px; color: white; font-size: 20px; } .footer-links, .built-with { display: inline-block; width: 40%; height: 150px; border: 2px solid black; } .container { margin: 0 auto; width: 960px; display: flex; align-items: flex-start; justify-content: center; } ``` ```html <div class="footer-above"> <div class="container"> <div class="built-with"> <h3>ABOUT THIS PAGE</h3> <p> Made with HTML5Boilerplate</p> </div><!--built-with--> <div class="footer-links"> <h3>AROUND THE WEB</h3> </div><!--footer-links--> </div><!--container--> </div><!-- footer-above --> ```
6,566,318
In javascript suppose you have this piece of code: ``` <div> <script type="text/javascript">var output = 'abcdefg';</script> </div> ``` Is there any way to simply "echo" (using PHP terminology) the contents of `output` into `#test`? That is, to output a string inline, assuming you have no standard way of traversing or selecting from the DOM? `document.write("...");` does write the contents of `output`, but in doing so, it replaces the entire document with the `output`. The solution I'm looking for should act the same way a PHP `echo` would: write the output into the document inline.
2011/07/04
[ "https://Stackoverflow.com/questions/6566318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/257878/" ]
"Kosher" code aside, yes. `document.write()`
If your code is in the div, then `document.write('abcdefg')` is the proper choice for inserting something inline at the point of execution. Or, if your code is not inside the div, you can do this: ``` <div id="test"> </div> <script type="text/javascript"> var output = 'abcdefg'; document.getElementById("test").innerHTML = output; </script> ``` You will have to make sure that your code runs AFTER the page is loaded and the div is present.
30,404,587
I have created a structure with a Id variable and a list of values. When I check the size before passing it to a function as a void\* it is 12. Once it gets in the function it is 4. How do I keep the size the same? Struct Code: ``` typedef struct { int id; std::list<int> sensorValues; }dataPacketDef; ``` Sending to other function code: ``` void SendDataBufferToServer() { cout << "Sending network data size: " << sizeof(dpd) << "\n"; client.writeData((void*)&dpd); } ``` In the above function the size is 12 but in the receiving function the size is only 4. The struct is declared as a global variable for my main program.
2015/05/22
[ "https://Stackoverflow.com/questions/30404587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373445/" ]
The size of a pointer is 4 bytes (or 8 if you were using an x64 compiler). If `writeData` needs to know the size of the pointed-to object, that information will need to be passed to it somehow; a common idiom is to pass the size as a second argument. With that done, you could use a helper function template to simplify things: ``` template<typename T> void writeData(Client& client, const T& obj) { client.writeData((void*)&obj, sizeof(obj)); } ``` Although as molbdnilo noted in the question comments, `client.writeData()` probably still won't be able to do what you want it to due to the presence of a `list` in `dataPacketDef`.
sizeof(void\*) is 4 bytes on a 32bit machine.
25,160,918
I have come across such a code and my Java knowledge is not enough for it - I am pretty sure it is something simple, but I have not found an explanation as don't know how to express it in google. Here is the abstracted code, I hope nothing is missing: ``` public class A{ Car car; . . . public A do() { car.move(somewhere); return this; } } public class B{ protected A doSomething(final A a ){ a.do(); return a; } } ``` My first question is what does "return this;" mean here? <http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html> does not include such a case. Second is how a.do() works in method doSomething()? Method do() is supposed to return a value, yet it is not assigned anywhere? Lastly, I suppose that "a" returned from doSomething() was changed in this method. Is this allowed, as "a" is final?
2014/08/06
[ "https://Stackoverflow.com/questions/25160918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2822768/" ]
1. `return this;` - Being that, the return type is an `A` object, when the `.do()` method is called, the method will return `this`, `this` is the exact same instance that called it. 2. `public A doSomething(final A a)`, the only contract here is that an `A` object is returned. What happens in the code block doesn't matter, as long as a `null` or class that extends `A` is returned. 3. `final A a` declaration, simply means the memory location address by variable a cannot be re-assigned.. i.e. `a = null;` or `a = new A()` would throw an exception
Using `return this;` at the end of methods is a technique called [Method Chaining](http://en.wikipedia.org/wiki/Method_chaining) and can be a very convenient way of performing a chain of operations on an object. `StringBuilder` is a good example: ``` String s = new StringBuilder().append("Hello").insert(0, "Goodbye").delete(7, 12).append(" :)").toString(); ``` NB: It can also be used to make code seem over-complex so it should only be used where appropriate.
137,721
I am pulling up carpet and putting down a floating, vinyl plank floor in a three-season room built on slap. The tack strips are nailed into the concrete. I see [How to repair concrete damage from pulling up nail strips](https://diy.stackexchange.com/questions/111434/how-to-repair-concrete-damage-from-pulling-up-nail-strips) but am looking for advice on the easiest way to get the tack strips up to begin with. Any thoughts?
2018/04/21
[ "https://diy.stackexchange.com/questions/137721", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/20103/" ]
Jim and Taylor are correct. Use a small pry par because it is not as thick and will get under the tack strip better. Hold the the long straight part or the pry bar and place the curved end so that the but is against the floor and the wedge part is up against the tack strip **directly in front of the nail**. Whack the the curved part of the pry bar with a hammer, it usually only takes one or two hits to *pop* up the nail. It helps to hold the bar at an angle so the bar goes under the strip and to not hit to hard, sometimes you can drive the end of the bar into the wall or trim if you get to aggressive. Do not pry up once the nail is free as this will splinter or break the strip at the next nail location, just continue whacking all the nails and when you get them all the whole tack strip will be free and easy to dispose of.
Prybar, hammer, elbow grease. There are many prybar styles, but this is the one I would choose. [![prybar](https://i.stack.imgur.com/JG3Gt.jpg)](https://i.stack.imgur.com/JG3Gt.jpg)
8,370,757
So, I have an array of unsigned chars, currently I'm trying to write a Set method (changes the bit in given index to 1). The best way I could think to do this was instead of creating a mask for the whole array, I would just create a mask the size of a byte and only mask the index spot in the array with the given bit that the user wants to change. However, every way I try to do it, either nothing happens to the resulting array after OR'ing it with a mask of all 0's with a 1 in the bit index, or I get a seg fault. The best I've been able to do is change the correct bit in the first array index. How my code is currently set up right now I understand why it's only changing the correct bit in the first byte of the array, but every attempt to change this has failed, I don't think this should be hard I just feel like I'm missing something, but pages of reading and google searches have lead me no where. Here's a snipit of my code as of now... ``` void BitArray::Set (unsigned int index) 70 { 71 int spot; // index in barray where 72 // bit to be set is located 73 char mask; 74 if (index < 8) 75 { 76 spot = 0; 77 mask = 1 >> index - 1; 78 } 79 else 80 { 81 int spot = index / 8; 82 mask = 1 << (index - (8*spot) - 1); 83 } 84 85 *barray = *barray | mask; 86 } ``` Instead of the \*barray = \*barray | mask, I would intuitively want something like barray[spot] = barray[spot] | mask; to work. Any help is greatly appreciated.
2011/12/03
[ "https://Stackoverflow.com/questions/8370757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1079357/" ]
To preselect a value, just add the selected attribute to the desired option. ``` <select id="viewSelector" name="when" style="width:92%;"> <option value="USA">USA</option> <option value="Australia" selected="selected">Australia</option> <option value="Germany">Germany</option> </select> ``` This will preselect Australia for example.
You need to add a `selected` attribute to the option you want to select, as described in the [spec](http://www.w3.org/TR/html4/interact/forms.html#h-17.6.1). ``` <select id="viewSelector" name="when""> <option value="USA">USA</option> <option value="Australia" selected="selected">Australia</option> <option value="Germany">Germany</option> </select> ``` In your script, you need to emit this attribute for whatever default you want to display.
26,159
I've kept diaries all my life and now have over 100...which I've recently started turning into an autobiography - where some of the original diary quotes are included along with the new text. I belong to a local writers group, most of whom are well into their 70's & have led much more 'normal' lives than myself. Today I received their feedback on my first chapter. They seemed fascinated by the content but the general consensus was that, because I'm not famous and "nobody buys memoirs of anyone who's not", it might be better if I wrote it as a novel - though still writing it in the first person. I've had quite an unusual life involving a great deal of travelling and (in my 20's) was socialising with several notorious rock musicians as well as getting caught up in some rather nefarious activities. I definitely dont have to fictionalise anything! I only discovered this website by googling the query of possible conviction for misdeeds I committed 40 years ago (which were never uncovered) by writing about them now. So I was wondering: 1. If others on here shared the same view that memoirs, by unknowns, are not a suitable genre for first time writers? 2. The question of admitting to crimes (drugs imparticularly...and more than just smoking some weed!) being liable to prosecution - or possible barring from the foreign countries where those crimes were committed. PS I'm now 65 & was only naughty in the 1970's!
2017/01/19
[ "https://writers.stackexchange.com/questions/26159", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/23089/" ]
There are two factors that sell an (auto)biography: fame and relevance. (Auto)biographies by famous persons sell because everyone wants to know what their lives were (or are) like. We, the common people, want to know how rich, famous, or talented people live. The (auto)biography of a celebrity will sell, even if that person has a completely common and boring life. Because even that is an insight that tickles our curiosity. How can they live a normal life, if their circumstances are so exceptional? (Auto)biographies by unknown persons sell because the "protagonist" led an exceptional life or because his life exemplifies the average life. Anne Frank was a very normal, completely unknown girl. Yet her autobiography has become a bestseller because her life was both tragic and an example by which we can understand the lives of many similarly normal people at that time. Today, of course, Anne Frank is "famous", if you want, but *only through her autobiography*. It is her autobiography that made her famous! That Anne Frank never intended to publish her diaries adds to the veracity of her writings and makes reading them even more heartbreaking. I disagree with the advice of Dale. If you are a common person and your life was average, you cannot make yourself famous and then sell your autobiography off that fame. And if your life was interesting enough to make you famous through the strategies outlined by Dale, it will sell without that effort, too. If you go to a bookstore and look at the biographies section, that will be misleading because the books there are often limited to famous people. But in the novels or social/political sections, there are many (auto)biographies of people that somehow exemplify the circumstances we live in. There are many (auto)biographies by or about women who escaped oppression in islamic states, for example. These are common, average women who were completely unknown before they published their books, but they have become both an inspiration to women in similar circumstances and have helped outsiders understand the situation in their countries. So if you are unknown, but you can manage to make your life relevant to a wider public, either because your life was exceptional, or because your life exemplifies something that people are struggling to understand, then your book will sell. There is one type of autobiography that seems to profit from novellisation, and that is the "normal" life of a member of some fringe group or subculture. A good example is *Fight Club*, which fictionalizes the experiences of the author. Other examples are books about drug addicts and criminals, but also musicians or teenagers. The authors of these books are people whose lives are not normal or average from the perspective of the wider audience, but are normal and average within the community they are a part of.
You might benefit from clarifying the difference between an autobiography and a memoir. There are many articles on these topics on the Internet. They might help you find an answer. Autobiographies tend to be chronological; memoirs focus on a theme, topic or event. What makes any story standout is getting the voice right: if you create an engaging persona as a storyteller and tell a good story in an engaging way, the actual genre whether autobiography, novel or memoir will matter less and be a marketing issue rather than a stylistic one.
779,946
Find the greatest possible value of $5\cos x + 6\sin x$. I attempted to solve this using graphing, however, the answer appears to be an ugly irrational. Is there a better method of solving this problem? Thank you.
2014/05/03
[ "https://math.stackexchange.com/questions/779946", "https://math.stackexchange.com", "https://math.stackexchange.com/users/147474/" ]
A simple vector-based approach: you recognize in the expression the dot product $$(5, 6) \cdot (\cos x, \sin x).$$ This product is maximized when the two vectors are parallel and it is then the product of the moduli $$\sqrt{5^2+6^2} \cdot 1.$$
Let $r^2=5^2+6^2=25+36=61$ and $\alpha = \arctan \frac 56$ You will find that $$5\cos x+6\sin x=r(\sin\alpha\cos x+\cos\alpha \sin x)=r \sin (x+\alpha)$$
61,283,484
``` | (true, Select(true)) => true | (false, Select(false)) => false ``` How can I combine these two in a switch statement with generic type?
2020/04/18
[ "https://Stackoverflow.com/questions/61283484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11537438/" ]
Unfortunately the patterns that you match against in a switch statement have to be 'linear' (ie, the variants inside the patterns should only appear once): See <https://caml.inria.fr/pub/docs/oreilly-book/html/book-ora016.html> > > A pattern must necessarily be linear, that is, no given variable can occur more than once inside the pattern being matched. Thus, we might have hoped to be able to write: > > > > ``` > # let equal c = match c with > (x,x) -> true > | (x,y) -> false;; Characters 35-36: This variable is bound several times in this matching > > ``` > > But this would have required the compiler to know how to carry out > equality tests. Yet this immediately raises numerous problems. If we > accept physical equality between values, we get a system which is too > weak, incapable of recognizing the equality between two occurrences of > the list [1; 2], for example. If we decide to use structural equality, > we run the risk of having to traverse, ad infinitum, circular > structures. > > > Note that ReasonML is just an alternative syntax for OCaml, so the above also holds for Reason. `match` is just the OCaml version of `switch`.
Yeah this is doable: ``` // using switch let theSolution = x => switch(x) { | (_, Select(inside)) => inside }; // using `fun` let theSolution = x => x |> fun | (_, Select(inside)) => inside; // or for a super short solution: let theSolution = fun | (_, Select(inside)) => inside; ``` For example: ``` type select = | Select(bool); let a = (true, Select(true)); let b = (true, Select(false)); let c = (false, Select(true)); let d = (false, Select(false)); let theSolution = x => x |> fun | (_, Select(inside)) => inside; Js.log2("A is", theSolution(a)); Js.log2("B is", theSolution(b)); Js.log2("C is", theSolution(c)); Js.log2("D is", theSolution(d)); ``` Will result in: ``` "A is" true "B is" false "C is" true "D is" false ``` Or if you want to compare the booleans, you can do either of: ``` let theSolution = fun | (a, Select(b)) => a && b; let theSolution = fun | (a, Select(b)) => a == b; ``` [See this example in the online repl](https://reasonml.github.io/try?rrjsx=true&reason=C4TwDgpgBAzhA2EDGwoF4oB8oGUHOAAoAjAe1PgEoBuAKFsVQEN0pDgAnAVwgBpd8KdtwiUaDCKmKthPfnkRCAZk3hwxdRlCQyVavgMVFOPDRNQATXarjzBRPevHmowABYQcFLsACWpADtWAA90AD4oUMwIpS4g7EIAfTsjQl8AmF8LUUpwqHTM7LpaACkYADp4UgBzACZCACIAQXyYBv53T28-QMImMzLKmvqGgCFW9tcPL3gffwCSAYqqusaAYQmO6e75wiQlodWGgBFNqa7ZnoWLDSA)
1,017,396
I am using Ubuntu 15.10 x64 and have skype 4.3.0.37. It is a well-known issue that with this old version all pictures sent by the other party are received as links like this: ``` https://api.asm.skype.com/s/i?0-xxx-a3-somehashkeysecretnumberchars ``` That's OK, I used to use it. Two days ago by some reason I entered a command `/msnp24` to "improve" group chats. Nothing visible happened and I decided to leave it as is. But the next day I found that all images sent to me like the link above do not work anymore. I receive `HTTP 404` error and blank screen. After some experiments I have found that if I rewrite the link to another view it can work. But I do not want to do it for ever incoming link. ``` https://api.asm.skype.com/v1/objects/0-xxx-a3-somehashkeysecretnumberchars/views/imgpsh_fullsize ``` The **question** is: HOW to return everything back and revert `/msnp24` command? > > I'm a stupid donkey, why the hell I used that command? > > >
2015/12/23
[ "https://superuser.com/questions/1017396", "https://superuser.com", "https://superuser.com/users/437717/" ]
Thanks to the information provided in the question itself, I was able to create a chrome extension to automatically redirect to a correct URL. In Order to Run it 1. Put the two files(manifest.json and background.js) with source code in a folder. 2. Go to Chrome Extension Manager (chrome://extensions/) and Check "Developer mode" at the top. 3. Click "Load unpacked extension..." button and choose the folder with files you created above. 4. Login into Skype Web once and then you can close that tab. The redirection works automatically when the image link is clicked from Skype. Here is Source Code of the Extension manifest.json ``` { "manifest_version": 2, "name": "Skype- Linux Image Sharing", "description": "This extension will re-write the image links of skype so that you can see skype shared images of chrome", "version": "1.0", "background": { "scripts": ["background.js"] }, "permissions": ["tabs"] } ``` background.js ``` chrome.tabs.onUpdated.addListener(function(tabId, info, tab) { var BROKEN_SKYPE_URL = 'https://api.asm.skype.com/s/i?'; var FIXED_SKYPE_URL = 'https://weu1-api.asm.skype.com/v1/objects/IMAGE_ID/views/imgpsh_fullsize' var currentUrl = tab.url; if (info.status === 'complete' && currentUrl.slice(0, BROKEN_SKYPE_URL.length) == BROKEN_SKYPE_URL) { var imageId = currentUrl.substring(currentUrl.indexOf("?")+1,currentUrl.length); var finalUrl = FIXED_SKYPE_URL.replace('IMAGE_ID',imageId); chrome.tabs.update(tab.id, {url: finalUrl}); } }); ``` Please read [Create Chrome Extension](https://developer.chrome.com/extensions/getstarted) for more information.
Not a solution I'm afraid, but a clue to the right direction. /msnp24 is possibly unrelated so you are looking for the wrong answer. I also use Ubuntu 15.10 (Mate) and the last 24 hours or so both skype image links I have received have been blank like yours. I have not entered then msnp24 command though. To me this looks like the skype api itself may be broken, or the command that creates the link. Rewriting the link as you showed says "Unauthenticated" for me even though logged into skype and manager on the web.
2,182,459
I have a string from which I have to remove following char: '\r', '\n', and '\t'. I have tried three different ways of removing these char and benchmarked them so I can get the fastest solution. Following are the methods and there execution time when I ran them 1000000 times: It should be fastest solution if I have 1 or 2 char to remove. But as I put in more char, it starts to take more time ``` str = str.Replace("\r", string.Empty).Replace("\n", string.Empty).Replace("\t", string.Empty); ``` **Execution time = 1695** For 1 or 2 char, this was slower then String.Replace, but for 3 char it showed better performance. ``` string[] split = str.Split(new char[] { '\t', '\r', '\n' }, StringSplitOptions.None); str = split.Aggregate<string>((str1, str2) => str1 + str2); ``` **Execution time = 1030** The slowest of all, even with 1 char. Maybe my regular expression is not the best. ``` str = Regex.Replace(str, "[\r\n\t]", string.Empty, RegexOptions.Compiled); ``` **Execution time = 3500** These are the three solutions I came up with. Is there any better and faster solution that anyone here know, or any improvements I can do in this code? **String** that I used for benchmarking: ``` StringBuilder builder = new StringBuilder(); builder.AppendFormat("{0}\r\n{1}\t\t\t\r\n{2}\t\r\n{3}\r\n{4}\t\t\r\n{5}\r\n{6}\r\n{7}\r\n{8}\r\n{9}", "SELECT ", "[Extent1].[CustomerID] AS [CustomerID], ", "[Extent1].[NameStyle] AS [NameStyle], ", "[Extent1].[Title] AS [Title], ", "[Extent1].[FirstName] AS [FirstName], ", "[Extent1].[MiddleName] AS [MiddleName], ", "[Extent1].[LastName] AS [LastName], ", "[Extent1].[Suffix] AS [Suffix], ", "[Extent1].[CompanyName] AS [CompanyName], ", "[Extent1].[SalesPerson] AS [SalesPerson], "); string str = builder.ToString(); ```
2010/02/02
[ "https://Stackoverflow.com/questions/2182459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150830/" ]
Even faster: ``` public static string RemoveMultipleWhiteSpaces(string s) { char[] sResultChars = new char[s.Length]; bool isWhiteSpace = false; int sResultCharsIndex = 0; for (int i = 0; i < s.Length; i++) { if (s[i] == ' ') { if (!isWhiteSpace) { sResultChars[sResultCharsIndex] = s[i]; sResultCharsIndex++; isWhiteSpace = true; } } else { sResultChars[sResultCharsIndex] = s[i]; sResultCharsIndex++; isWhiteSpace = false; } } return new string(sResultChars, 0, sResultCharsIndex); } ```
try this ``` string str = "something \tis \nbetter than nothing"; string removeChars = new String(new Char[]{'\n', '\t'}); string newStr = new string(str.ToCharArray().Where(c => !removeChars.Contains(c)).ToArray()); ```
156,473
I have a list with items and one of the column is a due date `{DueDate}`. I have a view, which displays items that are overdue (`{DueDate} <= [Today]`) that are assigned to a particular user `[Me]`. The `{DueDate}` column is calculated column - adding one year to another date from other column. I have an alert which is sending emails when items from that view are modified. Assuming the situtation that item is not showing in the view, because the Due Date condition is not met, but the next day the condition will be met (`{DueDate} <= [Today]`) and there will be no edit to the item, will I get alert message? Basically will SharePoint send me an alert when item will show up in the view, but there was no edit to the item? I hope the question is clear :)
2015/09/09
[ "https://sharepoint.stackexchange.com/questions/156473", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/4577/" ]
You can use a Workflow to wait till the DueDate then send an email. The Workflow approach is the Normal method OR be abnormal You can watch the Today calculation in a VIEW, [How to use Today and Me in Calculated column](https://sharepoint.stackexchange.com/questions/151144/how-to-use-today-and-me-in-calculated-column/151336#151336) You could extend that code to update the item like done in: <http://www.viewmaster365.com/#/Create/Priority> This then would trigger the standard Alert process because the item was modified. ### Update #1 See: [Understanding Eventing Actions in SharePoint Designer 2013](https://msdn.microsoft.com/en-us/library/office/jj650894.aspx)
Firstly,the calculated column gets updated only when the item is updated.So,there are no chance for the item to get into your view without any modification.
7,657
I am looking for a cheap way to get +24V DC max 3A from computer power supply. I prefer easy soldering solution like DIP, and standard components that do not need to be purchased over internet. Any ideas, please?
2010/12/08
[ "https://electronics.stackexchange.com/questions/7657", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/1129/" ]
I have done this in the past using 2 supplies in series. The ground for the supply is the wall ground so to make it work I had to take one of the supplies apart and mount the board on nylon bolts to isolate it from the case. Then that supply floats and can be put in series. Not quite sure what happens around the current limit of the supply.
<http://cdn.makezine.com/uploads/2014/04/da87333a_atx24-1bcq.jpg> The blue wire is -12v, as @Yann Vernier said. Computer PSU, even the oldest one is a switching power supply, has no 7912 or anything like that, should handle 3 amps. I had a PSU from old computer that has 29 amps on +12v rail and 19 amps on -12 v rail.
6,177,734
I read alot about this on this forum, but I cant make it work. I want to use the ajax function on my asp.net web application So here is the Javascript on VerifMain.aspx ``` $(document).ready(function () { //menu() $("#btnImprimer").click(function () { $.ajax({ type: "POST", url: "/VerifMain.aspx/Lol", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { alert("Good"); }, error: function (msg) { alert(msg); } }); }); }); ``` And here is the server code in VerifMain.aspx.vb ``` Partial Public Class _Default Inherits Page <WebMethod()> _ Public Shared Sub Lol() //TO DO End Sub End Class ``` So when I'm trying to call this method, It goes in the error function and the alert is "[object Object]" I have to use JQuery because where I work the Microsoft Ajax is not installed. I really need help for this, I don't understand what I do wrong and I'm stuck with ie7 only and almost every websites are blocked. Thank you! Have a nice day!! EDIT: Hi everyone Thank you for your time! I fixed it by removing the the partial class. so now it's only a static web method in the server code and it works. ``` <WebMethod()> _ Public Shared Sub Lol() //TO DO End Sub ``` To be honest, I don't understand how it works but thank you for your fast replies. This is the best website, I will spend some free time here now ;)
2011/05/30
[ "https://Stackoverflow.com/questions/6177734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/776438/" ]
Try to call this method instead just to test it once more: ``` <WebMethod()> _ <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _ Public Shared Function GetDate() As String Return Date.Now.ToString() End Function ``` Replace URL with this: ``` url: "/VerifMain.aspx/GetDate", ```
ASP.NET AJAX modified the JSON returned in 3.5. You need to access the `d` property, see <http://encosia.com/never-worry-about-asp-net-ajaxs-d-again>. I don't know what you're error is, but you'll see it if you changed the code to what's below: ``` $(document).ready(function () { //menu() $("#btnImprimer").click(function () { $.ajax({ type: "POST", url: "/VerifMain.aspx/Lol", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { alert("Good"); }, error: function (data) { alert(data.d); } }); }); }); ```
28,925,447
``` import logging import graypy my_logger = logging.getLogger('test_logger') my_logger.setLevel(logging.DEBUG) handler = graypy.GELFHandler('my_graylog_server', 12201) my_logger.addHandler(handler) my_adapter = logging.LoggerAdapter(logging.getLogger('test_logger'), { 'username': 'John' }) my_adapter.debug('Hello Graylog2 from John.') ``` is not working I think the issue is the url that should send to `/gelf` because when I curl from the terminal to my graylog server , it works ``` curl -XPOST http://my_graylog_server:12201/gelf -p0 -d '{"short_message":"Hello there", "host":"example1111.org", "facility":"test", "_foo":"bar"}' ```
2015/03/08
[ "https://Stackoverflow.com/questions/28925447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4391936/" ]
Open your Graylog Webapp, click 'System'. You will see a list of links on the right. On of them is 'Input', click this one. Now you have an overview of all running inputs, listening on different ports. On top of the page you can create a new one. There should be a drop box containing certain modes for the input listener (I think 'GELF AMQP' is standard). Change this one to GELF UDP and click 'Launch new input' in the next dialogue you can specify a port for the service. You also have to set a node where the messages have to be stored. This node as (or should have) the same IP as your whole graylog2 system. Now you should be able to receive messages
I think you've setup your input stream For Gelf TCP instead of UDP. I set up a TCP Stream and it got the curl message. However my python application wouldn't send to the stream. I then created a Gelf UDP stream and voila! I ran into this same issue configuring my Graylog EC2 Appliance just a few moments ago. Also make sure firewall/security groups aren't blocking UDP protocol on port 12201 as well. Good luck, and I hope this is your issue!
51,040,710
Assuming you must use a Windows batch file, *(not `powershell`)*, and one wants to delete all files ending in `.zip` that are in the current active directory. How to do this? All attempts so far are failing: ``` forfiles -p "C:\temp\test" -s -m *.zip -d 1 -c "cmd /c del *.zip" ``` For this it says > > > ``` > ERROR: No files found with the specified search criteria. > > ``` > >
2018/06/26
[ "https://Stackoverflow.com/questions/51040710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/211425/" ]
As suggested in my comment, your problem could easily be solved by reading the usage information for your command, *(available when entering `FORFILES /?` at the Command Prompt)*. Based on your questions criteria, "`delete all files ending in .zip` that are in `the current active directory`": You don't need to use the `/P` option because as stated in the usage information, "`The default folder is the current working directory (.)`". There is nothing in your question regarding recursing subdirectories of the current directory, so the `/S` option which "`Instructs forfiles to recurse into subdirectories`" is not required. For the `/D` option you are looking for files with a last modified date less than yesterday, *i.e. "`the current date minus "dd" days`"*, `/D -1`. Because you're wanting to delete files in the current directory, there's no need to use the "`Full path of the file`", `@path`, so what you need is the "`The name of the file`", `@file`. ```dos FORFILES /M *.zip /D -1 /C "CMD /C DEL @file" ```
You did not mention anything about subdirectories or windows version so I'm assuming somewhat. You have an old version syntax. In Windows 7 and further the syntax changed a little bit. For windows 7: ``` forfiles /P "C:\temp\test" /S /M *.zip /D -1 /C "cmd /c del @path" ```
28,825,157
I am trying to store a jQuery datepicker value into a php date formatted variable. The desired outcome: Example input field name "reviewdate" = 03/02/2015 input field name "reviewmonth" = 3 Both values will be submitted to a mysql database. I am able to store "reviewdate", but "reviewmonth" remains "null" after the information is submitted to the database. ``` <body> <!-- Datepicker --> <h2 class="demoHeaders">Datepicker</h2> <input name="reviewdate" type="text" id="datepicker"></input> <input name="reviewmonth" type="hidden" value="<?php if(isset($_GET["reviewdate"])) { echo date_format($_GET["reviewdate"], "n");} else {echo "";} ?>"></input> <script src="external/jquery/jquery.js"></script> <script src="jquery-ui.js"></script> <script> $( "#datepicker" ).datepicker({ inline: true }); </script> </body? Thank you so much for all your help! ```
2015/03/03
[ "https://Stackoverflow.com/questions/28825157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4225742/" ]
In order for [`date_format`](http://php.net/manual/en/datetime.format.php) to work, you need to initialize a `DateTime` object first: ``` <?php $month = ''; if(isset($_GET["reviewdate"])) { $date = new DateTime($_GET["reviewdate"]); // or $date = date_create($_GET["reviewdate"]); will work the same $month = date_format($date, "n"); } ?> <input name="reviewmonth" type="hidden" value="<?php echo $month; ?>"></input> ``` If you want to do this in JS, you need to add a handler for the datepicker to handle the reviewmonth and append it inside the hidden input: ``` <?php if(isset($_POST['submit'])) { echo '<pre>', print_r($_POST), '</pre>'; } ?> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css" /> <form method="POST"> <input name="reviewdate" type="text" id="datepicker" /> <input name="reviewmonth" type="hidden" value="" /> <input type="submit" name="submit" /> </form> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="//code.jquery.com/ui/1.11.3/jquery-ui.js"></script> <script type="text/javascript"> $('#datepicker').datepicker({ inline: true, onSelect: function(dateText, inst){ var date = $(this).val(); var d = new Date(date); var n = (d.getMonth() + 1); $('input[name="reviewmonth"]').attr('value', n); } }); </script> ``` [Sample Output](http://codepad.viper-7.com/Ng18A7)
you have to replace this ``` <script> $( "#datepicker" ).datepicker({ inline: true }); </script> ``` with ``` <script> $( "#datepicker" ).datepicker({ inline: true, dateFormat: 'Y-m-d' }); </script> ```
1,333,524
We have to prove that $$\frac{(x\_1+x\_2+x\_3+...+x\_n)}{n} \geq (x\_1\cdot x\_2\cdot x\_3\cdots x\_n)^{1/n}$$ **Attempt:** Raising both sides to the nth power gives $\left(\frac{x\_1+x\_2+x\_3+...x\_n}{n}\right)^{n} \geq x\_1x\_2x\_3...x\_n$ This is equivalent to proving that if a sum of random numbers is a fixed number, then their maximum product occurs when all the number are equal. So we have to find which combination of numbers gives the maximum product if their sum is fixed. Obviously $$\left({x\_1+x\_2+x\_3+...x\_n}\right)^{n} > x\_1x\_2x\_3...x\_n$$ then, a maximizer must exist. Now suppose that we have this combination of products: $x\_1x\_2x\_3...x\_n$ If i take the arithmetic mean of any 2 numbers and replace them by their arithmetic mean, I will get a bigger product (By the simple 2 case AM-GM inequality which is easy to proof), obviously the arthimetic mean of 2 numbers will not change the sum of the numbers, we can write that: $$\frac{x\_1+x\_2}{2}\cdot\frac{x\_1+x\_2}{2}\cdot x\_3 \cdots x\_n\ \geq x\_1x\_2x\_3\cdots x\_n$$ Which means if we have any combination of product of numbers, I could increase that product by making any 2 numbers equal (arthimetic mean) without changing the sum of the numbers. Now supposing that the maximum product does not have all of the numbers equal, then I can increase its product by having 2 numbers equal, so this mean that it's not the maximum product, then, by contradiction, the maximum product must occur when all the numbers are equal (Sum divided by the number of numbers) Which means that $$\left(\frac{x\_1+x\_2+x\_3+...x\_n}{n}\right)^{n} \geq x\_1x\_2x\_3...x\_n$$ Is this a valid proof? It's my first time here and I don't know how to do the math notations thingy on this website so forgive me, thanks.
2015/06/21
[ "https://math.stackexchange.com/questions/1333524", "https://math.stackexchange.com", "https://math.stackexchange.com/users/249641/" ]
That's pretty good. One aspect I'd want to fiddle with is the existence of the maximizer. You argued that it's bounded (which as a commenter noted could be made more explicit) and so a maximizer exists; this requires some kind of compactness argument, and the continuity of $\mathbb R^n\to\mathbb R$, $(x\_1,\dotsc,x\_n)\to\prod\_{k=1}^n x\_k$. That's all fine, but it would be better to make it explicit. If you don't want to use topological concepts like that, then the argument can be adjusted not to *assume* the existence of the maximizer, but to *prove* it. The idea is to repeatedly replace pairs of $x\_i$ until they're all the same, and argue (as you did) that we can do this keeping the AM constant but increasing the GM. The only tricky bit is that, if you replace pairs of numbers with their average, this process might not ever stop. (Example: $(1,2,2)\to (\frac32,\frac32,2)\to (\frac32,\frac74,\frac74) \to\dotsm$.) So the replacement step has to be tweaked. The resulting proof can be found in a note by Dijkstra, [EWD1140](http://www.cs.utexas.edu/users/EWD/transcriptions/EWD11xx/EWD1140.html).
**Hint:** Your idea is correct. Here is a north to let things rigorous. Consider $f, \psi : U \to \mathbb R$ defined as $$ f(x) = x\_1 \cdot x\_2 \cdots x\_n \,\,\, \text{and} \,\,\, \psi (x) = x\_1 + x\_2 + \ldots + x\_n$$ for all $x = (x\_1, x\_2, \ldots , x\_n) \in U$. Fix $s > 0$ and search for the critical points of $f|\_M$ where $M = \psi^{-1}(s)$. Observe that $\mathrm{grad} \, \psi (x) = (1,1,\ldots, 1)$ for any $x \in U$ and $\mathrm {grad}\, f (x) = (\alpha\_1 , \ldots , \alpha\_n)$, with $a\_i = \prod\_{j\neq i} x\_j$. Show that the maximum is necessarily in $M$ and is the only critical point of $f|\_M$.
37,431,844
I am working with a `IReadOnlyCollection` of objects. Now I'm a bit surprised, because I can use `linq` extension method `ElementAt()`. But I don't have access to `IndexOf()`. This to me looks a bit illogical: I can get the element at a given position, but I cannot get the position of that very same element. Is there a specific reason for it? I've already read -> [How to get the index of an element in an IEnumerable?](https://stackoverflow.com/questions/1290603/how-to-get-the-index-of-an-element-in-an-ienumerable) and I'm not totally happy with the response.
2016/05/25
[ "https://Stackoverflow.com/questions/37431844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1302653/" ]
`IReadOnlyCollection` is a collection, not a list, so strictly speaking, it should not even have `ElementAt()`. This method is defined in `IEnumerable` as a convenience, and `IReadOnlyCollection` has it because it inherits it from `IEnumerable`. If you look at the source code, it checks whether the `IEnumerable` is in fact an `IList`, and if so it returns the element at the requested index, otherwise it proceeds to do a linear traversal of the `IEnumerable` until the requested index, which is inefficient. So, you might ask why `IEnumerable` has an `ElementAt()` but not `IndexOf()`, but I do not find this question very interesting, because it should not have either of these methods. An `IEnumerable` is not supposed to be indexable. Now, a very interesting question is why `IReadOnlyList` has no `IndexOf()` either. ### `IReadOnlyList<T>` has no `IndexOf()` ***for no good reason whatsoever***. If you really want to find a reason to mention, then the reason is historical: Back in the mid-nineties when C# was laid down, people had not quite started to realize the benefits of immutability and readonlyness, so the `IList<T>` interface that they baked into the language was, unfortunately, mutable. The right thing would have been to come up with `IReadOnlyList<T>` as the base interface, and make `IList<T>` extend it, adding mutation methods only, but that's not what happened. `IReadOnlyList<T>` was invented a considerable time after `IList<T>`, and by that time it was too late to redefine `IList<T>` and make it extend `IReadOnlyList<T>`. So, `IReadOnlyList<T>` was built from scratch. They could not make `IReadOnlyList<T>` extend `IList<T>`, because then it would have inherited the mutation methods, so they based it on `IReadOnlyCollection<T>` and `IEnumerable<T>` instead. They added the `this[i]` indexer, but then they either forgot to add other methods like `IndexOf()`, or they intentionally omitted them since they can be implemented as extension methods, thus keeping the interface simpler. ***But they did not provide any such extension methods.*** So, here, is an extension method that adds `IndexOf()` to `IReadOnlyList<T>`: ``` using Collections = System.Collections.Generic; public static int IndexOf<T>( this Collections.IReadOnlyList<T> self, T elementToFind ) { int i = 0; foreach( T element in self ) { if( Equals( element, elementToFind ) ) return i; i++; } return -1; } ``` Be aware of the fact that this extension method is not as powerful as a method built into the interface would be. For example, if you are implementing a collection which expects an `IEqualityComparer<T>` as a construction (or otherwise separate) parameter, this extension method will be blissfully unaware of it, and this will of course lead to bugs. (Thanks to Grx70 for pointing this out in the comments.)
This extension method is almost the same as Mike's. The only difference is that it includes a predicate, so you can use it like this: `var index = list.IndexOf(obj => obj.Id == id)` ``` public static int IndexOf<T>(this IReadOnlyList<T> self, Func<T, bool> predicate) { for (int i = 0; i < self.Count; i++) { if (predicate(self[i])) return i; } return -1; } ```
160,886
I have a MacBook Pro which has Leopard Mac OS X 10.5.8 and i want to upgrade this to Snow Leopard 10.6.2. Is it possible? If yes then give me some guidelines.
2010/07/07
[ "https://superuser.com/questions/160886", "https://superuser.com", "https://superuser.com/users/42125/" ]
This really isn't the right forum for a question of this sort our sister site superuser.com would be. That said this is very easy; just buy 10.6 from Apple, backup your system, boot from the disk, follow the installation instructions then update your system once it's installed - it's that easy.
According to Apple here are the required specs. * Mac computer with an Intel processor * 1GB of memory * 5GB of available disk space DVD drive for installation * QuickTime H.264 hardware acceleration requires a Mac with an NVIDIA GeForce 9400M, GeForce 320M, or GeForce GT 330M graphics processor. * Developer tools require 1GB of memory and an additional 3GB of available disk space. * OpenCL requires one of the following graphics cards or graphics processors: NVIDIA GeForce 320M, GeForce GT 330M, GeForce 9400M, GeForce 9600M GT, GeForce 8600M GT, GeForce GT 120, GeForce GT 130, GeForce GTX 285, GeForce 8800 GT, GeForce 8800 GS, Quadro FX 4800, Quadro FX5600, ATI Radeon HD 4670, ATI Radeon HD 4850, Radeon HD 4870 * 64-bit support requires a Mac with a 64-bit processor. * Grand Central Dispatch requires a Mac with a multicore processor.
2,556,344
I'm using quartz to display pdf content, and I need to create a table of contents to navigate through the pdf. From reading Apple's documentation I think I am supposed to use CGPDFDocumentGetCatalog, but I can't find any examples on how to use this anywhere. Any ideas? **Update:** Still haven't found a solution for this. I tired Alex' solution but the output I get looks like this: ``` 2011-07-27 09:16:19.359 LDS Scriptures App-iPad[624:707] key: Pages 2011-07-27 09:16:19.361 LDS Scriptures App-iPad[624:707] key: Count 2011-07-27 09:16:19.362 LDS Scriptures App-iPad[624:707] pdf integer value: 238 2011-07-27 09:16:19.363 LDS Scriptures App-iPad[624:707] key: Kids 2011-07-27 09:16:19.366 LDS Scriptures App-iPad[624:707] key: Type 2011-07-27 09:16:19.368 LDS Scriptures App-iPad[624:707] key: Outlines 2011-07-27 09:16:19.370 LDS Scriptures App-iPad[624:707] key: Count 2011-07-27 09:16:19.371 LDS Scriptures App-iPad[624:707] pdf integer value: 7 2011-07-27 09:16:19.372 LDS Scriptures App-iPad[624:707] key: First 2011-07-27 09:16:19.374 LDS Scriptures App-iPad[624:707] key: Parent 2011-07-27 09:16:19.375 LDS Scriptures App-iPad[624:707] key: Count 2011-07-27 09:16:19.376 LDS Scriptures App-iPad[624:707] pdf integer value: 7 ``` No idea yet how to turn that into a usable table of contents. Ideally I would like to get to an array of `NSDictionary` objects with a title and matching page number.
2010/03/31
[ "https://Stackoverflow.com/questions/2556344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/306372/" ]
Something like this might help you get started: ``` NSURL *documentURL = ...; // URL to file or http resource etc. CGPDFDocumentRef pdfDocument = CGPDFDocumentCreateWithURL((CFURLRef)documentURL); CGPDFDictionaryRef pdfDocDictionary = CGPDFDocumentGetCatalog(pdfDocument); // loop through dictionary... CGPDFDictionaryApplyFunction(pdfDocDictionary, ListDictionaryObjects, NULL); CGPDFDocumentRelease(pdfDocument); ... void ListDictionaryObjects (const char *key, CGPDFObjectRef object, void *info) { NSLog("key: %s", key); CGPDFObjectType type = CGPDFObjectGetType(object); switch (type) { case kCGPDFObjectTypeDictionary: { CGPDFDictionaryRef objectDictionary; if (CGPDFObjectGetValue(object, kCGPDFObjectTypeDictionary, &objectDictionary)) { CGPDFDictionaryApplyFunction(objectDictionary, ListDictionaryObjects, NULL); } } case kCGPDFObjectTypeInteger: { CGPDFInteger objectInteger; if (CGPDFObjectGetValue(object, kCGPDFObjectTypeInteger, &objectInteger)) { NSLog("pdf integer value: %ld", (long int)objectInteger); } } // test other object type cases here // cf. http://developer.apple.com/mac/library/documentation/GraphicsImaging/Reference/CGPDFObject/Reference/reference.html#//apple_ref/doc/uid/TP30001117-CH3g-SW1 } } ```
Here is my approach. 1. Download this framework [**`vfr reader`**](https://github.com/vfr/Reader) 2. Use this lines of code to get all PDF chapters ``` NSString *path = [[NSBundle mainBundle] pathForResource:@"Reader" ofType:@"pdf"]; NSURL *targetURL = [NSURL fileURLWithPath:path]; NSArray *arr = [ReaderDocumentOutline outlineFromFileURL:targetURL password:@""]; ``` Hope it will help you.
68,485,907
var ToDateTime = formatDate(DateTime.now(), [dd, '/', mm, '/', yyyy, ' ', HH, ':', nn, am]);
2021/07/22
[ "https://Stackoverflow.com/questions/68485907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16206561/" ]
The `in` operator looks for substrings. In your case, you want `==` to compare the whole string. Instead of: ``` if 'task' in elem ``` Use: ``` if 'task' == elem ```
The problem is that you named your list, list. List is a built-in keyword in Python, and you are confusing Python. Change the list name to something like `my_list` and change `if elem == 'task'` * Carden
15,654
We've more or less asserted why the [Hogwart's express exists](https://scifi.stackexchange.com/a/10288/3804), but at some point in Hogwarts history it didn't. No problem I though, everyone just apparated with their children to Hogsmeade, no problem a long and tedious process considering luggage, and number of children. Except then I realised, how would a muggleborn student get there? I'm assuming that despite the era (witch burning etc.) that the founders were actively recruiting and not just leaving students too far south from Hogwart's to grow up untrained. So how did they get the students to Hogwart's?
2012/04/29
[ "https://scifi.stackexchange.com/questions/15654", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/3804/" ]
I'm not totally sure, but I somehow remember reading from somewhere that they used portkeys. Even if I'm talking rubbish, it still seems like the most logical answer, as you could transport quite many children at the same time and you could do it quickly.
Before the Hogwarts Express, everyone used Portkeys: > > Portkeys were therefore arranged at collecting points all over > Britain. > > > For Muggle-borns, a teacher would explain how it worked. Source: [Hogwarts Express](https://www.pottermore.com/writing-by-jk-rowling/the-hogwarts-express)
6,522,042
I have two tables, the 1st: ``` users(id,name, birth_date) skills(user_id,skill_name,skill_level) ``` I want to select all users with 3 some skills on level 2. its possible make this in one query ? example: ``` user has 3,marcus,19/03/1989 4,anderson,08/02/1990 skills has 3,php,2 3,html,1 4,php,1 ``` what i want is: all users who has php 2 AND html 1.
2011/06/29
[ "https://Stackoverflow.com/questions/6522042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821223/" ]
``` select * from users u join skills s on u.id=s.user_id where skill_level=2 group by id having count(*)>2 ```
Okay. Now that you've updated your question a bit more, the answer becomes "yes, it can be done, but you shouldn't necessarily do it like that". Firstly, just to show that it can be done: ``` SELECT u.* FROM users u INNER JOIN skills s1 ON (u.id = s1.user_id AND s1.skill_name = 'php') INNER JOIN skills s2 ON (u.id = s2.user_id AND s2.skill_name = 'html') WHERE s1.skill_level = 2 AND s2.skill_level = 1 GROUP BY u.id; ``` Would have saved me quite a bit of typing if you'd explained what you wanted in the beginning! :) Now should you do the above? It's not very pretty, but the principle is that you join to the table twice for both different skills, using aliases (s1 and s2) to hide the fact that it's the same table. Sometimes this is the right approach. The trouble is that I suspect you'll have loads of variations on this where you want to sometimes find people with lots of skills at different levels, sometimes only one, etcetera. You might find writing the code to automatically generate those queries slightly complicated and it wont necessarily scale well. You *need* to read up on database normalization to better design your tables. And you should also have an id field for the skills table and then you can more easily use sub-queries when you need to.
2,364,612
Is it possible to pass a chunk of html content to a hidden field and how would I do this? Thanks Jonathan
2010/03/02
[ "https://Stackoverflow.com/questions/2364612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/100238/" ]
You could do this with Javascript: ``` <input type="hidden" id="htmlCodes" /> ``` ``` document.getElementById("htmlCodes").value = "<strong>Hello World</strong>"; ``` Just be sure that your values are properly-escaped when you pass them into the hidden form field. Online Demo: <http://jsbin.com/ubofu/edit>
You can also "spawn" a hidden textarea after processing the content inside. This can be done easily with Jquery : ``` $('#your_form') .append('<textarea name="content" class="hidden">' + your_content + '</textarea>'); ``` Here we assuming that you've got a "hidden" class, Bootstrap's got one, but you can also use this : CSS Code : ``` .hidden { display: none !important ; visibility: hidden !important; } ```
26,911,892
In Ubuntu, I have this line present in `/etc/resolv.conf`: ``` search example.com uk.example.com se.example.com ``` Now when I type `host svr1.uk` I get the record for svr1.uk.example.com If I `ping svr1.uk`, I see pings from svr1.uk.example.com. However, If I try to `ping svr1.uk` on a mac with the same `search` line present in /etc/resolv.conf I get `"ping: cannot resolve svr1.uk: Unknown host"` although I do see the record for srv1.uk.example.com from the `host` command. Does any one have a way to make whichever lookup method `ping` uses properly resolve the domain suffixes in the order presented in `/etc/resolv.conf`?
2014/11/13
[ "https://Stackoverflow.com/questions/26911892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4248705/" ]
This doesn't work for El Capitan anymore. If you upgrade to El Capitan you need to do this: 1. `defaults write /Library/Preferences/com.apple.mDNSResponder.plist AlwaysAppendSearchDomains -bool true` 2. Reboot See the mDNSResponder man page for more details.
**On OS X 10.7-8** Look for these lines (Around line 16; 10.8 starts around line 17), and add the third line on the end, then save the file ``` <string>/usr/sbin/mDNSResponder</string> <string>-launchd</string> <string>-AlwaysAppendSearchDomains</string> ``` **On OS X 10.9** This is still around line 17 and will need to be re-edited after an OS upgrade. The "-launchd" line won't exist, so just append the `alwaysappend` line. Restart the responder: ``` sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.mDNSResponder.plist sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.mDNSResponder.plist ``` **On OS X 10.10.1** The file is now called `com.apple.discoveryd.plist`, and you need to add a very similar item below the `ProgramArguments` tag. Add in `<string>--AlwaysAppendSearchDomains</string>` (note, there are *two* hyphens) to the items in the tag. Run a similar pair of load/unload commands but referencing this new plist
25,441,723
I'm just working with `HashMaps` and now it pops up a question I actually can't answer by myself... In my HashMap there are some entries. I'm now searching through all the entries for a certain value. If that value is found It delete it using `hashmap.remove();`. But I don't "only" want to delete the entry but the whole "position" of the HashMap so that there is no blank space between it. In the end the HashMap shouldn't have any value anymore (I think it will be null then, won't it?) Is there any possible way to do so? That's what I got so far but it only deletes the entry not the whole position... ``` for (Entry<Integer, String> entry : myMap.entrySet()) { if (entry.getValue().contains("EnterStringHere")) { myMap.remove(entry); } } ```
2014/08/22
[ "https://Stackoverflow.com/questions/25441723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3951790/" ]
Understanding how `HashMap` works here [Link](http://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.html). Also see java doc here [link](http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html). If you want to set pack your hashmap try to check size of the map then delete one then check size again for example. ``` hashmap.size(); => 10 hashmap.remove(obj); hashmap.size() => 9 ``` this means the hashmap is packed and will not have any empty entry. At the end hashmap will automatically will not contain any value in it
OK I got a codeable example that's pretty easy. ``` public class TestingThingsOut { public static void main(String [] args) { HashMap<Integer, String> myMap = new HashMap<Integer, String>(); myMap.put(123, "hello"); myMap.put(234, "Bye"); myMap.put(789, "asdf"); System.out.println(myMap); // it says: {789=asdf, 234=Bye, 123=hello} System.out.println(myMap.size()); // it says: "3" for (Entry<Integer, String> entry : myMap.entrySet()) { if (entry.getValue().contains("hello")) { myMap.remove(entry); } } System.out.println(myMap); // it says: {789=asdf, 234=Bye, 123=hello} System.out.println(myMap.size()); // it says: "3" again } ``` }
65,557,038
I am building a login page using Kivy and it always says that I have a name error and password is not defined. I found some tutorials but they look the same as mine so I cant figure out the problem. Hope someone can help.Thank you Here is my code: ``` FloatLayout: TextInput: id: "password" name: "password" multiline: False hint_text: 'Enter Password' hint_text_color: (1,1,1,.5) pos_hint: {'center_y': .45, 'center_x':.5} size_hint: .3,.1 on_text: self.foreground_color: (1,0,0,1) foreground_color: (1,1,1,1) background_color: (.14,.15,.30,.5) cursor_color: (1,1,1,1) Button: text:"Submit" pos_hint: {'center_y': .3, 'center_x':.5} size_hint: .1,.1 on_release: app.root.current = "dashboard" if password.text == "admin" else "login" root.manager.transition.direction = "left" ```
2021/01/04
[ "https://Stackoverflow.com/questions/65557038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14761890/" ]
As mentioned in the other answers, the issue is that you're changing an existing object every iteration instead of adding a new one. I'd like to add that that you can also use `reduce` instead (I personally prefer the syntax and it's a bit shorter): ```js let nums = [{id:1, first_name: "sade", last_name: "Smith"}, {id:2, first_name: "Jon", last_name: "Doe"}]; let em = []; let num2 = {id:null, name: ""} em = nums.reduce((accumulator, item) => { accumulator.push({ id: item.id, name: `${item.first_name} ${item.last_name}`; }) }, []) ``` More info about the `reduce` function can be found in the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce). --- Why does it work like this? --------------------------- If you want to know more about why your solution didn't work, it's important to understand that in JS there's a difference between `primitive values` and `objects`. By assigning a variable that contains an object to another variable, you are not assigning a new object, but only pointing to an existing one instead. This causes coupling between your objects, they are pointing to the same object, as can be demonstrated here: ```js var obj1 = {name: 'Sherlock Holmes', country: 'England'} var obj2 = obj1; obj2.country = 'US'; console.log(obj1.country) // US console.log(obj2.country) // US ``` Because of this, when you want to assign an object to another variable you need to clone its content, but create a **new object**, therefor the variable will point to a new object and not to the old one. There are many ways to do it, but few simple ones are: 1. Using the spread operator like this: ```js var obj1 = {name: 'Sherlock Holmes', country: 'England'} var obj2 = { ...obj1 }; obj2.country = 'US'; console.log(obj1.country) // England console.log(obj2.country) // US ``` 2. Stringifying then parsing using `JSON.stringify` and `JSON.parse` ```js var obj1 = {name: 'Sherlock Holmes', country: 'England'} var obj2 = JSON.parse(JSON.stringify(obj1)); obj2.country = 'US'; console.log(obj1.country) // US console.log(obj2.country) // US ``` There are more ways, and differences between those ways, if your object has nested objects as well, the replications might not occur correctly, at this point it's best to use a function that does the cloning for you, like lodash's `deepClone` function.
That's because you keep pushing the same object to the `em` array in each iteration in the `forEach` loop. A simple approach would be to do this: ``` const nums = [{id:1, first_name: "sade", last_name: "Smith"}, {id:2, first_name: "Jon", last_name: "Doe"}]; const em = []; nums.forEach(e => { em.push({id: e.id, name: `${e.first_name} ${e.last_name}`}); }); console.log(em); ``` You could also use the `map` functionality on arrays: ``` const nums = [{id:1, first_name: "sade", last_name: "Smith"}, {id:2, first_name: "Jon", last_name: "Doe"}]; const em = nums.map((item) => ({id: item.id, name: `${item.first_name} ${item.last_name}`})); console.log(em); ``` Essentially, we are creating a new object and pushing it into the `em` array in every iteration in the loop and in the process, removing the need for the `num2` object that you've declared. In addition, the `em` variable can be made `const` since using a `const` variable does not mean that the value it holds is immutable; we're simply pushing new elements into the array [which is perfectly possible](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const).
47,022,131
I have a vendor and customer in login, It works fine and redirects to the vendor or customer dashboard but how can I do the same after registration? **Register Controller** ``` protected $redirectTo = '/'; ``` **Login Controller** ``` <?php public function login(Request $request) { $this->validate($request, [ 'email' => 'required|email', 'password' => 'required|min:6', ]); if (Auth::guard('web')->attempt(['email' => $request->email, 'password' => $request->password, 'active' => 1, 'role_id' => 2], $request->remember)) { return redirect()->intended(route('customer.dashboard')); } elseif (Auth::guard('web')->attempt(['email' => $request->email, 'password' => $request->password, 'active' => 1, 'role_id' => 1], $request->remember)) { return redirect()->intended(route('vendor.dashboard')); } return redirect()->back()->withInput($request->only('email', 'remember')); } ```
2017/10/30
[ "https://Stackoverflow.com/questions/47022131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Not sure which version you are using I'm posting my answer for Laravel 5.7+ After registration Laravel call this method: ``` // Auth\RegisterController /** * The user has been registered. * * @param \Illuminate\Http\Request $request * @param mixed $user * @return mixed */ protected function registered(Request $request, $user) { // Assign role to $user. Then you can add condition. if($user->hasRole('admin'){ return redirect()->route('xxx'); } return redirect()->route('default'); } ``` Hope it can help you. Good Luck!
Overwrite the authenticated method in LoginController ``` protected function authenticated(Request $request, $user) { //write your logic's here if ($user->role_id == 1) { return redirect()->route('write the route name'); } return redirect('/home'); } ```
41,935,581
I'm trying to remove the empty element from the array by copying the existing element to a new array. However, initialization of the new array is causing my return value to be null even when I initialize it within the `for` loop. ``` public String[] wordsWithout(String[] words, String target) { for(int i = 0; i < words.length; i = i +1){ String store[] = new String[words.length]; if (words[i] == target){ words[i] =""; } else if(words[i] != target){ words[i] = store[i]; } } return words; } ```
2017/01/30
[ "https://Stackoverflow.com/questions/41935581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6865102/" ]
To check the equality use .equals() method i-e string1.equals(string2) and to check non-equality you can use the same method but with not(!) operator i-e. !string1.equals(string2). You should declare the store array outside the loop because in each iteration it makes a new object onamed store. In the else condition do this store[i] = words[i].
You shouldn't compare strings using `==` operator. This is incorrect, because strings are objects. Use `.equals()` method instead, this should fix your problem. Rest part of your code is quite confusing, it's hard to understand what you are trying to achieve: you create new string array `store` each time in loop iterations, and then assign its `null` (by default) values to `words[i]`. You should elaborate your code and algorithm.
3,855,218
I'm trying to get the real size of an image displayed in an image view. Actually my image is larger than the screen and the imageview is resizing the image to diplay it. I'm looking for this new size. I've tried to override the onDraw method of the ImageView in a custom view but I'm not getting the correct height and width... ``` public class LandImageView extends ImageView { public LandImageView( Context context ) { super( context ); } public LandImageView(Context context, AttributeSet attrs) { super(context, attrs); } public LandImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onDraw( Canvas canvas ) { super.onDraw( canvas ); int test = this.getWidth(); int test2 = this.getHeight(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); } } ``` Do you have any clues ?
2010/10/04
[ "https://Stackoverflow.com/questions/3855218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/465803/" ]
I'm just passing by but hope it still helps I'm going under the assumption your talking about bitmaps in your imageView what you want to understand is the difference between `bmpBack.getWidth()` -> this gives you the size of your bitmap and `bmpBack.getScaledWidth(canvas)`; -> this will give you the size of the bitmap as displayed on the screen. I never used ImageView because the relative display was driving me mad so in the end I just override the onDraw and did my canvas very similarly to opengl. I think this is your problem cheers Jason
If I get you correctly you need your ImageView dimension, in order to scale your image accordingly. I did this with a custom class, where I override the `onMeasure()` call to get width and height. ``` class LandImageView extends ImageView{ public LandImageView (Context context, AttributeSet attrs) { super (context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); final int width = MeasureSpec.getSize(widthMeasureSpec); final int height = MeasureSpec.getSize(heightMeasureSpec); Log.v("", String.format("w %d h %d", width, height)); // width and height are the dimensions for your image // you should remember the values to scale your image later on this.setMeasuredDimension(width, height ); }} ``` In onMeasure you get the width and height for your image so that it fits your view. You can use the LandImageView in your Layout like this: ``` <my.package.LandImageView ... > ```
33,352,930
I'm using JQ <https://stedolan.github.io/jq/> to work in bash with my json and when I read the json is throwing me an error ``` parse error: Invalid numeric literal at line 2, column 5= ``` Since my json has some comments ``` // comment "spawn": {} ``` I've been seen looking the options and I cannot find any option to fix the problem. Any idea how to solve it?
2015/10/26
[ "https://Stackoverflow.com/questions/33352930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/854207/" ]
JSON and thus jq do not support comments (in the usual sense) in JSON input. The jq FAQ lists a number of tools that can be used to remove comments, including jsonlint, json5, and any-json. I'd recommend one that can act as a filter. See <https://github.com/stedolan/jq/wiki/FAQ#processing-not-quite-valid-json> for links and further details.
Remove them; JSON does not support comments. (JSON is defined [here](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf); you can see a briefer description of the grammar [here](http://json.org).)
16,268,868
I am using a function "loadScript" to insert an external .js if the browser detects it is online. ``` <script type="text/javascript"> function loadScript() { if (navigator.onLine == true) { var src = "js/getdata.js"; var script = document.createElement("script"); script.type = "text/javascript"; script.src = src; document.getElementsByTagName("head")[0].appendChild(script); } } </script> ``` It all works fine except that the final script appears as... ``` <script type="text/javascript" src="js/getdata.js"> function getData() // get MySQL data from db { <?php $dbopen = 0; // database flag $con = mysql_connect("website.co.uk","guest","password"); mysql_select_db("DB", $con); if (!$con) {die('Could not connect: ' . mysql_error());} else {$dbopen = 1;} ?> ``` etc... And the Firebug console tells me the function getData is not defined and the content ``` <?php ``` is a syntax error... I would like to get the script into the head and have it defined as a usable function within the DOM. I would appreciate any thoughts you may have. GitaarLAB asked for the whole code, so here it is. ``` <html> <head> <script type="text/javascript"> function loadScript() { if (navigator.onLine == true) { var src = "js/getdata.js"; var script = document.createElement("script"); script.type = "text/javascript"; script.src = src; document.getElementsByTagName("head")[0].appendChild(script); } } </script> </head> <body> <script type="text/javascript"> loadScript(); </script> </body> </html> ``` The output is... ``` <script type="text/javascript" src="js/getdata.js"> function getData() { <?php $hhgopen = 0; $con = mysql_connect("website.co.uk","guest","password"); mysql_select_db("ThisDB", $con); if (!$con) { die('Could not connect: ' . mysql_error()); } else { $result = mysql_query("SELECT * FROM articles", $con); $numrows = mysql_num_rows($result); $hhgopen = 1; } ?> } </script> ```
2013/04/28
[ "https://Stackoverflow.com/questions/16268868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1150866/" ]
If you want the script to be generated by PHP, you need to put it in a PHP file. Rename the file to `js/getdata.js.php` and update the `src` accordingly. Another option would be to configure the web server to parse all `.js` files as PHP, but it's unlikely you actually want to do that.
The problem is solved. Thanks to Mark Parnell and W3Geek who gave me the script.js.php extension clue. The element to load the script should not be a function. Details: It now runs as a script in the head, loads the function if it is online, then waits for window.onload before trying to call the new function. So now, if the app is online, it gets data from PHP. If the app is offline it gets data from cache and localStorage. IOS no longer parses the PHP within the getData function which causes an error when the app is offline. Hope this is of some use. ``` <html> <head> <script type="text/javascript"> if (navigator.onLine == true) { var src = "js/getdata.js.php"; var script = document.createElement("script"); script.type = "text/javascript"; script.src = src; document.getElementsByTagName("head")[0].appendChild(script); } </script> </head> <body> <script type="text/javascript"> window.onload=function(){getData();}; </script> </body> </html> ```
26,531,065
I have a method that takes an array as a parameter and returns a boolean. Inside the method, I have an if/else statement. If the statement is true, I want the result to return true, if the statement is false, I want the statement to returns false. ``` public static boolean allPositive (double[] arr) { for (int i = 0; i < arr.length; i++) { if(arr[i] > 0) { return true; } else { return false; } } return //What do i put here? } ``` } Of course, it needs a return value at the end. However, I am confused on what I should return at the bottom. How should I rewrite this?
2014/10/23
[ "https://Stackoverflow.com/questions/26531065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4168379/" ]
``` public static boolean allPositive (double[] arr) { boolean b = true; for (int i = 0; i < arr.length; i++) { if(!(arr[i] > 0)) { b = false; } } return b; } ``` The way Java works, it ensures no problems with your code by making sure all your returns happen outside of the if else statement. This because, a common bug by programmers is to return in the if else statement, but never create an else condition, so the method never returns anything. Doing it this way is more of a good practice thing so you don't bug out later trying to figure out why a method won't return.
You have to return in the end of the method (after the loop) the value that should be returned if an empty array is passed to your method. It's up to you to decide whether an empty array is "allPositive" or not.
61,693,429
I am trying to transform the array using `.reduce` function into an object of type: ``` { "date": xxxx, "amount": xxxx, } ``` Insted of: ``` {01-2018: 0, 09-2019: 0, 02-2020: 0, 03-2020: 142.95999999999998, 04-2020: 652.78, …} ``` I would like to obtain a json like this one: ``` { "date": 01-2018, "amount": 0, }, { "date": 09-2019, "amount": 0, }, { "date": 02-2020, "amount": 0, }, { "date": 03-2020, "amount": 142.95999999999998, }, ``` This is my code: ``` import React, { Component } from 'react'; import moment from "moment"; class RentabilidadMensual extends Component { //Este componente extendido es hijo de rentalidad y recibe de willmount los datos de la API. //Se calcculará la rentablidad mensual obtenida. constructor (props){ super(props) this.state ={ monthlyData: [], sortedData: [], monthlyTotalImport: [], } } componentWillMount() { var resultn = { NuevosDatosFinalizadas2: [] }; var resultFinal = { NuevosDatosFinal: [] }; function RentOperFinalizada (importe, Crypto, ValCryptoOperVenta , comisionCompra, comisionVenta, FechaCompra, FechaVenta){ function NuevoImporte(){ let tmpN = Number(ValCryptoOperVenta) * Number(Crypto) let R1 = tmpN - (Number(comisionCompra) + Number(comisionVenta)) return R1 } let P = ((NuevoImporte() * 100)/Number(importe)) - 100 //Rentabilidad //console.log("voy a calcular: ",NuevoImporte() , " ", Number(importe) ) let G = NuevoImporte() - Number(importe) //Cantidad ganada Neto let C = Number(comisionCompra) + Number(comisionVenta) //Comisiones Totales let D = moment(FechaVenta).diff( FechaCompra, 'days') console.log("Comisiones totales:", C) //R es Importe Total ganado en EUR //P es Rentabilidad en porcentaje //G es la cantidad ganada NETO en EUR. //C es Comisiones Totales en EUR //D es los días transcurrido entre la fecha compra y fecha venta. return [P.toFixed(2), G.toFixed(2), C.toFixed(2), D]; } //Añadimos simplemente los campos: var DataFromApiTemp = this.props.data.map((x) => Object.assign( x, x, {'RentabilidadPorcentaje' : ""}, {'CantidadGanadaNETO' : ""}, {'ComisionesTotales' : ""}, {'DiasTranscurrido' : ""} )); console.log("nuevo:",DataFromApiTemp ) DataFromApiTemp.forEach((value, key) => { if (value.estado == "Finalizado" && value.moneda_crypto == this.props.selectedcrypto){ console.log("valor.estado: ", value.estado, key) //Se llama la función para realizar los calculos. var r = RentOperFinalizada ( value.compra_en_fiat, value.compra_crypto_cantidad, value.venta_crypto_valorOper , value.compra_gasto, value.venta_gasto, value.compra_fecha_oper, value.venta_fecha_oper) //FIN //Actualizamos los valores de estos campos: value.RentabilidadPorcentaje = r[0]; value.CantidadGanadaNETO = r[1]; value.ComisionesTotales = r[2]; value.DiasTranscurrido = r[3]; resultn.NuevosDatosFinalizadas2.push(r); console.log("Datos de la API", resultn.NuevosDatosFinalizadas2) } }) console.log("dar algo modificado:", DataFromApiTemp) //Ya tenemos un nuevo Jason contruido donde se añadio previemnte las keys: //RentabilidadPorcentaje, CantidadGanadaNETO, ComisionesTotales, DiasTranscurrido let data = []; DataFromApiTemp.map(value => { let d = new Date(value.compra_fecha_oper); data.push({...value, date2: d}); }); //Ordenamos por fecha y creciente. let sortedData = data.sort((a, b) => a.date2 - b.date2); console.log(sortedData, 'sorted'); //Añadimos nuevo campo yearMonth: "MES-FECHA" let monthlyData = []; sortedData.map(value => { let d = new Date(value.compra_fecha_oper); let yearMonth = ("0" + (d.getMonth() + 1)).slice(-2) + "-" + d.getFullYear(); monthlyData.push({...value, yearMonth: yearMonth}); }); console.log(monthlyData, 'monthly data'); let result = monthlyData.reduce((acc, item) => ({ ...acc, [item.yearMonth]: (acc[item.yearMonth] || 0) + Number(item.CantidadGanadaNETO) }), {}); this.setState([{monthlyTotalImport: result}]); console.log("Result:", result) // var jsonObjFinal = // { // "fecha": monthlyTotalImport, // "importe": result, // } // // resultFinal.NuevosDatosFinal.push(jsonObjFinal); // } render() { const DataFromApi = this.props.data; var TipoCrypto = this.props.selectedcrypto; return ( <div> test... {JSON.stringify(this.state.monthlyTotalImport)} </div> ); } } export default RentabilidadMensual; ``` Thank you. DataFromApiTemp have this value (example): [![enter image description here](https://i.stack.imgur.com/GkIcW.png)](https://i.stack.imgur.com/GkIcW.png) Code tried from @canberker the result is: [![enter image description here](https://i.stack.imgur.com/laDqT.png)](https://i.stack.imgur.com/laDqT.png) My objective is to get a json format with my already data of month-yer and amount. If I have this data I will be able to charts this ressult.....
2020/05/09
[ "https://Stackoverflow.com/questions/61693429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12380654/" ]
``` let aggregatedMonthlyData = monthlyData.reduce((acc, item) => ({ ...acc, [item.yearMonth]: (acc[item.yearMonth] || 0) + Number(item.CantidadGanadaNETO) }), {} ); const formatAggregatedMonthlyData = function(aggregatedMonthlyData) { const dateFieldName = 'date'; const amountFieldName = 'amount'; const result = []; for (let [date, amount] of Object.entries(aggregatedMonthlyData)) { result.push({ [dateFieldName]: date, [amountFieldName]: amount }); } return result; } const result = formatAggregatedMonthlyData(aggregatedMonthlyData); console.log(result); ```
Assuming your input value is like below ``` const input = {"01-2018": 0, "09-2019": 0, "02-2020": 0, "03-2020": 142.95999999999998, ..} ``` Below solution will work ``` const transformData = input => JSON.stringify(Object.entries(input).reduce((acc, [date, amount]) => [...acc, { date, amount }], [])) const output = transformData(input) ```
2,357,091
A simple situation here, If I got three threads, and one for window application, and I want them to quit when the window application is closed, so is it thread-safe if I use one global variable, so that three threads will quit if only the global variable is true, otherwise continue its work? Does the volatile help in this situation? C++ programming.
2010/03/01
[ "https://Stackoverflow.com/questions/2357091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/283734/" ]
If you only want to "read" from the shared variable from the other threads, then it's ok in the situation you describe. Yes the *volatile* hint is required or the compiler might "optimize out" the variable. Waiting for the threads to finish (i.e. `join`) would be good too: this way, any clean-up (by the application) that should occur will have a chance to get done.
It's safe right up to the point that you change the variable's value to get the threads to quit. At that point 1) you need to synchronize access, and 2) you need to do something (sorry, volatile isn't enough) to assure that the new value gets propagated to the other threads correctly. The former part is pretty easy. The latter substantially more difficult -- to the point that you'll almost certainly need to use some sort of library- or OS-provided mechanism.
104,017
On a clear day is it possible to see the Isles of Scilly from Cornwall with the aid of binoculars? A distance of around 40km. I know on a very clear day you can only see maximum 20km from sea level but the coast of Cornwall is higher than sea level. So does the height advantage of the cliffs enable you to see further across the horizon? There are a couple of online forums that suggest you can see the Isle of Scilly from Cornwall but no photographic evidence. [![Google map as the crow flies](https://i.stack.imgur.com/tyymu.jpg)](https://i.stack.imgur.com/tyymu.jpg)
2017/10/20
[ "https://travel.stackexchange.com/questions/104017", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/19694/" ]
I saw the islands from near St Just last week, a distance of almost 30 miles. Very faint, but definitely visible. I had no trouble with binoculars separating the islands and the hill on Samson.
Based on [Mark Mayos](https://travel.stackexchange.com/users/101/mark-mayo) excellent answer to this [question](https://travel.stackexchange.com/questions/3666/can-i-see-lebanon-from-cyprus) and calculating the height 80 metres close to the Cornwall coast line you can only see a maximum of 32km with the naked eye. This is based on the calculation: [![calculation](https://i.stack.imgur.com/mTV4O.png)](https://i.stack.imgur.com/mTV4O.png) where d = distance in km and h = height in metres.
61,055,324
I can't run any binary in my docker container. Dockerfile: ``` FROM ubuntu:eoan AS compiler-build RUN apt-get update && \ dpkg --add-architecture i386 && \ apt-get install -y gcc \ gcc-multilib \ make \ cmake \ git \ python3.8 \ bash WORKDIR /home ADD . /home/pawn RUN mkdir build WORKDIR /home/build ENTRYPOINT ["/bin/bash"] CMD ["/bin/bash"] ``` I can't even use `file` builtin: ``` [root@LAPTOP-EJ5BH6DJ compiler]:~/dev/private/SAMP/compiler (v13.11.0) (master) dc run compiler file bash /usr/bin/file: /usr/bin/file: cannot execute binary file ```
2020/04/06
[ "https://Stackoverflow.com/questions/61055324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/309240/" ]
From [this forum thread](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/2109): > > This error occurs when you use a shell in your entrypoint without the "-c" argument > > > So, if you change your `Dockerfile` to end with ``` ENTRYPOINT [ "/bin/bash", "-l", "-c" ] ``` then you can run binary files. Note the purpose of the options for `/bin/bash`, from the manpage: * `-l`: Make bash act as if it had been invoked as a login shell * `-c`: If the `-c` option is present, then commands are read from the first non-option argument `command_string`. If there are arguments after the `command_string`, the first argument is assigned to `$0` and any remaining arguments are assigned to the positional parameters. The assignment to `$0` sets the name of the shell, which is used in warning and error messages. Additionally, [this article](https://www.ctl.io/developers/blog/post/dockerfile-entrypoint-vs-cmd/) is a worthwhile read on how to use both `ENTRYPOINT` and `CMD` together, and what their differences are. **EDIT:** [Here](https://phoenixnap.com/kb/docker-cmd-vs-entrypoint)'s another article that goes into a trivial (but clearer than the first article) example using the `echo` shell builtin. **EDIT:** Here's an adaptation of the trivial example from the second article I linked: ``` FROM ubuntu ENTRYPOINT [ "/bin/bash", "-l", "-c" ] CMD [ "ls" ] ``` ``` $ docker build -t test . $ docker run --rm test bin boot ... var $ docker run --rm test "ls etc" adduser.conf alternatives apt ... update-motd.d xattr.conf ``` Note the `"` around `ls /etc`. Without the quotes, the argument `/etc` doesn't seem to be passed to the `ls` command as I might expect.
I hit the same error. Unlike the other answers, my error was related to my `docker run` parameters: ``` # failed docker run -it $(pwd | xargs basename):latest bash # worked docker run -it $(pwd | xargs basename):latest ``` I didn't need to add `bash` as I already had this in my Dockerfile: ``` ENTRYPOINT ["/bin/bash"] ```
38,358,953
I am trying to find the field name "User Settings Updated Successfully" from the following code: ``` <div id="btn-usersettings" class="tab-content clearfix"> <h4>Set your User Settings in This Section</h4> <div class="notice success"> <i class="icon-ok icon-large"/> User Settings Updated Successfully <a href="#close" class="icon-remove"/> </div> <fieldset> <input type="submit" name="submit" value="Save Changes"/> </div> ``` The code that I am using in C# is ``` var title = Driver.Instance.FindElements(By.ClassName("notice success"))[0]; if (title != null) return title.Text; return " "; ``` Basically I am trying to clarify, if the user update has been successful or not, so if it is successful I want to code to return me with the text "User Settings Updated Successfully". But the problem that I am facing is even if the update is successful, it is failing to return me the value and it is throwing exception.
2016/07/13
[ "https://Stackoverflow.com/questions/38358953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When you open the menu, you should listen for clicks on document. Then when the document is clicked you close the popup (and you remove the listener on the document as well). PS: keep your listener on the menu-container as well ;) Here is an example you can use (I edited your fiddle) : ```js (function(){ //Remember if the menu is opened or not var menuOpened = false; var menuElement = document.getElementById('menu_control'); var menuContainer = document.getElementById('menu-standard'); // Add click listener on menu icon menuElement.addEventListener('click', onMenu_click); // Add click listener on menu menuContainer.addEventListener('click', onMenuContainer_click); function toggleMenu(){ menuOpened = !menuOpened; if (menuOpened){ menuContainer.className += ' show_menu'; document.addEventListener('click', onDoc_click); } else{ menuContainer.className = menuContainer.className.replace('show_menu', '').trim(); document.removeEventListener('click', onDoc_click); } } function onMenu_click(domEvent){ domEvent.stopPropagation(); toggleMenu(); } function onDoc_click(domEvent){ domEvent.stopPropagation(); toggleMenu(); } function onMenuContainer_click(domEvent){ domEvent.stopPropagation(); } })(); ``` ```css .nav, .menu_control{font-size:16px;line-height:23px;} .nav{display:none;position:relative;width:219px;height:0;top:7px;list-style:none;z-index:9;background-color:#666;color:#fff} .nav .sub-menu{list-style:none;padding-left:14px;} .nav .sub-menu li{width:192px;background-color:#666;} .nav .sub-menu .current-menu-item > a{background-color:#666;} .nav a, .show_menu{display:block;} .nav a{color:#fff;padding:7px 14px;} .nav a:hover{color:white;background-color:#999;} .nav .current-menu-item > a{color:#fff;background-color:#666;cursor:text;} .nav li{background-color:#666;} .menu_control{display:block;color:#111111;cursor:pointer;margin:7px -27px 0 -27px;padding-right:27px;padding-left:27px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;} .navicon-line{width:32px;height:4px;border-radius:1px;margin-bottom:5px;background-color:#333;} ``` ```html <span id="menu_control" class="menu_control"> <div class="navicon-line"></div> <div class="navicon-line"></div> <div class="navicon-line"></div> </span> <ul id="menu-standard" class="nav"> <li id="menu-item"><a href="/">Home</a></li> <li id="menu-item"><a href="#">test</a> <ul class="sub-menu"> <li id="menu-item"><a href="#">test</a></li> <li id="menu-item"><a href="#">test</a></li> <li id="menu-item"><a href="#">test</a></li> <li id="menu-item"><a href="#">test</a></li> </ul> </li> <li id="menu-item"><a href="#">test</a></li> </ul> <br /> Content Content Content ``` It's not the best way to do it because you add several click listeners... You could have just one listener on the doc and do different things depending on the target of the event...
Thanks to [finding-closest-element-without-jquery](https://stackoverflow.com/questions/18663941/finding-closest-element-without-jquery) my solution is based on: * window.onload: try to insert always your code in such handler to be sure all the elements are already loaded and so ready for your code * to test if an element has a class use `menu.classList.contains('show_menu')` * to add/remove classes use `menu.classList.remove('show_menu');` or `menu.classList.add('show_menu');` * add a listener for the whole document so that if you clicked ouside your menu you can remove the corresponding show\_menu if added My snippet: ```js function closest(el, selector) { var matchesFn; // find vendor prefix ['matches','webkitMatchesSelector','mozMatchesSelector','msMatchesSelector','oMatchesSelector'].some(function(fn) { if (typeof document.body[fn] == 'function') { matchesFn = fn; return true; } return false; }) var parent; // traverse parents while (el) { parent = el.parentElement; if (parent && parent[matchesFn](selector)) { return parent; } el = parent; } return null; } window.onload = function() { (function(){ document.addEventListener('click', function(e) { if (e.target.className.indexOf('menu_control') == -1 && e.target.className.indexOf('navicon-line') == -1 && closest(e.target, '#menu-standard.nav') == null) { // menu-standard document.getElementById('menu-standard').classList.remove('show_menu'); } }, false); var classes = document.getElementsByClassName('menu_control'); for (i = 0; i < classes.length; i++) { classes[i].onclick = function() { var menu = this.nextElementSibling; if (menu.classList.contains('show_menu')) menu.classList.remove('show_menu'); else menu.classList.add('show_menu'); }; } })(); } ``` ```css .nav, .menu_control{font-size:16px;line-height:23px;} .nav{display:none;position:relative;width:219px;height:0;top:7px;list-style:none;z-index:9;background-color:#666;color:#fff} .nav .sub-menu{list-style:none;padding-left:14px;} .nav .sub-menu li{width:192px;background-color:#666;} .nav .sub-menu .current-menu-item > a{background-color:#666;} .nav a, .show_menu{display:block;} .nav a{color:#fff;padding:7px 14px;} .nav a:hover{color:white;background-color:#999;} .nav .current-menu-item > a{color:#fff;background-color:#666;cursor:text;} .nav li{background-color:#666;} .menu_control{display:block;color:#111111;cursor:pointer;margin:7px -27px 0 -27px;padding-right:27px;padding-left:27px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;} .navicon-line{width:32px;height:4px;border-radius:1px;margin-bottom:5px;background-color:#333;} ``` ```html <span class="menu_control"> <div class="navicon-line"></div> <div class="navicon-line"></div> <div class="navicon-line"></div> </span> <ul id="menu-standard" class="nav"> <li id="menu-item"><a href="/">Home</a></li> <li id="menu-item"><a href="#">test</a> <ul class="sub-menu"> <li id="menu-item"><a href="#">test</a></li> <li id="menu-item"><a href="#">test</a></li> <li id="menu-item"><a href="#">test</a></li> <li id="menu-item"><a href="#">test</a></li> </ul> </li> <li id="menu-item"><a href="#">test</a></li> </ul> <br /> Content Content Content ```
14,727,407
I am new to android. I want to display buttons on the screen at particular x and y position. I have an one Relative layout and i put background image to that relative layout now i want to create or draw buttons on that image at particular x and y position and that X and Y position are given by me through XML i have 5 X and Y position. i google a lot but not found any relative solutions every one says using AbsoluteLayout we can do that but i dont want to use AbsoluteLayout. Please help me out.
2013/02/06
[ "https://Stackoverflow.com/questions/14727407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/996794/" ]
Is your `web config` pointing to the correct database? Are the credentials correct? Entity Framework will create tables in the database if you are going to use the `MVC4 WebSecutiy()` to handle the Authentication and Authorisation of users. This could be throwing the exception. In this case where you cannot create the tables needed for the membership provider, you will need to exclude this from the system. See this [here](http://weblogs.asp.net/jgalloway/archive/2012/08/29/simplemembership-membership-providers-universal-providers-and-the-new-asp-net-4-5-web-forms-and-asp-net-mvc-4-templates.aspx). Alternatively create a new MVC4 project and select empty template and just put in the bits you need.
I encountered a similar error after refactoring and renaming some code. The issue was that my C# code didn't match table name in the Database. My code in c#: ``` public virtual DbSet<MyTableName> ``` And the table name in SQL Server: ``` MyActualTableName ``` Since the table names didn't match (MyTableName != MyActualTableName), I got this (misleading) error: > > `Create TABLE permission denied in database MyDatabase` > > > Took me awhile to see what I'd messed up, but matching the table names resolved the error.
10,085,132
Is there any way to simply declare static `NSString` as defined int identifier ? I want to do something like in C++ `#define MY_SIMPLE_ID 4`. EDIT: Where should I declare this? In C++ I have global access to resource file with it. Is there a way to do that in Objective-C?
2012/04/10
[ "https://Stackoverflow.com/questions/10085132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1317394/" ]
Why not using : ``` #define MY_STRING @"MyString" ```
You can also go into your Project or Target **Build Settings**, and add to **Preprocessor Macros** or **Preprocessor Macros Not Used In Precompiled Headers**. See [Xcode Preprocessor Macros](https://stackoverflow.com/a/245288/1318452) for the distinction between these two options.
9,795,693
I am learning c programming in Linux. There are a lot of linux functions I need to look at. Is there a website that gives me the details of the Linux functions?
2012/03/20
[ "https://Stackoverflow.com/questions/9795693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1250904/" ]
Are you referring to system calls in Linux? There are lots of sources. The man pages are your good friends in this regard. Try also <http://linux.die.net/man/2/syscalls>. I am sure there are lots of others.
IMHO <http://linux.die.net/man/> is the easiest to get to start with. It has useful sections introductions, so you can get your bearings Most usefully are the one line synopsis pages, e.g. <http://linux.die.net/man/3/> This shows the scale of what you are asking, and also lets you search for a key word describing each function within your browser, which can be very handy. As has been pointed out, it is not the most up-to-date, but IMHO it is easier for a beginner to use than the alternative I've seen (not that there can't be something better, just google doesn't bother to show it). Also worth trying `apropos` or `man 3 -K` or aman -k`
1,476,107
I am wondering how to notate "for all positive real value $c$" Is there a correct notation among the following? $$ \forall c \in \mathbb{R} > 0\\ \forall c \left( \in \mathbb{R} \right) > 0\\ \forall c > 0 \in \mathbb{R}\\ \forall c > 0 \left( \in \mathbb{R} \right)\\ $$ My ultimate goal is notating the following sentence. "$o(g(n))=\{f(n):$ For any constant positive real value $c$, there is a constant $n\_0$ such that $0 \le f(n) \lt cg(n)$ for all $n \ge n\_0\}$" My trial is $$ o(g(n))=\{f(n):\forall c>0(c\in\mathbb R), \exists n\_0\in\mathbb{N} \ \ \ \ s.t.\ \forall n>n\_0,\ \ 0 \le f(n) \lt cg(n)\} $$ I want to correct this part: $\forall c>0(c\in\mathbb R)$
2015/10/12
[ "https://math.stackexchange.com/questions/1476107", "https://math.stackexchange.com", "https://math.stackexchange.com/users/250170/" ]
I see someone has already explained why not the options you listed. Alternative options, summing up comments : 1. $\forall c\in\mathbb R^+\_0\text\ \{0\}$ 2. $\forall c\in\mathbb R,c>0$ 3. $\forall c\in (0,\infty)$ From comments: 4. $\forall c\in\mathbb R\_{>0}$ (similar:[this question](https://math.stackexchange.com/questions/27968/how-does-one-denote-the-set-of-all-positive-real-numbers))
Another commonly used self-explanatory notation is $\mathbb{R}\_{> c}$. Anything beyond half-line ranges would need some interval notation like $(a,b)$ or $]a,b[$.
3,300,708
I'm getting a strange error. I have a function of the following signature: ``` template <typename DATA, DATA max> static bool ConvertCbYCrYToRGB(const Characteristic space, const DATA *input, DATA *output, const int pixels) { ``` Which is later called like this: ``` case kByte: return ConvertCbYCrYToRGB<U8, 0xFF>(space, (const U8 *)input, (U8 *)output, pixels); case kWord: return ConvertCbYCrYToRGB<U16, 0xFFFF>(space, (const U16 *)input, (U16 *)output, pixels); case kInt: return ConvertCbYCrYToRGB<U32, 0xFFFFFFFF>(space, (const U32 *)input, (U32 *)output, pixels); case kFloat: return ConvertCbYCrYToRGB<R32, FLT_MAX>(space, (const R32 *)input, (R32 *)output, pixels); case kDouble: return ConvertCbYCrYToRGB<R64, DBL_MAX>(space, (const R64 *)input, (R64 *)output, pixels); ``` The U\* and R\* are aliases for the unsigned integer and floating point types, respectively. What's weird is that all the integer ones work perfectly, while the floating point ones fail with a somewhat enigmatic error: ``` DPXColorConverter.cpp:171: error: no matching function for call to ‘ConvertCbYCrYToRGB(const dpx::Characteristic&, const dpx::R32*, dpx::R32*, const int&)’ ``` Any thoughts?
2010/07/21
[ "https://Stackoverflow.com/questions/3300708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/398098/" ]
As aaa pointed out, you can't use floating point numbers as template value parameters. But in this instance you don't need to. Get rid of the second parameter entirely, and then in the definition of ConvertCbYCrYToRGB instead of using 'max' use `std::numeric_limits<DATA>::max()`. Documentation on numeric\_limits is here: <http://www.cplusplus.com/reference/std/limits/numeric_limits/>
you can not use floating point numbers at template value parameters. Template value parameters must be integral types, ICE to be exact: <http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/template_non-type_arguments.htm>
14,357,196
I want to know if we can host Drupal application on AppHarbor ? Thanks
2013/01/16
[ "https://Stackoverflow.com/questions/14357196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1138133/" ]
this may help you ``` DataGridViewImageColumn delCol = new DataGridViewImageColumn();//create image column delCol.ImageLayout = DataGridViewImageCellLayout.Zoom;//column properties int icIndex = DGV_showTable.Columns.Add(delCol);//add column to DGV DGV_showTable.Columns[icIndex].Name = "Delete";//set name for column Image image = Image.FromFile(@"C:\Users\mohab.MOHAMMED\Desktop\delete.png");//load img png foreach (DataGridViewRow row in DGV_showTable.Rows)//foreach on all rows { row.Cells["Delete"].Value = image;//loadimage to dgv on spicific column } ```
You have to change `img.ValuesAreIcons` from `true` to `false` on the second code that you wrote it. It will works, it happened to me when I used your code to fix this problem.
34,487,470
I have a list of an Object and I want to detect whether Object Id is duplicate or not. Here is the object: ``` public class data{ private String id; private String value; private String status; } ``` All duplicate `data` will have "invalid" `status` except the first one. What is the most effective way for this?
2015/12/28
[ "https://Stackoverflow.com/questions/34487470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4101051/" ]
Try like this first you should override `equals` method to check duplicates ``` private class data{ private String id; private String value; private String status; public data(String id, String value, String status) { this.id = id; this.value = value; this.status = status; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public String toString() { return "data{" + "id='" + id + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof data)) return false; data data = (data) o; return !(id != null ? !id.equals(data.id) : data.id != null); } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } } ``` Then test like this ``` public class Test { public static void main(String[] args ) { List<data> dataList=new ArrayList<>(); dataList.add(new data("1","somevalue","somestatus")); dataList.add(new data("1","somevalue","somestatus")); dataList.add(new data("1","somevalue","somestatus")); dataList.add(new data("2","somevalue","somestatus")); dataList.add(new data("3","somevalue","somestatus")); List<data>validList=new ArrayList<>(); List<data>duplicateList=new ArrayList<>(); for (data data:dataList){ if (!(validList.contains(data))){ validList.add(data); System.out.println(validList); }else{ duplicateList.add(data); System.out.println(duplicateList); } } } ```
Make a list of the `id` of objects. Loop over the list of objects. See if the `id` of each object is already in the list. If the `id` is already present, then change the `status` of the object. Otherwise, add the `id` of the object to the list.
33,677,920
I am trying to cast a sfixed (from ieee.fixed\_pkg) to std\_logic\_vector and I wonder what the correct syntax is and why the following is (appearently wrong). I tried compiling the following 3 architectures: ``` library ieee; use ieee.std_logic_1164.all; use ieee.fixed_pkg.all; entity test is port (input: in sfixed(0 downto -7) := x"00"; output: out std_logic_vector(7 downto 0) := x"00"); end; ``` Architecture a: ``` architecture a of test is begin output <= std_logic_vector(input); end; ``` Architecture b: ``` architecture b of test is begin proc: process (input) begin output <= std_logic_vector(input); end process; end; ``` Architecture c: ``` architecture c of test is begin proc: process (input) begin if ('1' and '1') then output <= std_logic_vector(input); end if; end process; end; ``` The compiler I've used was "ModelSim ALTERA vcom 10.3d Compiler 2014.10 Oct 7 2014". Architectures a and b don't compile with the error message: ``` Error: [...] Index value -7 (of type std.STANDARD.NATURAL) is out of range 0 to 2147483647. ``` But architecture c compiles, while still giving me the warning message: ``` Warning: [...] Index value -7 (of type std.STANDARD.NATURAL) is out of range 0 to 2147483647. ``` So my question is: what is the correct way to cast this, and why is there any difference between the three architectures posted above?
2015/11/12
[ "https://Stackoverflow.com/questions/33677920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3938428/" ]
Funnily enough, this might actually be a grey area in the specification of the VHDL language itself. The same problematic conversion has been [discussed as a possible "bug"](https://sourceforge.net/p/ghdl-updates/tickets/102/) against the open-source simulator, [ghdl.](https://sourceforge.net/projects/ghdl-updates/) The essence of the problem is that `input` is declared as `sfixed(0 downto -7)` while the definition of `std_logic_vector` requires its index to be `natural`, i.e. a positive integer or 0. Thus a type conversion to an unconstrained std\_logic\_vector ``` output <= std_logic_vector(input); ``` inherits the bounds of the source vector, (0 and -7) and fails because one bound is out of range. There is a simple workaround, however : type conversion to a *constrained* std\_logic\_vector ... such as `std_logic_vector (input'length-1 downto 0)` ... which by using the `'length` attribute is guaranteed to be the right size. The semantics of this conversion keep the indexes valid, so the conversion succeeds, transferring leftmost bit to leftmost bit, and so on. In a bit more detail, the code looks like: ``` -- declarations subtype result_type is std_logic_vector (input'length-1 downto 0); signal output : result_type; -- assignment output <= result_type (arg); ``` I cannot guarantee Altera will accept the same workaround, but I'm reasonably confident that it will, it's more clearly valid VHDL. I also haven't tried declaring `output` as a port as you need. As far as we can tell, ghdl (which is usually rigorous in its interpretation of VHDL) is correct in rejecting this construct according to the letter of the VHDL language reference manual (LRM) and the "bug" report has accordingly been closed. However, further clarification has been sought from the VHDL standards committee - and possibly a future relaxation of the rule - IF - it can be shown to be completely proof against the sort of array bounds errors and buffer overruns that plague some other languages.
The fixed package conversion function is not the solution to the OP's reported error, see posting of the function to convert to std\_ulogic\_vector below. Note that 'result' is a std\_ulogic\_vector and is obtained by performing a type cast of the operand 'arg', exactly the same as the OP did (except OP used std\_logic\_vector). The fixed point package will produce the same error as reported by the OP. ``` -- Conversion functions. These are needed for synthesis where typically -- the only input and output type is a std_logic_vector. function to_sulv ( arg : UNRESOLVED_ufixed) -- fixed point vector return STD_ULOGIC_VECTOR is variable result : STD_ULOGIC_VECTOR (arg'length-1 downto 0); begin if arg'length < 1 then return NSLV; end if; result := STD_ULOGIC_VECTOR (arg); return result; end function to_sulv; ``` KJ
57,181,002
I'm working on an input mask for a little software tool. Therefore I have different possibilities to allow the user to give his input (input types). Also I have a select field for choosing an answer out of a given sort order. These answers are read from a table of my database. It is dynamic. After the user selected all the necessary input, he can update the values in the table by clicking on a submit button (with a formula). After this clicking process, the values in the database get updated via SQL, read again and given out. So with no problem the user can see instantly his changes. My aim is to show the updated values in the input fields, so the user can see them. And this is also no problem. But not at the select box. It would be perfect, if the last selected option in the select box would be declared as the selected option. And now my question is: Is it possible to declare a option as selected on a dynamic list in a select box? ``` <div class="select"> <select name="strategy"> <?php $resultSet=$conn->query("SELECT test_strategy FROM strategies"); while ($rows = $resultSet->fetch_assoc()){ $strategy = $rows['test_strategy']; echo "<option id='option' value='$strategy'>$strategy</option>"; } ?> </select> </div> ```
2019/07/24
[ "https://Stackoverflow.com/questions/57181002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11801841/" ]
You can use `$casts` property (<https://laravel.com/docs/5.8/eloquent-mutators#array-and-json-casting>): ``` class User extends Model { protected $casts = [ 'user_preferences' => 'array', ]; } ``` By doing this, Laravel will automatically serialize array to JSON and vice versa.
I think the easiest solution is to store your value in [JSON](https://www.json.org/json-en.html). There is a php function that allows you to encode and decode objects and arrays to JSON, namely [json\_encode](https://www.php.net/manual/de/function.json-encode.php) and [json\_decode](https://www.php.net/manual/de/function.json-decode.php) respectively. In your case, you could simply change your update statement to: ```php $user->where('id', $user->id)->update( [ 'first_name' => $request->first_name, 'last_name' => $request->last_name, 'email' => $request->email, 'city' => $request->city, 'type' => $request->type, 'user_preferences' => json_encode($request->userPreferences), 'updated_at' => Carbon::now() ] ); ``` When you get your data from the model, you need to decode the string back to an array. You can do that like this: ```php $user = User::find($user->id); if ($user) { $preferences = json_decode($user->user_preferences); } ``` As the other answers here stated, Laravel can automate this for you with [Array & JSON Casting](https://laravel.com/docs/5.8/eloquent-mutators#array-and-json-casting)
2,351,425
I want to merge to very diverged Git branches together. That will be a lot of work because they have several hundreds conflicts. What would be the best way, so that maybe also others can help me and also work on this merge? Normally, I am doing just the 'git merge ...' and then going through all conflicts, resolving them, then do the commit. But that is local only then. The work on the conflict-resolving maybe can take several days. I want to put my changes online already while I am working on it.
2010/02/28
[ "https://Stackoverflow.com/questions/2351425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133374/" ]
Chances are, you do not have a formal data source, such as a back-end database. For situations like this, use the .NET [application settings architecture](http://msdn.microsoft.com/en-us/library/8eyb2ct1.aspx) to save and restore application settings between runs.
public partial class Form1 { public string defaultValue; ``` private void form2Open_Click(object sender, EventArgs e) { Form2 f = new Form2(); if (defaultValue != null) f.textBox1.Text = defaultValue; f.mainForm = this; f.Show(); } ``` } public partial class Form2 { public Form1 mainForm; private void Form2\_Closing(object sender, DontRememberWhatItsCalledEventArgs e) { mainForm.defaultValue = textBox1.Text; } }
45,432,120
Initially I had various **XSD** definition for each **XSD** I had set of XML files stored. After some time duration there are some changes in **XSD** definition so my stored XML is no more validation again new **XSD**. For support I need to write **XSLT** and do changes in my stored XML to validate again new **XSD**. Now, in this scenario each time **XSD** change, I need to write **XSLT** manually how can I generate this **XSLT** dynamically. Currently I am able compare old and new **XSD** and get the list what is changes using **Microsoft.XmlDiffPatch** DLL. Based on this changes I need to generate **XSLT** using C#.
2017/08/01
[ "https://Stackoverflow.com/questions/45432120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8391924/" ]
It looks like `Class1` is not the only class that has a `static void Main()` method defined. Usually, when you create a console application, there's a class called "Program" that already contains a method `Main`. There should be no need to add another class. Just modify the existing `Main` method. This should solve the second error. The `Main` method is a bit like the [Highlander](https://en.wikipedia.org/wiki/Highlander_(franchise)) of methods - there can only be one. As for the first error: You do need to target the Windows platform to be able to use `Console`, so you need to create a Console application or a Windows Forms/WPF application or the like.
The first error is caused by a typo. To correct it, change `Writeline` to `WriteLine` (with a capital letter L). The second error is caused by the fact that you did not specify clearly which entry point the program should use. To fix this, follow these steps: Right-click on your project in **Solution Explorer**, and open the "Properties" menu. You will see the similar page and all that you should do is explicitly select entry-point. [![Enter image description here](https://i.stack.imgur.com/Qcr20.png)](https://i.stack.imgur.com/Qcr20.png)
3,127,088
I am querying a firebird database with a relatively complicated query that takes a while to execute and thought that it would be helpful if the user could get some form of feedback regarding the progress of the query. I intend to display a suitable 'please wait' message on a status bar when the query is started and clear the status bar when the query returns its data. I am using a TSQLDataSet, TDataSetProvider and TClientDataSet; which event will fire in which component to say that the query has finished and that the data is ready to be displayed? TIA, No'am
2010/06/27
[ "https://Stackoverflow.com/questions/3127088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/162502/" ]
In retrospect, I'm sorry I posted this question as the answer was remarkably easy and has nothing to do with events. Here is my simple solution. ``` statusbar1.simpletext:= 'Opening query'; qComplicated.open; statusbar1.simpletext:= ''; ``` When the query returns with its data, program control moves to the statement after the query open, which clears the statusbar. I apologise to those who answered.
Since this is UI related (showing a message), I would probably use the TClientDataSet's AfterOpen event.
74,131,585
Found this question by @CarstenWE but it had been closed with no answer: [How to get classification report from the confusion matrix?](https://stackoverflow.com/questions/73308803/how-to-get-classification-report-from-the-confusion-matrix) As the question is closed, I opened this question to provide an answer. The questions linked to the original all have answers to compute precision, recall, and f1-score. However, none seems to use the `classification_report` as the original question asked.
2022/10/19
[ "https://Stackoverflow.com/questions/74131585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3168934/" ]
This is how I solved it! ``` deliver( app_identifier: '{{YOUR_APP_ID}}', submit_for_review: false, skip_screenshots: true, force: true, itc_provider: "{{YOUR_TEAM_ID}}" // <- added! ) ```
For me adding the environment variable works perfectly: ``` ITMSTRANSPORTER_FORCE_ITMS_PACKAGE_UPLOAD: true ``` For my case, here is an example of Azure DevOps pipelines: ```yaml - task: AppStoreRelease@1 env: ITMSTRANSPORTER_FORCE_ITMS_PACKAGE_UPLOAD: true ... ``` Source [Fastlane GitHub issue](https://github.com/fastlane/fastlane/issues/20756)
15,778,947
How does the Aggregation Framework's `$max` operator evaluate on a compound key. For example: ``` { $project: { user: 1, record: { date: "$upload_date", comment: 1, some_integer: 1 } } }, { $group: { _id: "$user", latest: { $max : "$record" } } } ``` Will it get the maximum by `date`, `comment`, or by `some_integer`? I just assumed it will get the latest by `date`. If it's wrong, what is the correct way of finding the maximum by `date`? **Edit** From what I have tried so far, the latest record is determined by the first key. Is this the correct behavior? **Edit** To give an idea of my use case, I have the following document: ``` > db.logs.findOne() { 'id': ObjectId("50ad8d451d41c8fc58000003") 'name': 'Sample Log 1', 'uploaded_at': ISODate("2013-03-14T01:00:00+01:00"), 'case_id': '50ad8d451d41c8fc58000099', 'result': 'passing' 'tag': ['TAG-XYZ'] } ``` And I have the following aggregation: ``` db.test_case_logs.aggregate( {$project: {tag:'$tag', case:'$case_id', latest: {upload_date:1, date:'$upload_date', result:'$result', passing : { $cond : [ { $eq : ["$result","passing"] }, 1, 0 ] }, failing : { $cond : [ { $eq : ["$result","failing"] }, 1, 0 ] }} }}, {$unwind: '$tag'}, {$group: {_id:{tag:'$tag',case:'$case'}, latest:{$max:'$latest'}}}, {$group: {_id:'$_id.tag',total:{$sum:1}, passing:{$sum:{$latest.passing}}, failing:{$sum:{$latest.failing}, date:{$max:{$latest.upload_date}}} }, {'$sort': {'date':-1}} ) ``` Logs can have the same name `tag` and `case_id` and after grouping twice, I need the result to be only the latest logs by `upload_date` for each `tag`. **Edit** My expected result is something like: ``` { '_id':'TAG-XYZ', 'total':'1' 'passing':'1' 'failing':'0' } ``` Each count corresponds to the latest log of a given case.
2013/04/03
[ "https://Stackoverflow.com/questions/15778947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1847471/" ]
Replacing the Highchart with 3.0 works for me..Sebastian Bochan also answered same thing
Replace the jQuery 1.8.2 with jQuery 1.4.2
33,335,471
I'm trying to set up a basic Titan example. In following the docs, I tried running `bin/gremlin-server.sh -i com.thinkaurelius.titan titan-all 1.0.0` which throws; ``` Could not install the dependency: java.io.FileNotFoundException: /usr/share/titan/ext/titan-all/plugin/titan-all-1.0.0.jar (No such file or directory) java.lang.RuntimeException: java.io.FileNotFoundException: /usr/share/titan/ext/titan-all/plugin/titan-all-1.0.0.jar (No such file or directory) at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215) at org.apache.tinkerpop.gremlin.groovy.util.DependencyGrabber.getAdditionalDependencies(DependencyGrabber.groovy:165) at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215) at org.apache.tinkerpop.gremlin.groovy.util.DependencyGrabber.copyDependenciesToPath(DependencyGrabber.groovy:99) at org.apache.tinkerpop.gremlin.server.util.GremlinServerInstall.main(GremlinServerInstall.java:38) Caused by: java.io.FileNotFoundException: /usr/share/titan/ext/titan-all/plugin/titan-all-1.0.0.jar (No such file or directory) at java.util.zip.ZipFile.open(Native Method) at java.util.zip.ZipFile.<init>(ZipFile.java:219) at java.util.zip.ZipFile.<init>(ZipFile.java:149) at java.util.jar.JarFile.<init>(JarFile.java:166) at java.util.jar.JarFile.<init>(JarFile.java:130) at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215) at org.apache.tinkerpop.gremlin.groovy.util.DependencyGrabber.getAdditionalDependencies(DependencyGrabber.groovy:148) ... 3 more ``` I also tried it from gremlin.sh; ``` root@ubuntu:/usr/share/titan# bin/gremlin.sh \,,,/ (o o) -----oOOo-(3)-oOOo----- plugin activated: aurelius.titan plugin activated: tinkerpop.server plugin activated: tinkerpop.utilities SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:/usr/share/titan/lib/slf4j-log4j12-1.7.5.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: Found binding in [jar:file:/usr/share/titan/lib/logback-classic-1.1.2.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation. SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory] 14:45:44 INFO org.apache.tinkerpop.gremlin.hadoop.structure.HadoopGraph - HADOOP_GREMLIN_LIBS is set to: /usr/share/titan/lib plugin activated: tinkerpop.hadoop plugin activated: tinkerpop.tinkergraph gremlin> :install com.thinkaurelius.titan titan-all 1.0.0 ==>java.io.FileNotFoundException: /usr/share/titan/ext/titan-all/plugin/titan-all-1.0.0.jar (No such file or directory) gremlin> ``` I've confirmed that groovy has the file; ``` root@ubuntu:/usr/share/titan# ls ~/.groovy/grapes/com.thinkaurelius.titan/titan-all/jars titan-all-1.0.0.jar ``` So now I'm stumped.. Has anyone come across this before? **EDIT: Some notes on how I got here..** My first attempt at getting this working was to use the all-inclusive zip file as per the docs... I changed gremlin-server.yaml to; ``` graph: conf/titan-cassandra-es.properties ``` That threw; ``` 407 [main] WARN org.apache.tinkerpop.gremlin.server.GremlinServer - Graph [graph] configured at [conf/titan-cassandra-es.properties] could not be instantiated and will not be available in Gremlin Server. GraphFactory message: Configuration must contain a valid 'gremlin.graph' setting java.lang.RuntimeException: Configuration must contain a valid 'gremlin.graph' setting ``` Ok, simple google search tells me I need to add this to conf/titan-cassandra-es.properties; ``` gremlin.graph=com.thinkaurelius.titan.core.TitanFactory ``` At which point, I get.. ``` 484 [main] WARN org.apache.tinkerpop.gremlin.server.GremlinServer - Graph [graph] configured at [conf/titan-cassandra-es.properties] could not be instantiated and will not be available in Gremlin Server. GraphFactory message: GraphFactory could not instantiate this Graph implementation [class com.thinkaurelius.titan.core.TitanFactory] java.lang.RuntimeException: GraphFactory could not instantiate this Graph implementation [class com.thinkaurelius.titan.core.TitanFactory] ``` This leads me to believe that I'm missing `com.thinkaurelius.titan.core.TitanFactory`. Which is curious, since $TITAN\_HOME/lib does in fact contain titan-all-1.0.0.jar. So I assumed (perhaps wrongly) that I need to run the titan-all install to make it actually load the jars..
2015/10/25
[ "https://Stackoverflow.com/questions/33335471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/998101/" ]
The basic install for Titan is unzip the titan-1.0.0-hadoop1.zip. That is it! Download it from <http://titandb.io> <http://s3.thinkaurelius.com/docs/titan/1.0.0/getting-started.html> It is already packaged with the Titan plugins, so you don't need to install them into the Gremlin Console or Gremlin Server. If you want to try the Titan Server, there is a pre-packaged `titan.sh` script which automatically starts Cassandra and Elasticsearch with the server. <http://s3.thinkaurelius.com/docs/titan/1.0.0/server.html#_getting_started>
For anyone that comes across this strangeness, read the whole stack trace. It turns out waaay at the bottom, it actually had the real issue; it couldn't connect to Cassandra because I had not enabled Thrift.
169,198
I have a script as below: ``` #!/bin/bash df -k | tr -s " " "," | awk 'BEGIN {FS=","} {print $1,$5}'|sed 1d > file1.txt while read partition percentUsed do if [ $percentUsed > 75 ] then echo Partition: ${partition} space is ${percentUsed} else echo Pration: $partition: OK!! fi done < file1.txt ``` The script is executing properly, however, it is creating a zero byte file by the name 75. Any ideas why this is happening? ``` $ sh diskUsed.sh Partition: C:/Users/Public/Documents/CYGWIN/bin space is 75% Partition: C:/Users/Public/Documents/CYGWIN/lib space is 75% Partition: C:/Users/Public/Documents/CYGWIN space is 75% Partition: C: space is 75% Partition: H: space is 91% $ ls -lrt total 2 -rwxrwxrwx 1 diwvibh Domain Users 284 Nov 21 04:17 diskUsed.sh -rw-r--r-- 1 diwvibh Domain Users 133 Nov 21 04:29 file1.txt -rw-r--r-- 1 diwvibh Domain Users 0 Nov 21 04:29 75 ```
2014/11/21
[ "https://unix.stackexchange.com/questions/169198", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/80040/" ]
In line 5 you write the contents of $percentUsed to file "75". Instead, try `if [ ``echo $percentUsed | sed 's/%//'`` -gt 75 ]` which should do what you desire. At least with bash 4.2.25 on Linux it works. Note: Please only use one backtick instead of two shown here - that's because the Stackexchange web platform interprets those backticks.
This is one efficient way to calculate the disk space. In this example, I am using the `/home` dir. ``` #!/bin/bash { read -r; read -rd '' -a disk_usage; } < <(LC_ALL=C df -Pk "/home"; printf \\0) percent=$(echo "${disk_usage[4]}" | awk '{print $0+0}') if (( percent > 75 )); then echo "Disk is critical"; else echo "Disk space is OK"; fi ``` As a side note, The command you have there which is ``` df -k | tr -s " " "," | awk 'BEGIN {FS=","} {print $1,$5}'|sed 1d ``` Is very inefficient since it forks a lot of processes like `tr`, `awk`, `sed`. You can do this in one go. Remove the `+0` at the end if you want to see the `%` sign. ``` df -k | awk 'NR>1{print $1,$(NF-1)+0}' ```
45,654,051
What I am trying to accomplish is when a user clicks on a button, such as "Sign In", I fire my action which sets my state in my app state reducer to `loading:true` and the loading screen pops up. I would like to have that functionality across my screens just by setting my show loading state to true via an action. I do not know if it would be wrong or not to have the navigator in my reducer and have it fire a navigation even after setting my state. I feel like my reducer should handle my state and nothing else. Should it be in my action file? At this point of my app, everything works... all the console logins fires at the right time. I am just not sure where I should fire the [show lightbox event](https://wix.github.io/react-native-navigation/#/screen-api?id=showlightboxparams-) in a way that I can use on multiple screens. ### thank you for looking! ### package.json ``` "dependencies": { "axios": "^0.16.2", "date-fns": "^1.28.5", "lodash": "^4.17.4", "native-base": "^2.3.0", "react": "16.0.0-alpha.12", "react-native": "0.46.4", "react-native-navigation": "^1.1.143", "react-native-vector-icons": "^4.2.0", "react-redux": "^5.0.5", "redux": "^3.7.2", "redux-persist": "^4.8.2", "redux-thunk": "^2.2.0" }, "devDependencies": { "babel-jest": "20.0.3", "babel-preset-react-native": "2.1.0", "jest": "20.0.4", "react-test-renderer": "16.0.0-alpha.12" }, ``` ### actions/appStateActions.js ``` import { APP_LOADING_SCREEN, APP_LOADING_BUTTON } from './actionTypes'; export const showLoadingScreen = () => async dispatch => { console.log("this is loading screen action"); dispatch({ type: APP_LOADING_SCREEN, payload: true }); } export const showLoadingButton = () => async dispatch => { console.log("this is loading button action"); dispatch({ type: APP_LOADING_BUTTON, payload: true }); } ``` ### reducers/appStateReducer ``` import{ APP_LOADING_SCREEN, APP_LOADING_BUTTON } from '../actions/actionTypes'; const INITIAL_STATE = { isLoadingScreenVisible: false, isLoadingButtonVisible: false }; export default function(state = INITIAL_STATE, action) { switch (action.type){ case APP_LOADING_SCREEN: return { ...state, ...INITIAL_STATE, isLoadingScreenVisible: action.payload }; case APP_LOADING_BUTTON: return { ...state, ...INITIAL_STATE, isLoadingButtonVisible: action.payload }; default: return state; } } ``` my login screen is complete, albeit without a loading indicator but I have posted only part of it below ``` loginSubmit(){ this.props.showLoadingScreen(); } <TouchableOpacity activeOpacity={1.5} onPress={() => this.loginSubmit() }> <View style={styles.button} <Text style={styles.buttonText}>Sign In</Text> </View> </TouchableOpacity> const mapStateToProps = ({ auth }) => { const { locationDisplay, locationValue, serviceUrl } = auth; return { locationDisplay, locationValue, serviceUrl }; }; export default connect(mapStateToProps, {loginUser, showLoadingScreen})(LoginScreen); ```
2017/08/12
[ "https://Stackoverflow.com/questions/45654051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1361375/" ]
Use `error` event attached to `<link>` and, or `<script>` element, see [Is there a way to know if a link/script is still pending or has it failed](https://stackoverflow.com/questions/39824927/is-there-a-way-to-know-if-a-link-script-is-still-pending-or-has-it-failed/39908873?s=1|0.1926#39908873)
For checking `css` file exist or not, Just check if a `<link>` element exists with the `href` attribute set to your CSS file's URL: ``` if (!$("link[href='/path/to.css']").length){ // css file not exist } ``` and for `js` ``` if (!$("script[src='/path/to.js']").length){ // js file not exist } ```
31,309,494
I have a requirement where i have to populate drop down with list of all the weeks in a particular year as shown in the image ![enter image description here](https://i.stack.imgur.com/jjSZs.png) How can i achieve the list dynamically depending on the year using jquery or Rails?
2015/07/09
[ "https://Stackoverflow.com/questions/31309494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1273282/" ]
``` start_date = Date.current.beginning_of_year end_date = Date.current.end_of_year weeks = [] (start_date..end_date).to_a.in_groups_of(7).each do |range| weeks << "#{range.first} to #{range.last}" end ```
This might help you: ``` date1 = Date.today.beginning_of_year date2 = Date.today.end_of_year weeks = [] while date2>date1 do weeks << [date1.beginning_of_week, date1.end_of_week] date1=date1+7.days end ``` You can also format date as per your requirement before pushing it to array.
49,665,461
I am trying to read a .txt file into two different arrays one 1d string array and one 2d int array. The code reads the names into the NamesArray just fine. However, the code seems to either only read the first column of numbers in or only outputs the first column. I'm not sure where I'm going wrong with the code. Any help is greatly appreciated! The data below is how it is formatted in the file. ``` Jason 10 15 20 25 18 20 26 Samantha 15 18 29 16 26 20 23 Ravi 20 26 18 29 10 12 20 Sheila 17 20 15 26 18 25 12 Ankit 16 8 28 20 11 25 21 ``` Here is the code that I have so far. ``` import java.io.*; import java.util.*; public class Page636Exercise12 { // static Scanner console = new Scanner(System.in); public static void main(String[] args) throws FileNotFoundException, IOException { int Count = 0; String[] NamesArray = new String[5]; int [][] MileageArray = new int [5][7]; int Mileage = 0; String Names = ""; //Open the input file. Scanner inFile = new Scanner(new FileReader("Ch9_Ex12Data.txt")); //Reads from file into NamesArray and MileageArray. while (inFile.hasNext()) { Names = inFile.next(); NamesArray[Count] = Names; Mileage = inFile.nextInt(); MileageArray[Count][Count] = Mileage; Names = inFile.nextLine(); System.out.println(NamesArray[Count] + " " + MileageArray[Count][Count]); Count++; inFile.close(); } } ``` Here is what I get for the output. ``` Jason 10 Samantha 15 Ravi 20 Sheila 17 Ankit 16 ```
2018/04/05
[ "https://Stackoverflow.com/questions/49665461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9599452/" ]
The problem is that you are only storing one number in the `MileageArray` at index `[count][count]`. You will need to populate the array with a loop that loops for the total number of integer tokens expected like so: ``` for(int j = 0; j < 7; j++){ Mileage = inFile.nextInt(); MileageArray[Count][j] = Mileage; } Names = inFile.nextLine(); ``` I'd also suggest that you specify the `MileageArray` column and row size as constants. i.e.: ``` final int ROWS = 5; final int COLS = 7; ``` This will allow you to update your parsing code in a more configurable way if the input file format changes.
The answer is simple, what you do by invoking `Mileage = inFile.nextInt()` you get the next token of the input line you are currently at and parse it to an `int` but since the numbers are delimited by something (assumed a whitespace) only the first number is read and parsed. You have multiple options to fix this. You can either: **Solution 1** [Sparkplug were quicker than me.](https://stackoverflow.com/a/49665661/8181750) **Solution 2** ``` try (BufferedReader br = new BufferedReader( new FileReader( new File( "Performance_Results_310_13.dat" ) ) )) { String line; while ( (line = br.readLine()) != null ) { // split everything in a temporary array String[] temp = line.split( "\\s" ); // the name will always at the first position rest of the line are the numbers name = temp[ 0 ]; nameArray[ count ] = name; // or just simply nameArray[count] = temp[0] // start at 1 since 0 is the name for ( int i = 1; i < temp.length - 1; i++ ) { // create a new array which is big enough for all numbers following mileageArray[count] = new int[temp.length - 1]; mileageArray[ count ][ i - 1 ] = Integer.parseInt( temp[ i ] ); } count++; } } catch ( IOException e ) { e.printStackTrace(); } ``` This solution reads the entire line and then parses it into the desired format. It is a bit more flexible in my opinion but you must assure that the arrays are big enough to store the data. Also note that this solution does only work if every token after a whitespace is parsable to an `int` except for the first one.
5,391,394
I would like to enter the values in a range like 1-60. The `EditText` shouldn't accept values like 61,62..., or 0,-1,-2... How can we give the range 1-60 to `EditText` in android? I have done in main.xml as ``` <EditText android:layout_height="wrap_content" android:id="@+id/editText1" android:layout_width="160dip" android:inputType="number"> </EditText> ```
2011/03/22
[ "https://Stackoverflow.com/questions/5391394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769225/" ]
I fixed Daniel Wilson's solution: ``` public class InputFilterMinMax implements InputFilter { private int min, max; public InputFilterMinMax(int min, int max) { this.min = min; this.max = max; } public InputFilterMinMax(String min, String max) { this.min = Integer.parseInt(min); this.max = Integer.parseInt(max); } @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { try { //The commented line below only works if you append/modify the end of the text (not the beginning or middle) //int input = Integer.parseInt(dest.toString() + source.toString()); //corrected solution below (3lines) CharSequence part1 = dest.subSequence(0, dstart); CharSequence part2 = dest.subSequence(dend, dest.length()); int input = Integer.parseInt(part1 + source.toString() + part2); if (isInRange(min, max, input)) return null; } catch (NumberFormatException nfe) { } return ""; } private boolean isInRange(int a, int b, int c) { return b > a ? c >= a && c <= b : c >= b && c <= a; } } ``` Finally add the InputFilter to your EditText control: ``` mCentsEditText = (EditText)findViewById(R.id.cents_edit_text); InputFilterMinMax filter = new InputFilterMinMax("1", "60") {}; mCentsEditText.setFilters(new InputFilter[]{filter}); ```
Why not use a Seekbar Instead of EditText? That way, only numbers can be entered and the maximum limit can be specified/modified as and when you need. ``` public class SeekBar1 extends Activity implements SeekBar.OnSeekBarChangeListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); .. mSeekBar = (SeekBar)findViewById(R.id.seekBar); mSeekBar.setOnSeekBarChangeListener(this); .. } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) { //Do your Changes Here } public void onStartTrackingTouch(SeekBar seekBar) { //On First Track Touch } public void onStopTrackingTouch(SeekBar seekBar) { //On Stop Track Touch } } ``` For numerical Input type values, Seekbar is the best possible UI. Although, the precision on it is questionable.
12,148,729
Is there a way to echo a variable that is already echoing something, I try doing it this way but its not echoing it out ``` if (logged_in() === true) { echo ' <li ><a href="#">',$user_data['username'],'</a> <ul> <li><a href="../social.php">socail</a></li> <li><a href="../my/pictures.php">my pictures</a></li> <li><a href="../profile.php">profile</a></li> <li><a href="../logout.php">logout</a></li> </ul> '; } else { include'cpages/cmain/menuforms/formsmenu.php'; } ```
2012/08/27
[ "https://Stackoverflow.com/questions/12148729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1610606/" ]
Do you mean concatenation? ``` <li ><a href="#">' . $user_data['username'] . '</a> ```
You're concatenating the string wrong, you should use dots: **EDIT** After some googling I found out that it is apparently OK to concatenate with commas also, I did not know that... ``` echo "text".$variable."text".$variable2; //and so on. ``` **EDIT 2** Apparently echo can take multiple parameters, which is what happens when you pass in values by separating them with commas. And then it isn't really string concatenation, user ACJ pointed that one out. I would however still go with the HEREDOC in this case or concatenate the string, probably to a variable and then echo it out. Something to look for is that you escape double and single quotes correctly, this is a common problem when working with long strings, especially strings containing html. Also you might want to check out Heredoc: ``` $variable = <<<EOT Place your multiline string here and dont forget to end it with the same as you started it. EOT; //Must not be indented ``` You should check out this question also: [Best practices working with long strings in PHP](https://stackoverflow.com/questions/1848945/best-practices-working-with-long-multiline-strings-in-php) Okay so to actually get to your problem, assuming that you've checked to see that logged\_in() really evaluates to `true`, then the only problem i can think of is that $user\_data does not contain a key named `username`. I'd start with enabling error\_reporting by calling the following at the top of your file: ``` error_reporting(E_ALL | E_STRICT) //reports all errors. ``` And then you should get a pretty quick answer to what is wrong with your code, because it runs just fine on my computer.
16,747,056
I have two tables: posts and comment. One post has many comments. Often I want to retrieve all posts along with any comment they may have. I do this with a left join as shown: ``` select p.post_id, p.content_status, p.post_title, c.comment_id, c.content_status as comment_status from post p left join comment c on p.post_id = c.post ``` Now I want to exclude any posts or comments where the status is not 'Approved'. I can constrain the post table no problems, and still return posts that have no comments. As soon as I constrain the comments table though, I no longer retrieve posts that have no comments. Here's the offending query: ``` select p.post_id, p.content_status, p.post_title, c.comment_id, c.content_status as comment_status from post p left join comment c on p.post_id = c.post where p.content_status = 'Approved' and c.content_status = 'Approved' ```
2013/05/25
[ "https://Stackoverflow.com/questions/16747056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/356282/" ]
Just move the condition on the right-hand table into the `ON` clause. Any condition in the `WHERE` clause will remove rows entirely, while conditions in the `ON` clause will - as you want - not remove the row but just prevent a match. ``` SELECT p.post_id, p.content_status, p.post_title, c.comment_id, c.content_status AS comment_status FROM post p LEFT JOIN comment c ON p.post_id = c.post AND c.content_status = 'Approved' WHERE p.content_status = 'Approved' ``` [An SQLfiddle, courtesy of @hims056](http://sqlfiddle.com/#!2/590ac/3).
Move the condition on the left-joined table into the join condition: ``` select p.post_id, p.content_status, p.post_title, c.comment_id, c.content_status as comment_status from post p left join comment c on p.post_id = c.post and c.content_status = 'Approved' where p.content_status = 'Approved' ``` It seems to be a little known fact that the ON clause of a JOIN may contain non-key related conditions.