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
418,651
I want to redirect specific page to another page. This means that requests for any other page on foo.com will function like normal, but if bar.html is requested =, it redirects to bar.com/foo.html. This is pretty much the same problem as here [Redirect specific url requests to local site](https://superuser.com/questions/193564/redirect-specific-url-requests-to-local-site) except it seemed no one had a solution for what I'm asking here. I'm also looking for an OS-wide solution.
2012/04/30
[ "https://superuser.com/questions/418651", "https://superuser.com", "https://superuser.com/users/22902/" ]
What you're looking for is a proxy server that will rewrite the url. [Fiddler](http://www.fiddler2.com/fiddler2/) is the only one I can think of at the moment.
The simplest solution that does not even require server configuration, is to include the 'meta' HTML tag in the first page's header. And set the url attribute of the second page like so: ``` bar.html : ... <head> <meta http-equiv="Refresh" content="0;url=http://bar.com/foo.html" /> </head> ... ```
580,202
I am currently looking to make my own collection, which would be just like a regular list, except that it would only hold 10 items. If an item was added when there were already 10 items in the list, then the first item would be removed before the new item was appended. What I want to do is create a class that extends `System.Collections.Generic.List<T>`, and then modifies the `Add(T item)` method to include the functionality which removes the first item if necessary.
2009/02/24
[ "https://Stackoverflow.com/questions/580202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/68512/" ]
Your description of your requirement sounds like a [Circular Buffer](http://en.wikipedia.org/wiki/Circular_buffer). I implemented my own - similar to [this implementation on CodePlex](http://circularbuffer.codeplex.com/releases/view/27751#DownloadId=69221) except that mine implements `IList<T>`. Some of the other answers suggest using a `Queue<T>` - but this isn't quite the same thing, as it only allows FIFO access. As a general point, it's not recommended to derive from `List<T>` - instead derive from `Collection<T>`, and implement any additional stuff you need. But for a circular buffer it's probably more appropriate to use a private array rather than deriving from `Collection<T>` like the CodePlex implementation.
You could take a look at the C5 collection library. They have an ArrayList<T> that implements IList<T> and have a virtual Add method. The C5 collection library is an awesome collection of lists, queues, stacks etc... You can find the C5 library here: <http://www.itu.dk/research/c5/>
14,972,964
I have a class Event and a subclass ServerEvent, however the Event class is only an interface for ServerEvent to extend/inherit from. When I run make an Event.o isn't generated and I get an error that it doesn't exist. What's the right way to compile this interface and what to add in the makefile? Also, the reason I have a protected constructor is so that Event can't be instantiated. I couldn't use a virtual constructor - what is the normal way to go about inheritance? EDIT: including the makefile, ServerEvent.cpp and compile error now Event.h ``` #ifndef EVENT_H #define EVENT_H #include <string> #define EVENT_STOP 0 #define EVENT_START 1 class Event { private: protected: double time; std::string label; int type; // EVENT_START OR EVENT_STOP Event(); public: }; #endif ``` ServerEvent.h ``` #ifndef SERVEREVENT_H #define SERVEREVENT_H #include "Event.h" #include <vector> class ServerEvent: public Event { private: public: ServerEvent(std::vector<std::string> tokens); }; #endif ``` ServerEvent.cpp ``` #include "Event.h" #include "ServerEvent.h" #include <cstdlib> #include <sstream> ServerEvent::ServerEvent(std::vector<std::string> tokens) { std::stringstream stream(tokens[0]); stream >> time; } ``` makefile ``` OBJ = correngine.o CSVManager.o CorrelationEngineManager.o ServerEvent.o CC = g++ CFLAGS = -c -Wall -pedantic LFLAGS = -Wall -pedantic EXE = correngine correngine : $(OBJ) $(CC) $(LFLAGS) $(OBJ) -o $(EXE) correngine.o : correngine.cpp correngine.h CSVManager.h $(CC) $(CFLAGS) correngine.cpp CSVManager.o : CSVManager.cpp CSVManager.h $(CC) $(CFLAGS) CSVManager.cpp CorrelationEngineManager.o : CorrelationEngineManager.cpp CorrelationEngineManager.h Event.o $(CC) $(CFLAGS) CorrelationEngineManager.cpp Event.o : Event.h $(CC) $(CFLAGS) Event.h ServerEvent.o: ServerEvent.cpp ServerEvent.h Event.h $(CC) $(CFLAGS) ServerEvent.cpp clean : \rm *.o $(EXE) ``` compile error ``` ServerEvent.o: In function `ServerEvent::ServerEvent(std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >)': ServerEvent.cpp:(.text+0x11): undefined reference to `Event::Event()' ServerEvent.o: In function `ServerEvent::ServerEvent(std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >)': ServerEvent.cpp:(.text+0xe1): undefined reference to `Event::Event()' collect2: ld returned 1 exit status make: *** [correngine] Error 1 ```
2013/02/20
[ "https://Stackoverflow.com/questions/14972964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089851/" ]
1. This is a concrete base class, it has data members so it is not an 'interface'. An 'interface' class refers to a class with no data member and all member functions are pure virtual in a sense. 2. You #include the .h in a .cpp file and compile that .cpp file (but I don't see why you are going to do that, you must #include"Event.h" in the ServerEvent .cpp, right?) 3. Usually, to make an interface class inheriable but non-instantiable is to use pure virtual dtor, e.g. virtual ~Event() = 0; However, this doesn't apply to your case due to my point 0. Protected ctor is probably the right way for your case, but I have to say it doesn't look like an elegant (or right) design ...
As far as I know, you do not need the constructor. You need a virtual destructor, and any methods you need to implement need to be equal to 0 and virtual. Look here: [How do you declare an interface in C++?](https://stackoverflow.com/questions/318064/how-do-you-declare-an-interface-in-c "How do you declare an interface in C++")
356,528
I've read all the questions with similar titles but I couldn't find an answer. Suppose I'm rotating with my arms extended on a frictionless surface. I have angular momentum and energy: \begin{equation} L\_0=I\_0\ \omega\_0 \end{equation} \begin{equation} E\_0=\frac{1}{2}I\_0\ \omega\_0^{2} \end{equation} Where $I\_0$ is my moment of Inertia with my arms extended and $\omega\_0$ is my initial angular velocity. Suddenly, I decide to flex my arms to decrease my moment of Intertia. Then my angular momentum and energy are: \begin{equation} L\_f=I\_f\ \omega\_f \end{equation} \begin{equation} E\_f=\frac{1}{2}I\_f\ \omega\_F^{2} \end{equation} If I use conservation of energy to calculate final angular velocity I get: \begin{equation} \omega\_f = \sqrt{\frac{I\_0}{I\_f}}\omega\_0 \end{equation} But if I use conservation of angular momentum: \begin{equation} \omega\_f = \frac{I\_0}{I\_f}\omega\_0 \end{equation} Both can't be right... Is energy not conserved in this problem? why? **Edit:** Many anwers have pointed out that I'm actually doing work when I pull my arms back. Thanks for that clarification! What would happen if the system is a disk rotating with two persons in each side and they start walking towards the center? They walk using static frictional force which does not do work. Would energy be conserved then?
2017/09/10
[ "https://physics.stackexchange.com/questions/356528", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/130091/" ]
You do work on your arms as you pull them in, thus your energy has increased. The correct conserved quantity is angular momentum, as you deduce. The amount of work done on your arms can either be computed directly (force times distance type approach) or by using the solution from angular momentum (final energy minus initial energy type approach).
]You stand in a bus or train. You Don't hold any handle or grab bar. The train starts smoothly and accelerates. You accelerate too. Your velocity increases and so does your KE. What force did the work responsible for the change in your KE? Don't bother to include muscle forces. Same thing happens to your suitcase sitting next to you. And it has no muscles or tendons. So, your assumption that static friction cannot do work is not correct. There is nothing unusual to explain. If you walk towards the center of the disk without sliding laterally you have to slow down your motion so there is a tangential acceleration and so, a tangential force who does work. This force is (or may be) static friction.
2,093,908
I have the following array ``` [0] => Array ( [id] => 229 [val] => 2 ) [3] => Array ( [id] => 237 [val] => 1 ) [4] => Array ( [id] => 238 [val] => 6 ) ``` I need to sort this array according to the val values in the array, and do not know how to accomplish this?
2010/01/19
[ "https://Stackoverflow.com/questions/2093908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/131637/" ]
[array\_multisort](http://www.php.net/array_multisort) can help with this, example 3 presents a similar problem and solution.
This would help - <http://www.informit.com/articles/article.aspx?p=341245&seqNum=7>
22,419,467
Having trouble testing out the legacy basic auth api... I want to mature this into nodejs or php, for a blog interface, but I can't seem to get the cURL working properly. I believe I am following their [docs](https://developer.bigcommerce.com/api/stores/v2/blog/posts)... but who knows. ``` curl --request POST \ -H "Content-Type: application/json" \ -u "user:key" \ -d '{"title": "title", "content": "content"}' \ https://myteststoreurl.mybigcommerce.com/api/v2/blog/posts ``` I get an empty response when I attempt the following with my person info added in... When I run ``` curl --request GET \ -H "Content-Type: application/json" \ -u "user:key" \ https://myteststoreurl.mybigcommerce.com/api/v2/blog/posts ``` I get all current posts, correctly. But POST will not work. Also, when updating a post with PUT, it removes the post from the interface but does send the change which I can verify by running the get request. Any Bigcommerce experts to help out here??
2014/03/15
[ "https://Stackoverflow.com/questions/22419467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1842294/" ]
I believe you are doing this from windows and where single quote makes the problem. Change your `-d` values. ``` -d "{title\": \"title\", \"content\": \"content\"}" ``` Also add the `-v` parameter to see what is curl sending when you perform the request.
Try the same request with something like Advanced REST client (Chrome app) <https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo> If you are still getting the same error most likely it's a Bigcommerce API side issue. ![enter image description here](https://i.stack.imgur.com/Z1z3m.png)
77,650
I've heard the number 7% thrown around a bunch of times, but I am struggling to find reputable data to back it up. All I found was a quote from Warren Buffet that I couldn't find an original source for and data assembled by individuals on their personal websites. Is there something from an organization such as Market Watch making a statement about this? I'm hoping to specifically find what the 10 or 20 year return is for investing in the S&P 500 index fund or another diversified portfolio option.
2017/03/22
[ "https://money.stackexchange.com/questions/77650", "https://money.stackexchange.com", "https://money.stackexchange.com/users/49445/" ]
The oddly named [MoneyChimp](http://www.moneychimp.com/features/market_cagr.htm) offers a great look at the numbers for the S&P. [![enter image description here](https://i.stack.imgur.com/1C6rz.jpg)](https://i.stack.imgur.com/1C6rz.jpg) You can enter a date as early as 1871 and any ending date you wish. The last 100 years did, in fact, show a CAGR of 10.06%. Take off a bit, .05 - .10 for expenses if you want to see the return for an ETF or mutual fund.
First, your question is what a mathematician would call "ill-posed." Second, it doesn't matter unless it is for historical curiosity since you should be concerned with future returns rather than historical ones. It is ill-posed because investments include land, where returns are locally determined rather than nationally or internationally, and private investments alongside public ones. Second, returns would be gross of taxes. If people are intelligent, then they choose their investments, in part, based on their tax situation and so many investments would be irrelevant to you as their after-tax return for you would be poor, but good for someone else. On the flip side, returns are a function of interest rates and price to income. Interest rates are near enough to historic lows that non-bond investments can pay ridiculously low returns and be competitive. That was not the case across history. For example, you could purchase 18% per year bonds in the '70s and '80s. As a result, equity securities were discounted way way way below that level. The starting point matters. Had you invested in the Dow on January 1, 1929, reinvesting dividends, and a friend invested in 90 day bills on the same date, it would have taken until 1964 for you to break even with your friend. Within three years you would have shot past him or her by a huge amount, but you would have been worse off in the interim. Based on the current price to earnings ratio, for US stocks, as well as the dividend yield, and reasonable inflation expectations, my highly educated guess, based on decades of statistical research on the topic by me, is that forward returns before taxes will be six percent, or in that neighborhood. The personal finance pages do not allow for mathematical notation, so there isn't a simple way to justify it. Bonds rates could very well be representative of long term bond rates, but my guess is that rates will rise due to serious missteps being made by the Congress and the current president. If you are looking at real property investments, look at the purchase price to rental price ratio. Pittsburgh is among the best values and San Francisco among the worst. Price to income is what matters, and a lot of value gets sunk in land in the US. The question should be what return should I make from a particular price to income stream. The answer to that is to use standard time value of money discounting methods.
28,849,353
Need help to put some jquery function inside if statement . I want to hide my div when data from database is empty . I've done like this , and nothing happened. ``` <?php if(empty($all_data)){ ?> <script> $(document).ready(function () { $( '.table-wrapper').css("display","none"); }); </script> <===update <?php }else{ ?> <?php foreach($all_data->result() as $data){ ?> <tr> <td><?php echo $data->id_history;?></td> <td><?=$data->id_admin;?></td> <td><?=$data->ipc;?></td> <td><?=$data->task_date;?></td> <td><?=$data->task_time;?></td> <?php if ($data->id_task == 1){ ?> <td>Login Site</td> <?php }else{ ?> <td>Logout Site</td> <?php } ?> <td>-</td> </tr> <?php } ?> <?php } ?> ``` Is it possible to put some jquery inside php ??
2015/03/04
[ "https://Stackoverflow.com/questions/28849353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4258293/" ]
Nothing ever calls `hiding()`. So you conditionally *define* that function in PHP, but you never actually invoke it. If you want the contents of that function to execute in the `if` block then don't declare the `hiding()` function, just execute the code: ``` <?php if(empty($all_data)){ echo "<script> $(document).ready(function () { $( '.table-wrapper').hide(); }); </script>"; }else{ ?> ... ``` Or maybe remove the `echo` and just emit the output directly, might look a little cleaner: ``` <?php if(empty($all_data)){ ?> <script> $(document).ready(function () { $( '.table-wrapper').hide(); }); </script> <?php }else{ ?> ... ``` Though, if I'm being honest, hiding on document ready probably isn't the best approach. If `.table-wrapper` elements should be hidden when the page renders, conditionally style them as hidden (or don't emit them to the page at all if they're not supposed to be visible, depending on the dynamic functionality of the page). Emitting visible output and then hiding it could easily cause a poor user experience. Better to emit it as hidden in the first place or not emit it at all.
Well,delete the `function hiding(){}`.It's better to do this with php,like ``` <?php if(!empty($all_data)){ ?> <div class="table-wrapper"> <?php foreach($all_data->result() as $data){ ?> <tr> <td><?php echo $data->id_history;?></td> <td><?=$data->id_admin;?></td> <td><?=$data->ipc;?></td> <td><?=$data->task_date;?></td> <td><?=$data->task_time;?></td> <?php if ($data->id_task == 1){ ?> <td>Login Site</td> <?php }else{ ?> <td>Logout Site</td> <?php } ?> <td>-</td> </tr> <?php } ?> </div> <?php } ?> ```
21,322,007
I'm trying to write a shell script to parse values from grepped lines of a log: ``` <WhereIsTheCar - the car with id number 'Sys Generated. VARIABLESTRING 1111' is driving to: Canada> <WhereIsTheCar - the car with id number 'Sys Generated. VARIABLESTRING 2222' is driving to: Mexico> <WhereIsTheCar - no car could be found with the following ID number: 'Sys Generated. VARIABLESTRING 3333'> ``` I've already grepped for those lines and created an array. I'm then looking to get an output that's something like: ``` Canada Sys Generated. VARIABLESTRING 1111 Mexico Sys Generated. VARIABLESTRING 2222 Not Found Sys Generated. VARIABLESTRING 3333 ``` I'm admittedly not very good at shell scripting but I've figured out a somewhat 'brute force' approach to obtaining the values I want: ``` i=0 for line in "${grep[@]}" do loc[i]=`sed -e "s/.*\:\(.*\)>/\1/" <<< $line | sed -e "s/^[ \t]*//" -e "s/[ \t]*$//" -e "s/^\([\"']\)\(.*\)\1\$/\2/g"` echo ${loc[i]}; id[i]=`sed -e "s/^.*\'\(.*\)\'.*$/\1/" <<< $line | sed -e "s/^[ \t]*//" -e "s/[ \t]*$//" -e "s/^\([\"']\)\(.*\)\1\$/\2/g"` echo ${id[i]}; let i++ done ``` Where I'm creating a location and id array and then trying to trim off the whitespace and extra quotes. I think I can finish from here but I was wondering if someone had a more elegant (or better suited) approach. Any advice would be appreciated.
2014/01/24
[ "https://Stackoverflow.com/questions/21322007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/899166/" ]
Another possibility is just to use `BASH_REMATCH` in bash rather than `awk` or `sed` ``` BASH_REMATCH An array variable whose members are assigned by the =~ binary operator to the [[ conditional command. The element with index 0 is the portion of the string matching the entire regular expression. The element with index n is the portion of the string matching the nth parenthesized subexpression. This vari‐ able is read-only. ``` So this should work for you ``` #!/bin/bash while read -r line; do [[ $line =~ "is driving to:"(.*)">" ]] && echo ${BASH_REMATCH[1]} || echo "Not Found" [[ $line =~ \'(.*)\' ]] && echo -e "\t${BASH_REMATCH[1]}\n" done < "file" ``` Example output ``` > ./abovescript Canada Sys Generated. VARIABLESTRING 1111 Mexico Sys Generated. VARIABLESTRING 2222 Not Found Sys Generated. VARIABLESTRING 3333 ```
awk would make it easier: ``` awk -F"('|driving to: |>)" '{printf "%s\n\t%s\n\n", NF==5?$4:"Not Found",$2;next}' file ``` test with your data: ``` kent$ cat f <WhereIsTheCar - the car with id number 'Sys Generated. VARIABLESTRING 1111' is driving to: Canada> <WhereIsTheCar - the car with id number 'Sys Generated. VARIABLESTRING 2222' is driving to: Mexico> <WhereIsTheCar - no car could be found with the following ID number: 'Sys Generated. VARIABLESTRING 3333'> kent$ awk -F"('|driving to: |>)" '{printf "%s\n\t%s\n\n", NF==5?$4:"Not Found",$2;next}' f Canada Sys Generated. VARIABLESTRING 1111 Mexico Sys Generated. VARIABLESTRING 2222 Not Found Sys Generated. VARIABLESTRING 3333 ```
28,347,728
I have implemented a single page application with `AngularJS`. The page consists of a content area in the middle and sections assembled around the center that show additional info and provide means to manipulate the center. ![enter image description here](https://i.stack.imgur.com/LHqgh.png) Each section (called `Side Info`) and the content area have a separate AngularJS controller assigned to them. Currently, I communicate via `$rootScope.$broadcast` and `$scope.$on()`, e.g. ``` app.controller('PropertiesController', function ($scope, $rootScope) { $scope.$on('somethingHappened', function(event, data){ // react }); }); ``` I then call to communicate with other controllers: ``` $rootScope.$broadcast('somethingHappened', data); ``` I have quite a lot of communication happening between the Controllers. Especially if something is going on in the content area, several side info elements have to adopt. The other way around is also frequent: a user submits a form (located in a side info) and the content area and other side info elements have to adopt. **My question:** Is there a better way to handle `SPA` with heavy controller communication? The code works fine but it is already getting a bit messy (e.g. it is hard to find which events are handled where etc.). Since the application is likely to grow a lot in the next weeks, I'd like to make those changes (if there are any better solutions) asap.
2015/02/05
[ "https://Stackoverflow.com/questions/28347728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3955724/" ]
This is really interesting. Pub/Sub should be a right solution here. You could add extra order to your project by using Angular services **as your MVC's model**, and update this model for each change. The issue here is that you should implement an observable pattern inside your service and register to them, in order for this to be live synced. So - we're back to Pub/Sub (or other Observable solution that you could think about...). But, the project will be better organised that way. For example - SideInfo1Service will be a service/model. Each property change will trigger an observable change which will change all listeners: ``` myApp.factory('SideInfo1Service', function($scope){ var _prop1; return { setProp1: function(value){ $scope.$broadcast('prop1Changed', value); _prop1 = value; }, getProp1: function(){ return _prop1; } } }); ``` You could find those really interesting blog posts about using Angular Services as your MVC's model: <http://toddmotto.com/rethinking-angular-js-controllers/> <http://jonathancreamer.com/the-state-of-angularjs-controllers/> And, this post is about observable pattern in Angularjs: <https://stackoverflow.com/a/25613550/916450> Hope this could be helpful (:
You can use ``` $rootScope.$emit('some:event') ; ``` because it goes upwards and rootscope ist the top level use ``` var myListener = $rootScope.$on('some:event', function (event, data) { }); $scope.$on('$destroy', myListener); ``` to catch the event Then you have a communication on the same level the rootscope without bubbling Here is my implemented eventbus service <http://jsfiddle.net/navqtaoj/2/> **Edit**: you can use a namespace like **some:event** to group and organize your event names better and add log outputs when the event is fired and when the event is catch so that you easy can figure out if fireing or catching the wrong eventname.
98,345
Despite the fact that $\forall n, n^3 + 2n \equiv 0 \pmod 3$, I understand that $n^3 + 2n$ (considered as a polynomial with coefficients in $\mathbb Z/3\mathbb Z$) is *not* equal to the zero polynomial. What is the value of defining polynomials in this (strange) way? What situations does it make things simpler? I ask this because it seemed natural to me to define polynomials as a subset of functions, so I was surprised by this.
2012/01/12
[ "https://math.stackexchange.com/questions/98345", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
I’m astonished someone (namely, @Qiaochu Yuan) remembered about field extensions, but nobody did mention that field extensions **rely** on irreducible polynomials, defined in the sense discussed. Namely, the quotient ring $k[x]/\langle P(x)\rangle$, where $P$ is irreducible, is a field and gives an extension of $k$, non-trivial one if $\deg P > 1$. How many *functions* there are from ${\mathbb F}\_p$ to ${\mathbb F}\_p$? (“${\mathbb F}\_p$” is what original poster would denote by ${\mathbb Z}/p{\mathbb Z}$ for a prime $p$.) There are $p^p$. One can’t hope to construct from the ring of functions, in just two operations, any field ${\mathbb F}\_{p^m}$ where $m>p$. What is cardinality of ${\mathbb F}\_p[x]$? In other words, how many *polynomials* with coefficients from ${\mathbb F}\_p$ exist? Countably infinite. And for each natural $m$ there exist such irreducible polynomial $P$ (of degree $m$) that ${\mathbb F}\_p[x]/\langle P(x)\rangle ≃ {\mathbb F}\_{p^m}$ . In fact, any irreducible polynomial $P$ of degree $m$ is feasible; it’s their *existence* that is crucial.
I would mean the opposite: since there is no injection $k[X\_1,\dots,X\_n]\to \operatorname{Func}(k^n,k)$, formal polynomials is something different than functions.
19,806,452
I have a problem with Android-x86 and VirtualBox. I had never worked with Linux before, so I don't understand what's happening. After creating a new virtual machine and choosing "Install Android-x86", I get this: ![Kernel panic](https://i.stack.imgur.com/Syk8K.png) My settings: ![configuration](https://i.stack.imgur.com/iFXE8.png) I've tried using android-x86-4.2-20130228.iso and android-x86-4.2-20121225.iso What's wrong?
2013/11/06
[ "https://Stackoverflow.com/questions/19806452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1474925/" ]
Download Android 4.0 for EEEpc and you don't need Virtualization technology. It works for me.
[![enter image description here](https://i.stack.imgur.com/RVxou.png)](https://i.stack.imgur.com/RVxou.png) **Make Sure Graphics Controller: VBoxSVGA**
24,173,837
I'm basicallly following the guide on <https://github.com/amplab/shark/wiki/Running-Shark-Locally>. I downloaded scala I'm using ec2 amazon linux my shark/shark-0.8.0/conf/shark-env.sh configuration file look like this ``` export SPARK_MEM=1g export SHARK_MASTER_MEM=1g export SCALA_HOME="/home/user2/scala/" export HIVE_HOME="/home/user2/shark/hive-0.9.0-shark-0.8.0-bin/" ``` I also have JAVA\_HOME set to /usr/lib/jvm/jre when i type java -version it returns: ``` java version "1.7.0_55" OpenJDK Runtime Environment (amzn-2.4.7.1.40.amzn1-x86_64 u55-b13) OpenJDK 64-Bit Server VM (build 24.51-b03, mixed mode) ``` Every time trying to run shark with the following: ``` shark/shark-0.8.0/bin/shark ``` I don't understand why I'm getting this bunch of error. DOes anybody know?? ``` Exception in thread "main" java.lang.NoClassDefFoundError: scala/ScalaObject at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:800) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) at java.net.URLClassLoader.access$100(URLClassLoader.java:71) at java.net.URLClassLoader$1.run(URLClassLoader.java:361) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:800) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) at java.net.URLClassLoader.access$100(URLClassLoader.java:71) at java.net.URLClassLoader$1.run(URLClassLoader.java:361) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:800) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) at java.net.URLClassLoader.access$100(URLClassLoader.java:71) at java.net.URLClassLoader$1.run(URLClassLoader.java:361) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482) Caused by: java.lang.ClassNotFoundException: scala.ScalaObject ```
2014/06/11
[ "https://Stackoverflow.com/questions/24173837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2773013/" ]
You can go: ``` std::string(clean, clean + 30); ``` It would be better if you store the string in an array (or a `#define`), then you can check its length programmatically, e.g. ``` char const raw[] = "text1\0\0text2\0\0\0text3\0more text"; std::string(raw, raw + sizeof raw - 1); ```
This is the expected behavior. The "\0" is being understood as end of string. If you try to pritnf you raw variable with "%s" format you will get the same output - "text1". If you want the whole string this is what you should do: ``` const char * raw = "text1\\0\\0text2\\0\\0\\0text3\\0more text"; ``` So, before passing it to an std::string constructor you can write another routine which appends an extra '\'.
81,166
I am traveling to New Jersey on the 4th of November, but unfortunately my air ticket is booked via JFK. There were no direct flights to EWR from where I live. Which is the best possible way to travel to either Hoboken or Harrington Park on a student's budget?
2016/10/21
[ "https://travel.stackexchange.com/questions/81166", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/52778/" ]
While the train option outlined by mazeem is probably the best balance of time and cost for most people, there is a less expensive option for those who have more time. Namely, you can take the MTA subway from Jamaica to the World Trade Center (or from Howard Beach to Fulton Street), and then take the PATH to Hoboken. The fare will be $10.50: $5 for the AirTrain and $2.75 each for the subway and the PATH. According to Google, the travel time for the LIRR itinerary is around an hour and 25 minutes, while for the subway itinerary, via Howard Beach and the A train, it's around 10 minutes longer, and via Jamaica and the E train, it's around an hour and three quarters. I got the Howard Beach itinerary by choosing "fewest transfers" in the search options, and the Jamaica itinerary by choosing "less walking." If you are traveling on the weekend, you can save yourself three dollars on the LIRR fare by buying CityTicket at the kiosk. This costs $4.25, as opposed to the $7.25 off-peak fare. A side benefit of this approach is that if you take the A train to Fulton Street, you can walk through the recently opened *Oculus:* [![enter image description here](https://i.stack.imgur.com/8LY2e.jpg)](https://i.stack.imgur.com/8LY2e.jpg) This is especially useful in foul weather, as it means you can avoid going outside.
[First go to Manhattan by the routes mentioned on this previous question](https://travel.stackexchange.com/questions/7623/getting-from-new-york-jfk-airport-to-manhattan-without-the-sneaky-airtrain-exit?rq=1). That way, no need to pay for the sky train. The total cost $2 or $3. Then follow the advice of @phoog [above to switch to the path train](https://travel.stackexchange.com/a/81170/46787) to Jersey. Total cost is less than $10, so you can buy some small packets of peanuts and a [Daily News](http://www.nydailynews.com/) to read on the train.
51,363,935
I am trying to build an old project using Android studio but the process fails. The error message I get is this: *Error:Failed to read native JSON data Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $* I get a more detailed error message in the Build tab:[![enter image description here](https://i.stack.imgur.com/M5ks2.png)](https://i.stack.imgur.com/M5ks2.png) I believe that the build.gradle file of the app, is responsible for the error. The code of the file is: ``` apply plugin: 'com.android.application' android { compileSdkVersion 25 buildToolsVersion "25.0.3" defaultConfig { applicationId "com.example.despoina.ldtest" minSdkVersion 15 targetSdkVersion 25 versionCode 1 versionName "1.0" ndk { abiFilters 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a' } testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" externalNativeBuild { cmake { arguments '-DANDROID_PLATFORM=android-13', '-DANDROID_TOOLCHAIN=clang', '-DANDROID_STL=gnustl_static' } } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } sourceSets { main { // let gradle pack the shared library into apk jniLibs.srcDirs += ['../gen-libs/gmp'] jniLibs.srcDirs += ['../distribution/ecc/lib'] jniLibs.srcDirs += ['../distribution/smodbus/lib'] resources.includes = [ 'res/parameters.txt' ] } } externalNativeBuild { cmake { path 'src/main/cpp/CMakeLists.txt' } } }dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'com.android.support:appcompat-v7:25.2.0' implementation 'com.android.support.constraint:constraint-layout:1.0.1' // uncomment out this one to generate lib binaries, // and also uncommented out the one in settings.gradle // after lib is generated, just comment them out again //implementation project(':gen-libs') } ``` Any help will be appreciated!!
2018/07/16
[ "https://Stackoverflow.com/questions/51363935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4941288/" ]
Solution 1: =========== Finally I solved my problem which is not related to the json lenient mode, something wrong with my POST response (there some other non json output before the json data). Here is the response from JakeWharton regarding how to set Gson lenient mode: make sure that you have:`compile 'com.google.code.gson:gson:2.6.1'` ``` Gson gson = new GsonBuilder() .setLenient() .create(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .client(client) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); ``` Solution 2: =========== Also this issue occurred when the response contenttype is not `application/json`. In my case response content-type was `text/html` and i faced this problem. I changed it to `application/json` then it will work.
An errore in Line 1 and Column 1 usually means that the JSON is not a real JSON. Maybe the Server is sending the JSON as HTML or something else or the format is not well readable (UTF-8 and ASCII are well supported, but other encoders may not). Try to print Server's response as byte[] and see which is the first char.
13,841,880
I am binding an `enum` to a property grid like this: ``` public enum myEnum { Ethernet, Wireless, Bluetooth } public class MyClass { public MyClass() { MyProperty = MyEnum.Wireless; } [DefaultValue(MyEnum.Wireless)] public MyEnum MyProperty { get; set; } } public Form1() { InitializeComponent(); PropertyGrid pg = new PropertyGrid(); pg.SelectedObject = new MyClass(); pg.Dock = DockStyle.Fill; this.Controls.Add(pg); } ``` My problem: I get data on the fly when the program is running. I read the network adapter then store adapter names to `myArray` like this: ``` string[] myArray = new string[] { }; myArray[0] = "Ethernet"; myArray[1] = "Wireless"; myArray[2] = "Bluetooth"; ``` Is possible convert `myArray` to `myEnum` on the fly using c#? Thank You.
2012/12/12
[ "https://Stackoverflow.com/questions/13841880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/705654/" ]
If your source data is not something entirely reliable, you may want to consider converting only the items that can actually be parsed, using `TryParse()` and `IsDefined()`. Getting an array of myEnums from an array of strings can be performed by the following code: ``` myEnum [] myEnums = myArray .Where(c => Enum.IsDefined(typeof(myEnum), c)) .Select(c => (myEnum)Enum.Parse(typeof(myEnum), c)) .ToArray(); ``` Note that `IsDefined()` only works with a single enumerated value. If you have a `[Flags]` enum, combinations fail the test.
Use `Enum.Parse` in the loop for each element in the array.
20,916,339
I am wanting to route the main site and exclude paths with digits in them (like the account id). So for example, I want to constraint a url like domain.com/about\_us or domain.com/signup/plan/1 BUT exclude all paths that start with a integer, like domain.com/1234573/user/3 or domain.com/123456 I have the following code but I get "No route matches [GET] '/signup'" when going to any of the constraint urls like domain.com/signup. I get the homepage just fine (domain.com). ``` class MainSite # Match only non account pages # urls like domain.com/signup # BUT NOT like domain.com/2342342 def self.matches?(request) not request.path =~ %r{\A\/\D} end end Myapp::Application.routes.draw do devise_for :app_admins mount RailsAdmin::Engine => '/app_admin', :as => 'rails_admin' # Routes for the public site constraints MainSite do # Homepage get '/' => "content#index" get '/signup' => 'accounts#plans', :as => 'plans' .... end root :to => "accounts#dashboard" devise_for :users ... ``` Not sure what I am missing here.
2014/01/04
[ "https://Stackoverflow.com/questions/20916339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1002361/" ]
Here is one way to do it: * Convert it to `String` * Take the substring without the first "digit" * Convert it to `int` --- **Code:** ``` public static void main(String[] args) { int x = 123456789; String x_str = Integer.toString(x); int new_x = Integer.parseInt(x_str.substring(1)); System.out.println(new_x); } ``` **Output:** ``` 23456789 ``` --- **Note:** This can be done in one line with ``` int x = 123456789; int new_x = Integer.parseInt(Integer.toString(x).substring(1)); ``` **Edit:** To handle negative-case, check if number is positive or integer: ``` int new_x = Integer.parseInt(x > 0 ? Integer.toString(x).substring(1) : Integer.toString(x).substring(2)); ```
I think I remember the string-free version of this … although I totally agree with @Christian as how I would do it… NOTE: as @Darren Gilroy pointed out, one must consider negatives and zero spocially, and my function fails to do so. Of course `%` is a better solution also. ``` public static void main (String [] argv) { final int x = 123456789; int newX = x; /* How many digits are there? */ final double originalLog = Math.floor (Math.log10 (x)); /* Let's subtract 10 to that power until the number is smaller */ final int getRidOf = (int)Math.pow (10, originalLog); while (originalLog == Math.floor (Math.log10 (newX))) { newX -= getRidOf; } System.out.println (newX); } ``` Poor profiling attempt: Looping the above function without the `println` for 20,000,000,000 repeats in a `for` loop: ``` real 0m9.943s user 0m9.890s sys 0m0.028s ``` The same with Christian's far-easier-to-understand and perfectly functionable version, but for only 200,000,000 repeats (because I'm lazy and got tired of waiting): ``` real 0m18.581s user 0m17.972s sys 0m0.574s ``` So one might argue that constructing the String objects is probably slowing it down by roughly 200×, but that isn't a really finely-tuned profiling set-up.
27,612,165
That seems too tricky for me since `ImmutableSet` instances are only built with `ImmutableSet.Builder` instances, which don't implement `Collection` so you can't just use `Collectors.toCollection(ImmutableSet::new)` or `Collectors.toCollection(ImmutableSet.Builder::new)`.
2014/12/22
[ "https://Stackoverflow.com/questions/27612165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1542343/" ]
This is built into guava now, [ImmutableSet#toImmutableSet](https://google.github.io/guava/releases/22.0/api/docs/com/google/common/collect/ImmutableSet.html#toImmutableSet--) Use like, ``` something.stream().collect(ImmutableSet.toImmutableSet()) ```
This is the closest that I found: ``` Set<String> set = list.stream().collect(ImmutableSet.Builder<String>::new, ImmutableSet.Builder<String>::add, (builder1, builder2) -> builder1.addAll(builder2.build())).build(); ``` There is no method that takes append the elements of one builder into another builder, only an Iterable or an Iterator, so you cannot use a method reference for this one.
24,766
Suppose we have 2 strategies : * **strategy A** : every $N$ days, we short a call option with a time-to-maturity of $N$ days; * **strategy B** : every day, we short $\frac{1}{N}$ of a call option with a time-to-maturity of $N$ days. When would strategy B be considered better than strategy A ?
2016/03/09
[ "https://quant.stackexchange.com/questions/24766", "https://quant.stackexchange.com", "https://quant.stackexchange.com/users/19693/" ]
Draw a picture. For each scenario, there are obvious circumstances that the payoff for each would be better. For the N day option, the payoff would be better if there was a slow gradual decline in price and a slow gradual increase over the same period, such that the final difference in the price of the underlying was largely unchanged. For multiple options issued over that period, at expiration, there would be several options that would need to pay off, so that would be worse. In the event of quick downward and upward movements, I'm unable to say which would be better. The multiple options would benefit from increased premium from higher implied volatilities, but will be further out of the money. In the event of a slow decreasing or increasing underlying price, the multiple options would benefit from strike prices that are struck at different levels and therefore, the overall volatility of the strategy would be lower than just selling one option. You will find that if you look at these strategies using historical prices, the multiple options will have a lower return, but the decrease in volatility will push the information ratio of the strategy higher than the individual sale. Given you are selling options, and depending on your cash coverage requirements, this could mean that, for the same volatility, you can put on a larger position in the second scenario and have a larger return than the first.
Given the information provided in the question, expected value of A and B is the same. Simple example: consider this binomial model with stock paths on the left, and call option prices on the right. [![enter image description here](https://i.stack.imgur.com/ZBMG1.png)](https://i.stack.imgur.com/ZBMG1.png) What you can easily calculate is that expected value of strategy A and strategy B is the same. If we label paths as UU, UD, DU, DD (up & up, up & down, etc ) the payoffs are: A: -15,5,5,5 B: -12.5,7.5,2.5,2.5 Like @Yugmorf noted "For any given [arbitrage-free] vol curve, the expected cost of the two strategies should be the same"; with A having higher variance and higher kurtosis than B. This statement is correct in general, not only for a two-period model, and for convex or flat vol surface. In practical cases however, if you expect change in volatility, or have an opinion on direction, A or B may be preferable.
1,587,496
I'm writing an application to parse certain network packets. A packet field contains the protocol version number in an octet, so that 4 high bits are the 'major' and low 4 are the 'minor' version. Currently I am parsing them as follows, but am wondering if there is a prettier or more 'pythonic' way of doing it: ``` v = ord(data[17]) major = (v & int('11110000',2) ) >> 4 minor = v & int('00001111',2) ```
2009/10/19
[ "https://Stackoverflow.com/questions/1587496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180174/" ]
Well named functions are always a good way to hide ugliness and irrelevant complexity. This way the bit-fiddling is confined to small and easily proven correct functions while the higher level code can refer to the purpose of the fiddling. ``` def high_nibble(byte): """Get 4 high order bits from a byte.""" return (byte >> 4) & 0xF def low_nibble(byte): """Get 4 low order bits from a byte.""" return byte & 0xF def parse_version(version_byte): """Get the major-minor version tuple from the version byte.""" return high_nibble(version_byte), low_nibble(version_byte) major, minor = parse_version(version_byte) ```
It would be neater to use literals instead of calling `int`. You can use binary literals or hex, for example: ``` major = (v & 0xf0) >> 4 minor = (v & 0x0f) ``` Binary literals only work for Python 2.6 or later and are of the form `0b11110000`. If you are using Python 2.6 or later then you might want to look at the `bytearray` type as this will let you treat the data as binary and so not have to use the call to `ord`. If you are parsing binary data and finding that you are having to do lots of bit wise manipulations then you might like to try a more general solution as there are some third-party module that specialise in this. One is [hachoir](http://hachoir.org/), and a lower level alternative is [bitstring](http://python-bitstring.googlecode.com) (which I wrote). In this your parsing would become something like: ``` major, minor = data.readlist('uint:4, uint:4') ``` which can be easier to manage if you're doing a lot of such reads.
46,882
[Feeblemind](https://www.dndbeyond.com/spells/feeblemind) requires an Int save: on a fail, the target's Intelligence and Charisma are set to 1. This pretty much destroys any Int or Cha-based caster, but the fact that the latter have low Int (and are not proficient with Intelligence saving throws) makes them especially vulnerable. What are some ways to handle this? The route I've taken with a Sorcerer concept is to start as a Rogue for my 1st level (for Int proficiency) and then go Sorcerer from 2nd level. Other ideas welcome. My goal is to learn what options there are to prevent getting Feebleminded, be it at character creation, or a magical item, or... anything that helps resist it. E.g., it just occurred to me that, while expensive, L9 *Globe of Invulnerability* will prevent it (and duration could be doubled for 1 sorcery point).
2014/08/28
[ "https://rpg.stackexchange.com/questions/46882", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/15680/" ]
### The 8th level spell [*mind blank*](https://www.dndbeyond.com/spells/mind-blank) grants outright immunity to the spell [*feeblemind*](https://www.dndbeyond.com/spells/feeblemind). *Mind blank* says, > > Until the spell ends, one willing creature you touch is immune to psychic damage, any effect that would sense its emotions or read its thoughts, divination spells, and the charmed condition. The spell even foils wish spells and spells or effects of similar power used to *affect the target's mind* or to gain information about the target. > > > *Feeblemind* says, > > You blast the mind of a creature that you can see within range, attempting to shatter its intellect and personality. > > > Now, *feeblemind* is an 8th level spell, but *mind blank* is written to specifically counter this when it says "*the spell even foils wish spells and spells or effects of similar power used to affect the target's mind*.
Get a *headband of intellect* ----------------------------- Magical items always require cooperation by your DM who controls access, but you are asking also for magical items that can help. A [headband of intellect](https://www.dndbeyond.com/magic-items/4652-headband-of-intellect) will set your intelligence to 19, improving your chances to make that saving throw. It has the added advantages that it is only uncommon, so you could find it or procure it as a quest reward relatively early in the game, and that it is an ongoing effect that works around the clock. It has a downside in requiring attunement, which at high levels where you may have several items competing for it can be a real cost. As an item it does not use up one of your feats, and you could combine it with a features that give you proficiency on the save like the Resilient feat or like the first level Rogue dip that you took, to nearly be on par with a maximized Intelligence-based caster like a wizard. What's more, the *headband* is a generally useful item that will give you a boost to all Intelligence releated ability checks such as Investigation or the various knowledge checks (History, Nature, Arcana). --- P.S. If you think about it, it is not a great idea to invest too many resources to defend specifically against only *feeblemind*. High level spells can all be pretty bad. The odds are it really does not matter that much *which* 8th level spell is hitting you -- when it happens early in the game, an upcast fireball can destroy you just as well. Even lower level spells like *plane shift* (Cha save), *flesh to stone* (Con save) or *disintegrate* (Dex save) can remove a character from play, and yet not everyone is trying to shore up all of these saves with their precious feats. You cannot avoid all of them all of the time, so consider tactics that allow you to recover from setbacks, like allies that can restore you.
26,967,682
I'm trying to make this persistant cart that lets you add products to cart without redirecting to a new page. It works perfectly, but the only problem is that it can not be closed when you click on the exit button in the corner. [Live version here by clicking on cart](http://eldeskin.com/products/gel-cleanser). Make sure to add a product to see it work, else you won't see anything. I have tried this: ``` <script type="text/javascript"> $(document).ready(function(){ $('.cart-show').click(function(){ $("#cart").hide(); }); }); </script> ``` Aswell as cartToggle with is a feature in the Shopify theme Timber.
2014/11/17
[ "https://Stackoverflow.com/questions/26967682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/964012/" ]
The class `.cart-show` is adding to your `[X]` element later, so you should use event delegation: ``` $(document).ready(function() { $('body').on('click', '.cart-show', function (e) { $("#cart").hide(); }); }); ```
1.) You should use event delegation, 2.) If you have id for element you should use id as selector ``` $(document).ready(function() { $('body').on('click', '#exit', function () { $("#cart").hide(); }); }); ```
9,496
Have a suite of web-drivers tests that run in chrome and IE 10, but will not run in IE 11. The tests fail in IE-11 when clicking a button as the following action (a form popup) does not occur. I cannot repeat this manually and this only seems to happen in IE-11. No exceptions are thrown when finding the button or clicking the button. This is an intermittent error as sometimes the clicking will work and the tests will run. I can put an explicit wait before the click(s) occur and tests will then run. The button is always present in the DOM (not added later by javascript). I have also added a check so that web-driver will not start interacting (clicking) with a page until after all the initial javascript has finished running on the page. This is done by the last piece of javascript setting a flag. Has anyone had similar issues? **Edit** I don't want to have waits in the test code. Just put them in to debug what was not working
2014/08/20
[ "https://sqa.stackexchange.com/questions/9496", "https://sqa.stackexchange.com", "https://sqa.stackexchange.com/users/5216/" ]
For Selenium 3.0.1, I setup as follow and it works for IE 11. ``` InternetExplorerOptions caps = new InternetExplorerOptions(); caps.IgnoreZoomLevel = true; caps.EnableNativeEvents = false; caps.InitialBrowserUrl = "http://localhost"; caps.UnexpectedAlertBehavior = InternetExplorerUnexpectedAlertBehavior.Accept; caps.IntroduceInstabilityByIgnoringProtectedModeSettings = true; caps.EnablePersistentHover = true; IWebDriver driver = new InternetExplorerDriver(caps); ```
Try next steps: 1. Open Display settings in Windows (right click on desktop, choose Display Settings) 2. Set option "Change the size of text, apps, and other items" to 100%. After this steps, Click() method should work. This solved my problem with Click() method.
10,627,650
I have 2 double quotes that need to be replaced by a single double quote. I am using this method: ``` private static void ReplaceTextInFile(string originalFile, string outputFile, string searchTerm, string replaceTerm) { string tempLineValue; using (FileStream inputStream = File.OpenRead(originalFile)) { using (StreamReader inputReader = new StreamReader(inputStream)) { using (StreamWriter outputWriter = File.AppendText(outputFile)) { while (null != (tempLineValue = inputReader.ReadLine())) { outputWriter.WriteLine(tempLineValue.Replace(searchTerm, replaceTerm)); } } } } } ``` and calling it this way ``` ReplaceTextInFile(file, file + "new", (char)34 + (char)34, (char)34); ``` the error i am getting is ``` Error 4 Argument '3': cannot convert from 'int' to 'string' and Error 5 Argument '4': cannot convert from 'char' to 'string' ``` what am i doing wrong?
2012/05/16
[ "https://Stackoverflow.com/questions/10627650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/117700/" ]
I'd use `ReplaceTextInFile(file, file + "new", "\"\"", "\"");`
The function expects four `string`s. You pass two `string`s, and then an `int`, and then a `char`. Adding two `char`s results in an `int`. You can't concatenate chars, it makes no sense as a `char` represents an *individual* character, so the result is an `int`. The last one is a straight cast to `char` where a `string` is expected, that seems obvious enough.
1,361,468
The expected number of coin flips to get one heads is $2$. What is wrong with this argument? > > There is a $1/2$ chance of getting $H$, $1/4$ chance of getting $TH$, > $1/8$ chance of getting $TTH$, etc. so the expected value of flips is > > > $$\frac{1}{2} + \frac{2}{4} + \frac{3}{8} + ...\approx \ ?$$ > > > Edit: incorrect value
2015/07/15
[ "https://math.stackexchange.com/questions/1361468", "https://math.stackexchange.com", "https://math.stackexchange.com/users/122489/" ]
you need to consider the event $A\_k$ ={Head shows up in the $k$ flip} $$P(A\_k) = P(T(k-1 \text{times} ) H) = 2^{-k}$$ The expected value of $X = \sum\_k k \chi\_{A\_k}$ which thakes the value $k$ when $A\_k$ occurs is \begin{align}\Bbb{E}[X] = \sum\_k k2^{-k} &= \frac{1}{2} + \frac{1}{4} + \frac{1}{8} + \ldots & = 1\\ & \qquad + \frac{1}{4} + \frac{1}{8} + \ldots &= \frac{1}{2} \\ & \qquad \qquad +\frac{1}{8} + \ldots &=\frac{1}{4}\\ &\qquad \qquad \qquad\vdots&\vdots\end{align} So $\Bbb{E}[X] = 1 + \frac{1}{2} + \frac{1}{4} + \ldots = 2$ --- Addendum: If the format is a little unclear, try this: $\begin{align} \sum\_{k=1}^\infty \frac k{2^k} & = \frac 1 2 + \frac 2 4 + \frac 3 8 +\cdots \\[2ex] & = \boxed{\begin{matrix} (\frac 1 2 & + \frac 1 4 &+ \frac 1 8 &+\cdots)+ \\ & (\frac 1 4 & + \frac 1 8 & +\cdots)+ \\ & & (\frac 1 8 & + \cdots) +\\&&& + \cdots \end{matrix}} \\[2ex] & = \boxed{\begin{matrix} (\frac 1 2 & + \frac 1 4 &+ \frac 1 8 &+\cdots)+ \\ & \frac 1 2(\frac 1 2 & + \frac 1 4 & +\cdots)+ \\ & & \frac 1 4(\frac 1 2 & + \cdots) +\\&&& + \cdots \end{matrix}} \\[2ex] & = 1 + \frac 1 2 + \frac 1 4 + \cdots \\[2ex] & = 2 \\[1ex]\Box \end{align}$
I think I get what you're trying to do, although the proof is much easier to show from a more direct definition. The probability of having one coin flip result in heads is $1/2$. The probability of it taking two flips is $1/4$. In general the probability of it taking n flips is $2^{-n}$. So we automatically know you'll never have to flip the coin an infinite number of times. To find the average number of flips required, simply take the weighted mean (expected value) of all the probabilities. $$\sum\_{n=1}^{\infty} 2^{-n} \cdot n$$ You'll get $2$. This is the average number of flips needed to get heads.
3,918,612
I have a menu coded in html here, but i need a dotted line to span between the Names and Prices, How would i go about doing that here? I'm kinda lost haha. You can see it here. <http://mystycs.com/menu/menuiframe.htm> I know i can use css to do it, but how would i get to it span between those two. Thanks =)
2010/10/12
[ "https://Stackoverflow.com/questions/3918612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/330396/" ]
``` <style type="text/css"> .menugroup{ width:100%; } .itemlist{ list-style-type: none; } .separator{ margin: 5px; width:50%; border-bottom: 1px dotted #000 } </style> <div class="menugroup"> <ul class="itemlist"> <li>item name<span class="separator"></span>price</li> </ul> </div> ```
``` <style> table th, td{ border-bottom: 1px dotted #CCCCCC; } ``` HTML code block: ``` <h3>Current House Trends</h3> <table class="table" border="0"> <tbody> <tr> <th>Price</th> <td>$500,000</td> </tr> <tr> <th>Market</th> <td>78</td> ``` If you want to put '-' in between you can add an extra column in the middle which contains '-' or similar of your choice.
9,588,960
I found this example of how to use ViewPager and it's pretty simple to follow along. Now I'm wondering, can the ViewPager can show multiple views at the same time? If I have 10 items in the PagerAdapter can I have it show views 1, 2, and 3 first then when you swipe it moves over to 2,3,4; then 3,4,5; etc...
2012/03/06
[ "https://Stackoverflow.com/questions/9588960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/862495/" ]
`Map` is an interface; `HashMap` is a particular implementation of that interface. HashMap uses a collection of hashed key values to do its lookup. TreeMap will use a red-black tree as its underlying data store.
`HashMap` is an implementation of `Map`. [Map](http://docs.oracle.com/javase/6/docs/api/java/util/Map.html) is just an interface for any type of map.
87,070
Suppose a finite-dimensional Lie group $G$ is given. Does there exist a connected manifold $M$ and a Riemannian metric $g$, such that $G$ is the **full** isometry group of $(M,g)$? For example if I try to do this for a connected $G$, then I often get a bigger group as the full isometry group, which includes e.g. the orientation reversing isometries. (Maybe one has to take a non--orientable space for that?) Even if I try to realize $\mathbb R$ as a full isometry group, I fail. (One could take the full isometry group of $\mathbb R$ with the standard metric, which is given by $\mathbb R \rtimes \mathbb Z\_2$ and divide out the $\mathbb Z\_2$ action. But this leads to a fixpoint and the quotient is therefore not a manifold any more.) There is an article of J. de Groot1 which proves that every abstract group can be realized as an isometry group of some metric space, but it is not clear to me, if this is true in the category of Lie groups and Riemannian manifolds. 1de Groot, J. "Groups represented by homeomorphism groups." Math. Ann. 138 (1959) 80–102. [MR119193](https://www.ams.org/mathscinet-getitem?mr=119193) doi:10.1007/BF01369667</a
2012/01/30
[ "https://mathoverflow.net/questions/87070", "https://mathoverflow.net", "https://mathoverflow.net/users/20999/" ]
The group $\mathbb R$ can be realized as full isometry group of $(\mathbb R\times\mathbb S^1 ,g)$. Choose a generic periodic one parameter family of quadratic forms $h(t)$ on $\mathbb R^2$. Consider metric $g(x,y)=h(y)$ on $\mathbb R\times\mathbb S^1$. **Why:** Note that each fiber $\mathbb R\times u$ maps to it-self. Note that orthogonal fibration $\mathcal{F}$ is preserved. Go along $\mathcal{F}$ once around $\mathbb S^1$. Since $h$ is generic you will not get to the same point. Therefore each isometry preserves the orientaion of $\mathbb R$-fibers. This idea seems to work in general. Consider metric $g$ on $G\times \mathbb T^2$ which is invariant w.r.t. left $G$-translations and such that $g(e,t)=h(t)$ is a generic family of quadratic forms on $T\_{(e,t)}$; here $t\in \mathbb T^2$. **Why:** This way you get a holonomy map from $G\to G$ for any loop in $\mathbb T^2$. For generic $h(t)$ you may assume that there is no automorphism of $G$ which preserve this holonomy.
Maybe this is the same as the idea of Anton, but I thought I post it anyway for its visualization. I think something like this will have *full* isometry group $=\Bbb R$: a periodically winding "rope" with a generic surface structure. [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/9Vv5n.png In formulas, if $h:\Bbb S^1\to\Bbb R$ is generic, then above figure can be given by a parametric description $$(\theta,z)\quad\mapsto\quad (1+h(\theta+\alpha z))\begin{pmatrix}\cos(\theta)\\\sin(\theta)\\0\end{pmatrix} + \begin{pmatrix} 0\\0\\z \end{pmatrix}$$ with some parameter $\alpha$.
6,561,771
I am trying to generate a key for encryption: ``` public static final String ENCYT_ALGORITHM = "AES/ECB/PKCS7Padding"; public static final String KEY_ALGORITHM = "PBEWITHSHA256AND256BITAES-CBC-BC" ; //BENCYT_ALGORITHMSE64Encoder encod = new BENCYT_ALGORITHMSE64Encoder(); //BENCYT_ALGORITHMSE64Decoder decod = new BENCYT_ALGORITHMSE64Decoder(); public Encryption(String preMaster,String text,int x){ this.preMaster=preMaster; this.text=text.getBytes(); } public void keyGenerator(){ KeyGenerator kg = null; try { kg = KeyGenerator.getInstance("AES"); secret = kg.generateKey(); } catch (Exception e) { // TODO ENCYT_ALGORITHMuto-generated catch block e.printStackTrace(); } } public String preMaster() { byte[] keys = null; keys = preMaster.getBytes(); int x = -1; int process = 0; while (x < keys.length - 2) { x++; switch (x) { case 1: process = keys[x + 1] | a ^ c & (d | keys[x] % a); case 2: process += a | (keys[x] ^ c) & d; case 3: process += keys[x] ^ (keys[x + 1] / a) % d ^ b; default: process += keys[x + 1] / (keys[x] ^ c | d); } } byte[] xs = new byte[] { (byte) (process >>> 24), (byte) (process >> 16 & 0xff), (byte) (process >> 8 & 0xff), (byte) (process & 0xff) }; preMaster = new String(xs); KeyGenerators key = new KeyGenerators(preMaster); String toMaster = key.calculateSecurityHash("MD5") + key.calculateSecurityHash("MD2") + key.calculateSecurityHash("SHA-512"); return toMaster; } public String keyWrapper(){ Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); Key SharedKey = secret; String key = null; char[] preMaster = this.preMaster().toCharArray(); try { byte[]salt={ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06}; paramSpec = new PBEParameterSpec(salt,256); PBEKeySpec keySpec = new PBEKeySpec(preMaster,salt,1024,256); SecretKeyFactory factory = SecretKeyFactory.getInstance(KEY_ALGORITHM); passwordKey = factory.generateSecret(keySpec); Cipher c = Cipher.getInstance(KEY_ALGORITHM); c.init(Cipher.WRAP_MODE, passwordKey, paramSpec); byte[] wrappedKey = c.wrap(SharedKey); key=new String(wrappedKey,"UTF8"); }catch(Exception e){ e.printStackTrace(); } return key; } ``` And this is the result : ``` java.security.InvalidKeyException: Illegal key size at javax.crypto.Cipher.a(DashoA13*..) at javax.crypto.Cipher.a(DashoA13*..) at javax.crypto.Cipher.a(DashoA13*..) at javax.crypto.Cipher.init(DashoA13*..) at javax.crypto.Cipher.init(DashoA13*..) at fiador.authentication.util.Encryption.keyWrapper(Encryption.java:101) at fiador.authentication.util.Encryption.main(Encryption.java:144) null ``` I am really desperate ... please help me, thanks !
2011/07/03
[ "https://Stackoverflow.com/questions/6561771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/594131/" ]
You have not installed the unlimited strength crypto files, (the default JDK install allows 128 bit keys as documented in <http://download.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#AppC>). Download unlimited strength crypto package [here](https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_Developer-Site/en_US/-/USD/ViewProductDetail-Start?ProductRef=jce_policy-6-oth-JPR@CDS-CDS_Developer). [Installation Help](http://gonithethinker.blogspot.com/2012/07/install-java-cryptography-extension-jce.html)
I can't see where `keyGenerator` is being called. If it is not called, then `secret` is not being initialized. That could be the cause of the root exception. (It is hard to tell, because you've left out the declaration of `secret`.)
43,999,809
When i add long text to my `TextView` in linear layout it takes up all the space, and other views get squeezed. I set `layout_width="0"` to every view but it did not help. I should also add that this layout is used in `RecyclerView`. Here is my code: ``` <?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:weightSum="100"> <TextView android:textSize="12sp" android:gravity="center" android:id="@+id/lp" android:layout_width="0dp" android:layout_height="match_parent" android:text="Lp" android:layout_weight="5" /> //this TextView takes all the space if text is long, but it behaves normally if text is short <TextView android:textSize="12sp" android:gravity="center" android:id="@+id/nazwa" android:layout_width="0dp" android:layout_height="match_parent" android:text="Końcówka Yankauer do odsysania pola operacyjnego CH 23 (4 otwory boczne) z kontrolą odsysania" android:layout_weight="20"/> <TextView android:textSize="12sp" android:gravity="center" android:id="@+id/ilosc" android:layout_width="0dp" android:layout_height="match_parent" android:text="#" android:layout_weight="5" /> <TextView android:textSize="12sp" android:gravity="center" android:id="@+id/jednostka" android:layout_width="0dp" android:layout_height="match_parent" android:text="JM" android:layout_weight="15" /> <TextView android:textSize="12sp" android:gravity="center" android:id="@+id/cenaNetto" android:layout_width="0dp" android:layout_height="match_parent" android:text="C. net." android:layout_weight="15" /> <TextView android:textSize="12sp" android:gravity="center" android:id="@+id/wartNetto" android:layout_width="0dp" android:layout_height="match_parent" android:text="W.net." android:layout_weight="15" /> <TextView android:textSize="12sp" android:gravity="center" android:id="@+id/wartVAT" android:layout_width="0dp" android:layout_height="match_parent" android:text="VAT" android:layout_weight="10" /> <TextView android:textSize="12sp" android:gravity="center" android:id="@+id/wartBrutto" android:layout_width="0dp" android:layout_height="match_parent" android:text="W. brut." android:layout_weight="15" /> </android.support.v7.widget.LinearLayoutCompat> ``` Here is a print screen of what breaks in my app [link](https://i.imgur.com/6zXPy8u.png)
2017/05/16
[ "https://Stackoverflow.com/questions/43999809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7988178/" ]
yes you can but it is recommended to use click event for clean code if you dont use event and you can do this with ``` if(IsPostBack) { //do something } ``` bu if you have multiple buttons you will add a condition for each button ``` if (IsPostBack) { string target = Request.Params["__EVENTTARGET"].ToString(); if (target == "send") { //do something } if (target == "update") { //do something } } ```
page\_load is a part of page life cycle you cannot exclude its execution you can only add checking for IsPostBack ``` if(!IsPostBack) { //Add Your Page Load Code Here } ```
67,050,552
There is an empty space to the left of the image and I don't know the reason. This is my HTML code for this section ```css #features{ background-color: #f9f6f7; } .featuresimg{ width: 40%; float: left; } ``` ```html <section id="features"> <img class="featuresimg" src="https://via.placeholder.com/1920x1080.jpg" alt="laptop"> <h3 class="featuresh">Free, open, simple</h3> <p class="featuresp">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure</p> <h3 class="featuresh">Powerful tooling</h3> <p class="featuresp">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim </p> </section> ``` ![enter image description here](https://i.stack.imgur.com/Z5y29.png)
2021/04/11
[ "https://Stackoverflow.com/questions/67050552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15584299/" ]
You could use a dictionary lookup: ```py def evaluate(a: int, b: int, operation: str): oper = { "+": a+b, "-": a-b, "*": a*b, "/": a/b, "%": a%b, "//": a//b } return oper.get(operation) ``` With a few test runs: ```py >>> evaluate(2, 5, "+") 7 >>> evaluate(2, 5, "-") -3 >>> evaluate(2, 5, "*") 10 >>> evaluate(2, 5, "bananas") None ```
Here is an option: ``` operator = input('Enter an operator: ') operators = '+-**/' if operator in operators: executable = f'print(2{operator}3)' exec(executable) ``` The program will ask for user input and then check if the input is in operators and if it is it will print out whatever result from using 2 and 3 and that operator. You can put pretty much any code in that `f string`. About security: As someone in the comments mentioned this isn't safe (the use of `exec()`)? Since I can only assume it is because then it is possible to run any code (including malicious) You can just filter what the user inputs. Here is probably an implementation to Your code (should use python 3.6 or higher or sth like that that supports `f strings`): ```py n = 5 i = 3 operator = '*' # main part ======================== result = None exec(f"""result = {n}{operator}{i}""", globals()) s = f'''{n} * {i} = {result}''' print(s) ``` However this doesn't seem as efficient as I thought at first so You probably are better of using the other answer with using dictionaries and defining a function.
68,664,807
I am trying to learn Spring Cloud Config. So first I setup a Server, where I can fetch the properties using `http://localhost:9090/config/default/master/app.static.properties` on the browser. It has about 5 or 6 properties. I am trying to get just one for now. I wrote my classes like: ``` package com.gcp.logicalprovisioning.config.server; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.context.annotation.Bean; @SpringBootApplication @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) public class DemoClientApplication { private static final Logger LOGGER = LoggerFactory.getLogger(DemoClientApplication.class); public static void main(String[] args) { SpringApplication.run(DemoClientApplication.class, args); } /** * Output property from cloud-config-server on startup of app, * * also can be seen at: * http://localhost:9090/env/APP.aaf.env */ @Bean public CommandLineRunner printProperties(@Value("${APP.aaf.env}") final String appProperty) { return args -> LOGGER.info("APP.aaf.env is: [{}]", appProperty); } } ``` and ``` package com.gcp.logicalprovisioning.config.server; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController // This will allow us to reinitialize this controller to get any new config // values when the /refresh endpoint is POSTed to. @RefreshScope public class DemoClientController { @Value("${APP.aaf.env}") private String appProperty; @RequestMapping("/") public String hello() { return "Using [" + appProperty + "] from config server"; } } ``` My bootstrap.properties look like: ``` spring.application.name=client spring.cloud.config.label=master spring.cloud.config.uri=http://localhost:9090/config/default/master/ spring.cloud.config.enabled=true spring.security.user.name=admin spring.security.user.password=admin logging.level.web=DEBUG debug=false spring.output.ansi.enabled=ALWAYS spring.devtools.restart.enabled=true spring.config.import=optional:configserver:http://localhost:9090/ spring.cloud.config.import-check.enabled=false ``` But I get this error: ``` org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'printProperties' defined in com.gcp.logicalprovisioning.config.server.DemoClientApplication: Unexpected exception during bean creation; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'APP.aaf.env' in value "${APP.aaf.env}" at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:537) ~[spring-beans-5.3.9.jar:5.3.9] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.9.jar:5.3.9] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.9.jar:5.3.9] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.9.jar:5.3.9] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.9.jar:5.3.9] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) ~[spring-beans-5.3.9.jar:5.3.9] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.9.jar:5.3.9] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.9.jar:5.3.9] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.5.3.jar:2.5.3] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) [spring-boot-2.5.3.jar:2.5.3] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:434) [spring-boot-2.5.3.jar:2.5.3] at org.springframework.boot.SpringApplication.run(SpringApplication.java:338) [spring-boot-2.5.3.jar:2.5.3] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) [spring-boot-2.5.3.jar:2.5.3] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1332) [spring-boot-2.5.3.jar:2.5.3] at com.att.logicalprovisioning.config.server.DemoClientApplication.main(DemoClientApplication.java:20) [classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_281] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_281] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_281] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_281] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.5.3.jar:2.5.3] Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'APP.aaf.env' in value "${APP.aaf.env}" at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:180) ~[spring-core-5.3.9.jar:5.3.9] at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126) ~[spring-core-5.3.9.jar:5.3.9] at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:239) ~[spring-core-5.3.9.jar:5.3.9] at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210) ~[spring-core-5.3.9.jar:5.3.9] at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.lambda$processProperties$0(PropertySourcesPlaceholderConfigurer.java:175) ~[spring-context-5.3.9.jar:5.3.9] ``` I searched for the problem on StackOverflow, found a few solutions, tried it. But nothing worked. But since I am getting my feet wet, I am not exactly sure what is going wrong. Am I missing some extra configuration? Any help would be appreciated. I haven't posted my server's code, if needed let me know, I will add it.
2021/08/05
[ "https://Stackoverflow.com/questions/68664807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1047226/" ]
Please note that Spring Cloud Config Server client will build the full path to your application's profile specific configuration for you. Therefore, you should only provide the base URL in `bootstrap.properties`. In your case this would be probable some like this: ``` spring.cloud.config.uri=http://localhost:9090/ ```
Yes, as suggested by Gregor Zurowski you can use Native profile and provide appropriate naming for the properties/yaml file containing the properties. Note: the Spring Cloud Config Server should provide "spring.cloud.config.server.native.search-locations" if you are using native based profile.
7,069,565
Here is [a sample from Allegro5 tutorial:](http://wiki.allegro.cc/index.php?title=Allegro_5_Tutorial/Events) (to see the original sample, follow the link, I've simplified it a bit for illustratory purposes. ``` #include <allegro5/allegro.h> int main(int argc, char **argv) { ALLEGRO_DISPLAY *display = NULL; ALLEGRO_EVENT_QUEUE *event_queue = NULL; al_init() display = al_create_display(640, 480); event_queue = al_create_event_queue(); al_register_event_source(event_queue, al_get_display_event_source(display)); al_clear_to_color(al_map_rgb(0,0,0)); al_flip_display(); while(1) { ALLEGRO_EVENT ev; ALLEGRO_TIMEOUT timeout; al_init_timeout(&timeout, 0.06); bool get_event = al_wait_for_event_until(event_queue, &ev, &timeout); //-->// if(get_event && ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { //-->// break; //-->// } al_clear_to_color(al_map_rgb(0,0,0)); al_flip_display(); } al_destroy_display(display); al_destroy_event_queue(event_queue); return 0; } ``` If I don't manually check for the `ALLEGRO_EVENT_DISPLAY_CLOSE`, then I can't close the window or terminate the program (without killing the process through task manager). I understand this. But in this case I don't understand how the minimize button works without me manually handling it. Can someone please explain?
2011/08/15
[ "https://Stackoverflow.com/questions/7069565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/469935/" ]
Disclaimer: I don't know Allegro. Minimizing a window at the most basic level only involves work from the process that deals with the windows (the Window Manager), not the process itself. Terminating a program, usually requires files to be closed or memory to be freed or something else that only the process itself can do.
The biggest reason that you must handle it yourself via an event is that closing (destroying) a window invalidates the `ALLEGRO_DISPLAY *` pointer. The request to terminate the window comes from a different thread, so it would be unsafe to destroy it immediately. Allowing you to process it yourself on your own time is safe and easy, and fits in with the event model that Allegro 5 uses for all other things. There are other ways to solve the problem, but they are no more simple than this method and don't really have any major advantages.
23,034,752
I get the following error when pulling a image ``` docker pull ubuntu Pulling repository ubuntu c0fe63f9a4c1: Error pulling image (latest) from ubuntu, read tcp 162.159.253.251:443: connection reset by peer e20bcab99567: Error pulling image (lucid) from ubuntu, unexpected EOF f697cdc2ef19: Error pulling image (quantal) from ubuntu, flate: read error at offset 806906: read tcp 162.159.253.251:443: connection reset by peer 25593492b938: Error pulling image (saucy) from ubuntu, read tcp 162.159.253.251:443: connection reset by peer ab4344e23e3a: Error pulling image (13.04) from ubuntu, flate: read error at offset 585714: read tcp 162.159.253.251:443: connection reset by peer 511136ea3c5a: Download complete 9a8b9d29f4fc: Download complete 01bdd5cc09de: Download complete 13dec63ebd94: Error downloading dependent layers 6170bb7b0ad1: Download complete 79fdb1362c84: Error downloading dependent layers 1c7f181e78b9: Download complete d0732e6ce563: Error downloading dependent layers f323cf34fd77: Download complete 9109d385566e: Error downloading dependent layers 2014/04/13 04:21:18 Could not find repository on any of the indexed registries. ```
2014/04/12
[ "https://Stackoverflow.com/questions/23034752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355634/" ]
How fast is your internet connection? I got the same error and believe it to be associated with a timeout because of slow internet. Multiple attempts worked...
Try running it as root. I am getting the same error when running the command as a non-privileged user. When I ran it as root, it worked fine. ``` sudo docker pull ubuntu ```
40,112,681
When using Fetch to download a url from Teamcity I get a Fetch failed! error. But the download of the file actually works. They have recently changed permissions of our Teamcity server so i've to use a username and password when obtaining the URL of the file to download. I'm just wondering if this is causing an issue with fetch's validation of the Gateway, but as I can download the file. Is there a way to suppress this error or just downgrade it to a warning? ``` Perl Code: my $ff = File::Fetch->new(uri => "$uri"); my $where = $ff->fetch ( to => "$DOWNLOAD_LOCATION" ); print Dumper($ff); Output: Fetch failed! HTTP response: 502 Bad Gateway [502 notresolvable] at <path>\myfile.pl line 249. Dumper Output: $VAR1 = bless( {'vol' => '', 'file_default' => 'file_default', '_error_msg' => 'Fetch failed! HTTP response: 502 Bad Gateway [502 notresolvable]', 'file' => 'myfilename.zip', 'scheme' => 'http', 'path' => '/repository/download/buildlabel/1042086:id/', '_error_msg_long' => 'Fetch failed! HTTP response: 502 Bad Gateway [502 notresolvable] at C:/Perl/lib/File/Fetch.pm line 598. ```
2016/10/18
[ "https://Stackoverflow.com/questions/40112681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2413767/" ]
The format argument belongs in the `date` function, not in `strtotime`. And you need to eliminate the single quotes around `$traveltime`, or you'll just be evaluating the literal string '$traveltime'. Also, the `%` characters shouldn't be used in the format string. Those are used for `printf`, etc. and aren't required here. ``` $contraveltime = date("H:i", strtotime($traveltime)); ```
Its show error because date function first parameter must date format but you given strtotime function for correct result please follow below code ``` $traveltime = "11:00 PM"; $contraveltime = date('H:i',strtotime($traveltime)); echo $contraveltime; ``` and out put will be like below code ``` 23:00 ``` now you store $contraveltime into database
2,936
Is it possible to test whether a token register is empty without expanding it?
2010/09/09
[ "https://tex.stackexchange.com/questions/2936", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/175/" ]
At time of writing the other TeX based answers on this page are flawed in that they hide a conditional `\ifx` inside a macro but still use `\else`/`\fi` at the "top" level. This will mean that things break unexpectedly when used inside other conditionals. The LaTeX3 programming language expl3 contains a module for doing stuff with token registers: ``` \usepackage{expl3} ... \ExplSyntaxOn \toks_if_empty:NTF \mytoks {true} {false} \ExplSyntaxOff ``` It essentially does internally what the other answers here are suggesting, but it uses expansion to grab its arguments so the branching is robust (and you don't have `\fi` lying around to get in your way). **Update**: So what does this approach do that is superior to other methods? Consider the style of solution first offered in answer to this question: ``` \def\IfEmpty#1{% \edef\1{\the#1} \ifx\1\empty } ... \IfEmpty\foo T\else F\fi ``` This doesn't behave nicely when nested, because TeX scans ahead when discarding unfollowed branches of a conditional. Consider ``` \ifx\bar\baz \IfEmpty\foo T\else F\fi % <- uh oh \else E \fi ``` If `\bar` = `\baz`, then the second branch is discarded and the first branch is executed. So far so good. If `\bar` ≠ `\baz`, then the first branch is discarded by reading ahead until the first unmatched `\else` — and this is the one in the line labelled "uh oh" above. So you could collapse the expansion of the above snippet in this case to: ``` \iffalse\else F\fi % <- uh oh \else E \fi ``` and hence the cause of the ‘Extra `\else`’ error message in this case. So this form for conditionals doesn't work so well. Next try. You can also write this style of code like this: ``` \def\IfEmpty#1#2#3{% \edef\1{\the#1} \ifx\1\empty #2% \else #3% \fi } ``` This avoids the problems of nesting as in the previous trial solution, but it's prone to another problem: `#2` and `#3` have trailing material behind them, namely `\else` and `\fi`. This is a problem if you want to write something like ``` \def\processfoo#1{...something with #1...} \IfEmpty\foo{\error}{\processfoo} {arg} ``` because the `#1` passed to `\processfoo` will be `\fi` instead of the desired `{arg}`. The conditional in this case is better written as ``` \def\IfEmpty#1#2#3{% \edef\1{\the#1} \ifx\1\empty \expandafter\@firstoftwo \else \expandafter\@secondoftwo \fi {#2}{#3} } ``` so overcome this problem. This is how expl3 conditionals work, and it's why we're writing `TF` at the end of all their names to indicate "true" and "false" branches. (Or just `T` or just `F` if you only want one of them.) Incidentally, there are expandable tests for checking for emptiness, which is why I suggest using the expl3 approach for this test. Expandability is not always required, of course, but code that is fully expandable tends to be more reliable and it's always nice to have for cases such as ``` \typeout{ \toks_if_empty:NT \foo {Warning:~\string\foo\space is~ empty} } ```
Ulrich Diez regularly posts on `comp.text.tex` some code along the following lines (slightly modified by me for toks): ``` \newcommand\@ifempty@toks[1]{% \ifcat\relax\detokenize\expandafter{\the#1}\relax \expandafter\@firstoftwo \else \expandafter\@secondoftwo \fi } ``` Or, without using e-TeX, ``` \newcommand\@ifempty@toks[1]{% \ifcase\iffalse{{{\fi\expandafter\@ifempty@@toks\the#1}1}1}0 \expandafter\@firstoftwo \else \expandafter\@secondoftwo \fi} \newcommand{\@ifempty@@toks} {\expandafter\@gobble\expandafter{\expandafter{% \ifcase`}\expandafter}\expandafter\fi\string} ``` EDIT: Ulrich Diez rightfully points out that redefining `\relax` can make the first test fail. It is slightly safer to use a character token like `$` or `X` that has category code among 3,4,7,8,11. Additionally, neither method works if the `\toks` contains outer macros, as in `\outer\def\foo{} \newtoks\mytoks \mytoks=\expandafter{\noexpand\foo}`.
126,739
For some reason our office linux box is being assigned an ip address via dhcp and I don't know why. What is confusing to me is that when I check system-config-network it shows that my eth0 is setup to be a static ip address. And /etc/sysconfig/network-scripts/ifcfg-eth0 also shows it is setup to be a static ip, yet it is getting a different ip address than the one specified in the ifcfg-eth0. Let me know if you have any suggestions on or ideas on where I can look next. Here are a few details that might help you figure out what an idiot I am :) Fedora 11 Router in front of this box is running dhcp, starting at 10.42.1.100 This box is configured to be 10.42.1.50 (at least I think it is!), subnet 255.255.255.0 (which is same as the router's lan subnet) Instead of having the static IP, this box is getting assigned 10.42.1.100. Here are the ifcfg-eth0 details ``` DEVICE=eth0 BOOTPROTO=none ONBOOT=yes TYPE=Ethernet USERCTL=no NM_CONTROLLED=no NETMASK=255.255.255.0 IPADDR=10.42.1.50 GATEWAY=10.42.1.1 ```
2010/03/26
[ "https://serverfault.com/questions/126739", "https://serverfault.com", "https://serverfault.com/users/38919/" ]
Here's a list of parameters that I would like to have you amend: 1. *BOOTPROTO=static* 2. Remove the NM\_Controlled parameter, or at least comment it out. Execute 'service network restart' or '/etc/init.d/network restart' and it should work. Otherwise, you may have to reboot the system and check the relevant log files for further diagnosis.
``` DEVICE=eth0 BOOTPROTO=static ONBOOT=yes TYPE=Ethernet USERCTL=no #NM_CONTROLLED=no (delete) NETMASK=255.255.255.0 IPADDR=10.42.1.50 GATEWAY=10.42.1.1 service network restart chkconfig network on chkconfig dhcpd off ```
9,448,145
I guess there is problem with the relation of malloc and goto. Or, I guess there is some wastage of memory or corruption of memory happening out here. Hope, someone can point to me the exact error. When I compile its not giving me any error, but, my senior is insisting that I have a mistake. ``` #define FINISH() goto fini; BOOL Do() { BOOL stat; UINT32 ptr; int err; ptr = (UINT32)malloc(1000); free((void*)ptr); fini: return stat; } ```
2012/02/25
[ "https://Stackoverflow.com/questions/9448145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/963182/" ]
Here are the problems I spotted in the code * When `err != ERROR_SUCCESS` this function will leak memory. It will jump over the `free` call. * You are storing the return of `malloc` into a 32 bit location. This is not a portable solution. On 64 bit platforms this will wreak havoc on your program as you'd be truncating the address. If you must use a non-pointer type here use `size_t` instead (although I would reccomend a pointer over an integral type) * The local `stat` is not definitively assigned here. You are returning garbage if `err != ERROR_SUCCESS`. It needs to always be assigned a value. Easiest way is provide a default. * You don't check the return value of `malloc` and potentially pass a hidden `NULL` pointer into `Fun2` Here's the function with the edits I suggested ``` BOOL Do() { BOOL stat = FALSE; size_t ptr = 0; int err; ptr = (UINT32)malloc(1000); err = Fun1(); if (err != ERROR_SUCCESS || ptr == 0) FINISH(); else stat = Fun2(ptr); fini: free((void*)ptr); return stat; } ```
Whatever you do, you are not compiling that code. It has a syntax error. ``` if(foo) bar;; else baz ``` Check your build system.
67,596,745
This is the input I am using for logstash. ``` ItemId,AssetId,ItemName,Comment 11111,07,ABCDa,XYZa 11112,07,ABCDb,XYZb 11113,07,ABCDc,XYZc 11114,07,ABCDd,XYZd 11115,07,ABCDe,XYZe 11116,07,ABCDf,XYZf 11117,07,ABCDg,XYZg Date,Time,Mill Sec,rows,columns 19-05-2020,13:03:46,534,2,2 19-05-2020,13:03:46,539,2,2 19-05-2020,13:03:46,544,2,2 19-05-2020,13:03:46,549,2,2 19-05-2020,13:03:46,554,2,2 ``` I need to remove first 8 lines from the csv and make the next line as column header and parse rest of lines as usual. Is there a way to do that in logstash?
2021/05/19
[ "https://Stackoverflow.com/questions/67596745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15967440/" ]
You could do this using the file input and then read it line by line using grok to make sure it has the right amount of fields comma separated and ignore the header one Your input will look like this: ``` input { file { path => "/path/to/my.csv" start_position => beginning } } ``` This will read each line into an event with the data in the field named message and then send it to your filters. In your filter you'll use grok with a pattern like this: ``` filter { grok { match => { "message" => [ "^%{DATE:Date},%{TIME:Time},%{NUMBER:Mill_Sec},%{NUMBER:rows},%{NUMBER:colums}$" ] } } } ``` This will present each line as an event looking like this: ``` { "colums": "2", "Time": "13:03:46", "Mill_Sec": "554", "rows": "2", "Date": "19-05-2020" } ``` You can use mutate to remove unwanted fields (like message) prior to going to your output part. If there is no match with the pattern defined you'll get a tag with the value `_grokparsefailure` in your tags, you can use that to decide to send it to your output or not. As you defined that it has to be numbers, it will also fail on the header one and thus leave you with only 'real' events. This can be done by having your output defined like this: ``` output { if "_grokparsefailure" not in [tags] { elasticsearch { ... } } } ```
You should do this before the file gets to Logstash. There *are* ways to do it within Logstash, for example by using a `mutliline` code then doing exotic `grok` matches to remove the first N lines (or removing lines until a particular regex), then doing a `split` followed by a plain ol' `csv` filter. You need to be even more careful than usual with header rows. It's a big mess. Much better to put something in front of Logstash to handle this issue. If the files are local to your logstash instance, you could use the [Exec input plugin](https://www.elastic.co/guide/en/logstash/current/plugins-inputs-exec.html) to deal with the irregularities. ```rb input { exec { command => "/path/to/command_or_script" # sh or py or js etc interval => 60 } } ``` On Linux, this `command` will print a file from the 8th line on... ``` command => "tail +8 /path/to/file" ``` This one (again for Linux) will drop everything until a line that starts with `date`, and print everything after that ``` command => "sed -n -e '/^date/,$p' /path/to/file" ``` You can avoid read the same file over and over again by deleting or archiving it in a script (rather than a one-liner as used in these examples) After trimming the unwanted leading lines, you should be able to use the `csv` filter in a normal way. Note that if you want to `autodetect_column_names` that pipeline workers must be set to 1.
32,122,794
I'm just starting with Meteor. In an app which is to be localized, I want to set the document title. I am following the [advice given by Bernát](https://stackoverflow.com/a/19010848/1927589) In my barebones version, I have just 2 documents: head.html ``` <head> <meta charset="utf-8"> <title>{{localizedTitle}}</title> </head> ``` ui.js ``` UI.registerHelper("localizedTitle", function() { var title = "Localized Title" document.title = title; }); ``` When the app loads, the document title is "{{localizedTitle}}". If I call `UI._globalHelpers.localizedTitle()` from the console, the correct title is shown. What do I have to do to get the localized title to show when the page is loaded? --- EDIT: This works for me, but it seems to be a bit of a hack. The `title` template does nothing but get itself rendered, which actually adds nothing to the interface. body.html ``` <body> {{> title}} </body> <template name="title"> </template> ``` title.js ``` Template.title.onRendered(function () { document.title = getLocalizedString() function getLocalizedString() { return "Title : in English" } }) ```
2015/08/20
[ "https://Stackoverflow.com/questions/32122794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1927589/" ]
Following Bernát's answer, your global helper should not be called in the head's `<title>` tag, but within the `<template>` tag of the template where you wish to have a given title. In Meteor, `<head>` does not count as a template, therefore you cannot use Spacebars notation in it: it will just be considered as simple text. Also, keep in mind that your helper will not return (i.e. print) anything to the page. `document.title = "something"` directly assigns "something" to your ` tag. So no need to call your helper inside it! So, say you want to have the "Localized Title" title for a page using the `localized` template : ``` <template name="localized"> <h1>This is the localized page</h1> {{localizedTitle}} </template> ``` Here, your trick should work.
I think a more elegant solution is to make the title reactive and set it via a Session variable (other reactive data sources are of course also OK). Like that: ``` Template.body.onRendered(function() { this.autorun(function() { document.title = Session.get('documentTitle'); }); }); ``` Now every time you set the 'documentTitle' variable with ``` Session.set('documentTitle', 'Awesome title'); ``` the page title will change. No need for hacks and you can do this anywhere in your client code.
24,928
It is an age old question. How can I ensure that the chocolate in a s'more is properly melted. Even when assembling them quickly the marshmallow just doesn't have enough heat to melt the chunk of chocolate. Any solutions are welcome but I would especially like to know how to do it with no special tools- just a campfire and a stick.
2012/07/09
[ "https://cooking.stackexchange.com/questions/24928", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/2001/" ]
Microwave the chocolate **first** in a microwaveable bowl, *then* heat the 'mellows and the crackers, before putting it all together. It's what I call "indoor s'mores".
I think Hershey changed something in their recipe to keep chocolate from melting too quickly in the sun/heat. Back in 1970 the chocolates melted just fine in Girl Scouts.
117,005
Related: [If I cast Banishment on myself while in a demiplane, where exactly do I exit?](https://rpg.stackexchange.com/questions/116960/if-i-cast-banishment-on-myself-while-in-a-demiplane-where-exactly-do-i-exit) If I am trapped in the extradimensional space of a [bag of holding](https://www.dndbeyond.com/magic-items/bag-of-holding), can I escape by casting *[Banishment](https://www.dndbeyond.com/spells/Banishment)* on myself? Is the space inside of a bag of holding considered to be a plane with respect to this spell, or is it more a place that is not part of any plane?
2018/03/08
[ "https://rpg.stackexchange.com/questions/117005", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/30877/" ]
Yes, Banishment will let you escape =================================== Demiplanes are discussed in the DMG in the chapter on planes, under the “Other Planes” heading — a demiplane is absolutely a plane in its own right. And “extradimensional space” and “demiplane” mean the same thing, per that section (DMG, p. 68): > > Other Planes > ------------ > > > […] > > > ### Demiplanes > > > Demiplanes are extradimensional spaces that come into being by a variety of means and boast their own physical laws. > > > (For more discussion of the nature of the things called demiplanes/extradimensional spaces/pocket dimensions, see [this question on that exact subject](https://rpg.stackexchange.com/questions/105928/is-the-pocket-dimension-a-familiar-goes-into-a-demiplane-or-an-extradimensiona).) Basically, everywhere in the D&D cosmos is a plane of some kind or part of a plane. Extradimensional spaces must exist somewhere, are explicitly *not* part of other planes (*ibid.*); therefore all extradimensional spaces are demiplanes (by the process of elimination), and planes in their own right. Magic items that connect to demiplanes are better thought of as keys or gates to another plane. And we know that [if you cast Banishment in a demiplane, the target goes back to its home plane](https://rpg.stackexchange.com/questions/98036/what-does-the-banishment-spell-do-inside-a-demiplane) (to an unpredictable location), and [you can cast Banishment on yourself](https://rpg.stackexchange.com/questions/47436/can-you-cast-banishment-on-yourself). So unless you're a native to *that bag's* demiplane, yes, casting Banishment will let you escape. However, be prepared to show up [*anywhere* on your native plane](https://rpg.stackexchange.com/questions/116960/if-i-cast-banishment-on-myself-while-in-a-demiplane-where-exactly-do-i-exit). If you native plane is very large, you might end up escaping into an even more difficult predicament.
It works... ----------- It doesn't matter if it is a demiplane or not. Spells do what they say. The spell *[banishment](https://www.dndbeyond.com/spells/banishment)* doesn't say you have to be on a plane or demiplane for it work, it just says: > > If the target is native to a different plane of existence that the one you’re on... > > > [The Handy Haversack](https://www.dndbeyond.com/magic-items/handy-haversack) description makes it clear that the inside of a bag of holding is extradimensional space: > > Placing the haversack inside an extradimensional space created by a bag of holding... > > > The inside is clearly in extradimensional space. Extradimensional means outside of dimensions, that is, it is not on the prime material plane. If you are in extradimensional space, you not on the prime material plane. When banished, you'll return to the prime material, if that is the plane to which you are native. Where to? --------- > > ... the target is banished with a faint popping noise, **returning to its home plane**. > > > which would mean anywhere the DM wants to place the target in the prime material plane. P.S. It is a Demiplane ---------------------- The DMG stats the definition of Demiplane as: > > Demiplanes are extradimensional spaces that come > into being by a variety of means and boast their own > physical laws. > > > We know from above it meets the first criteria, it is extradimensional space. The second criteria is that it has its own physical laws that are stated in the description. > > If the bag is overloaded, pierced, or torn... If the bag is turned inside out... Breathing creatures inside... (etc.) > > > Being an extradimensional space with its own physical laws makes it a demiplane. It goes on to say: > > Theoretically, a plane shift spell can > carry travelers to a demiplane, but the proper frequency > required for the tuning fork would be extremely hard to > acquire. The gate spell is more reliable, assuming the > caster knows of the demiplane. > > > Which just confirms the banishment statement from above.
46,939,059
I have below scenario. ``` list1=['10/22/2017 10:00','10/22/2017 10:00','10/22/2017 10:00', '10/22/2017 11:00','10/22/2017 11:00','10/22/2017 11:00', '10/22/2017 12:00','10/22/2017 12:00','10/22/2017 12:00', .... ] list2 = [1,2,5,4,5,3,3,5,6,......] #(list2 size will be equal to no. of unique elements of list1) ``` My question is how to display list3 which has values like below. ``` list3=[1,1,1, 2,2,2, 5,5,5, ...] ``` Means for no. of consecutive duplicate elements of list1, each list2 element should be appended into list3 that many times.
2017/10/25
[ "https://Stackoverflow.com/questions/46939059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6870043/" ]
My take using an OrderedDict: ``` >>> from collections import OrderedDict >>> list1 = ['a', 'a', 'b', 'b', 'c', 'c'] >>> list2 = [1, 2, 3] >>> dictionary = dict(zip(OrderedDict(zip(list1, list1)), list2)) >>> [dictionary[k] for k in list1] [1, 1, 2, 2, 3, 3] ``` This has the advantage of keeping a dictionary of the values so it is useful if you need to translate keys to values again. The trick is to create an ordered set (an special case of the OrderedDict) before pairing the two lists in a new dict.
I did a quick attempt using the idea of a counter that increments when the next element is different from the previous (I'm assuming the list is in order). It works for the values you put in, you'd need to double check on a full data set though: ``` list1=['10/22/2017 10:00','10/22/2017 10:00','10/22/2017 10:00', '10/22/2017 11:00','10/22/2017 11:00','10/22/2017 11:00', '10/22/2017 12:00','10/22/2017 12:00','10/22/2017 12:00' ] list2 = [1,2,5,4,5,3,3,5,6] list3 = [] previous = None counter = -1 for i in list1: if previous != i: counter += 1 list3.append(list2[counter]) previous = i print list3 #[1, 1, 1, 2, 2, 2, 5, 5, 5] ```
41,018,053
for a single dimensional array normally I would use a for loop like the one below but I can't think of a way to do this that doesn't involve lots of loops. ``` for (int i = 0; i < myArray.length; ++i) { myArray[i] = rnd.Next(1, 500); } ```
2016/12/07
[ "https://Stackoverflow.com/questions/41018053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4151152/" ]
You can try *low level* [Buffer.BlockCopy](https://msdn.microsoft.com/en-us/library/system.buffer.blockcopy(v=vs.90).aspx) to conceal the loop(s): ``` // N-D array (whatever dimensions) int[,,] array = new int[3, 5, 11]; Buffer.BlockCopy( Enumerable .Range(0, array.Length) .Select(x => rand.Next(0, 500)) .ToArray(), 0, array, 0, array.Length * sizeof(int)); // sizeof(int) : we copy bytes... ``` we create 1-D array ``` Enumerable .Range(0, array.Length) .Select(x => rand.Next(0, 500)) .ToArray() ``` with the total length of N-D one (`array.Length == array.Length(0) * ... * array.GetLEngth(N)`) and copy it into N-D one.
Use more than one loop: ``` for (int i = 0; i < myArray.Length; ++i) { for (int j = 0; j < myArray[i].Length; ++j) { myArray[i][j] = rand.Next(0, 500); } } ```
4,876,308
I have various important variables that I need transfering from PHP to JS on the same page load. I am currently storing these variables in DOM element attributes and using jQuery to grab them out. This works fine, although as some of the information is quite important I would rather this wasn't publicly visible in the DOM and 'hidden from prying eyes'. So my question is: How to you transfer variables to JS or the DOM from PHP and keep them hidden from sight? Cheers guys, hope you can help!
2011/02/02
[ "https://Stackoverflow.com/questions/4876308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/516629/" ]
use an ajax request on page load. Here is a shell for jQuery: ``` $(function() { $.ajax("http://yoursite.com/phpscript.php", { method: "post", dataType: "json", success: function(data) { // do what you will with the data here } }); }); ``` all information has to be downloaded to the person's computer at some point. You can keep it "hidden" in javascript but the end user can easily use firebug or something similar to view that data.
If the data is sensitive, there is no way to hand it over for client-side processing while keeping it secure. That simply isn't how the web works. Everything you hand over to the client must necessarily be readable by the client. You can use technologies like SSL to protect data from being intercepted, but the intended recipient must be able to read it. You should be processing any sensitive data server-side, and outputting only the results intended for public consumption. If you simply want to make data available to the page while hidding messy implementation details, there are many options: * use an `<input type="hidden" />` field * store your values directly in JavaScript by outputting something like `var myValue = <?= $serverside_value ?>` or using `json_encode` * request the values via AJAX
20,089,470
I have a basic Hibernate code, I have set the property "hibernate.hbm2ddl.auto" as update still it is not auto-creating the table in the Database. These are the required files: employee.hbm.xml ``` <hibernate-mapping> <class name="contacts.employee" table="contacts"> <meta attribute="class-description"></meta> <id column="contactId" name="contactId" type="string"> <generator class="assigned"/> </id> <property column="contactName" length="100" name="contactName" not-null="true" type="string"/> <property column="password" length="100" name="password" not-null="true" type="string"/> <set cascade="all" name="groupOfResponsibilities" table="employee_responsibilty"> <key column="contactId"/> <many-to-many class="contacts.responsibilities" column="responsibilityId"/> </set> </class> </hibernate-mapping> ``` responsibility.hbm.xml ``` <hibernate-mapping> <class name="contacts.responsibilities" table="responsibilities"> <meta attribute="class-description"> This class list of responsibilities if an employee </meta> <id column="responsibilityId" name="responsibilityId" type="long"> <generator class="increment"/> </id> <property column="responsibilityName" name="responsibilityName" type="string"/> </class> </hibernate-mapping> ``` hibernate.cfg.xml ``` <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/****</property> <property name="hibernate.connection.username">*****</property> <property name="hibernate.connection.password">*****</property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.show_sql">true</property> <mapping resource="contacts/employee.hbm.xml"/> <mapping resource="contacts/responsibilitiy.hbm.xml"/> </session-factory> </hibernate-configuration> ``` This is the Main.java that I am trying to run: ``` public class Main { public static void main(String[] args) { SessionFactory sessionfactory = NewHibernateUtil.getSessionFactory(); Transaction transaction = null; try { Session session = sessionfactory.openSession(); transaction = session.beginTransaction(); Set<responsibilities> groups = new HashSet<responsibilities>(); responsibilities responsibilityOne=new responsibilities("Java"); responsibilities responsibilityTwo=new responsibilities("SQL"); responsibilities responsibilityThree=new responsibilities("Oracle"); groups.add(responsibilityOne); groups.add(responsibilityTwo); groups.add(responsibilityThree); String uuid = UUID.randomUUID().toString(); String uuid2 = UUID.randomUUID().toString(); employee firstEmployee; firstEmployee = new employee(uuid, "Mike", groups); employee secondEmployee = new employee(uuid2, "Marc", groups); session.save(responsibilityOne); session.save(responsibilityTwo); session.save(responsibilityThree); session.save(firstEmployee); session.save(secondEmployee); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { } } } ``` This is the error that I get: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table '*\**\*.responsibilities' doesn't exist
2013/11/20
[ "https://Stackoverflow.com/questions/20089470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1787314/" ]
I had the same issue, but for me the solution was: ``` <property name="hibernate.hbm2ddl.auto">create-drop</property> ``` instead of ``` <property name="hibernate.hbm2ddl">create-drop</property> ```
Adding this in *application.properties* works for me ``` spring.jpa.generate-ddl=true ```
104,790
Did Rashi issue any halachic rulings? (Examples?) Or did he simply provide useful and succinct explanations, drawn from the Sources, for those studying Torah?
2019/06/13
[ "https://judaism.stackexchange.com/questions/104790", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/15154/" ]
This answer regards the Commentary of Rashi. The Shem hagedolim writes: > > מצאתי בספר כתב יד ישן נושן וזה לשונו ראש לכל החיבירים שנתחברו דרך פירוש הם פירושי הרב רבינו שלמה בר יצחק. ואם רבו הלוחמים עליו, כלי סיימו עליו ותשובתו מתוך דבריו כולם נכוחים למבין, אין מעלתו ניכרת רק ליחידים כי במילה אחת יכלול לפעמים תירוצים של חבילי קושיות אלא שלא כיון הרב בהם לענין פסק. עד כאן לשונו. והא דגמר אומר אלא שלא כיון הרב לפסק הלכה הכי חזיתיה לרדב''ז בתשובה חלק א'סימן ק''ט שכתב וזה לשונו כל שכן שיש בידנו כלל גדול כי רש''י מפרש הוא ולא פוסק ויותר יש לסמוך על בעלי הפסק. גם מרן בבית יוסף אורח חיים סימן י'כתב דרש''י מפרש הוא ולא פוסק עיין שם.ואל תתמה על החפץ דמי לנו גדול מרש''י ואיך הרדב''ז ומרן כתבו דיש לסמוך יותר על הפוסקים, כי עיניך לנכים יביטו דברי הרב בהם לענין פסק ותנוח דעתך, דהכוונה דרש''י עצמו עיקר כונתו לפרש ולא כיון לפסק. ומאחר בקבלה בידם דרש''י עצמו לא כיון לענין פסק אם כן שפיר קאמרי מרן והרדב''ז דיש לסמוך יותר על בעלי הפסק. וזה תלמוד ערוך פרק יש נוחלין... אמנם כאשר רש''י כותב בפירוש לענין פסק כמו באסור והיתר שלפעמים פוסק הדין בפירוש, אז ודאי דסברתו נחשבת כאחד מגדולי הפוסקים וזה ברור, וכן כתבתי במקום אחר ועיין בהלכות קטנות חלק ה' סימן קי''ז ובספר בית דוד חושן משפט סימן ה' אות ך' דיש חולקין בזה וכן הרב מעדני מלך הלכות ציצית אות ס''א חלק על מרן בזה דחש לרש''י שפירש הסוגיא אף על פי שהוא עצמו סובר שאינו אליבא דהלכתא, וכי לא יחוש לחורבא דנפיק מינה וכו' עיין שם. > > > Summary. Often Rashi addresses the psak clearly. Most times he only comments and we cannot be sure that he holds the Halacha as his comment. Radbaz and Bet Yosef s that commentary is not a psak. But some acharonim, the Rama mifano and Bet David hold that his comment has a strong halachic value.. Note. It's hard to think that the right pshat regarding the conclusion of the Gemara is not the right Halacha.
This [Halachipedia article](https://www.halachipedia.com/index.php?title=Rashi) notes that there are two halacha seforim by Rashi: one ("**Sefer HaPardes**") was written by him and the other ("**Sefer Likutei Pardes**") was his halachik rulings compiled by his talmidim. 1) **Sefer HaPardes** --------------------- ([hebrewbooks.org link](http://www.hebrewbooks.org/8962)) [![enter image description here](https://i.stack.imgur.com/PEDFa.png)](https://i.stack.imgur.com/PEDFa.png) --- 2) **Sefer Likutei Pardes** --------------------------- ([hebrewbooks.org link](http://www.hebrewbooks.org/1747)) [![enter image description here](https://i.stack.imgur.com/ZAG6w.png)](https://i.stack.imgur.com/ZAG6w.png)
73,526,599
I am building a system that recommends a book from a dataset based on what is best for the user. The problem is that not only 1 book is returned to me, but a lot of them come out. How can I solve? The code is this: ``` from sklearn.neighbors._classification import KNeighborsClassifier import pandas as pd class SuggestAudiobook: def __init__(self, book): model = KNeighborsClassifier() book = pd.read_csv("dataset.csv", delimiter = ";") var2 = book.Title var1 = book[["audioRuntime_converted", "category_converted"]] var2 = var2.astype('string') var1 = var1.astype('int') model.fit(var1, var2) dataframe = pd.DataFrame(data = {"audioRuntime_converted": book.audioRuntime_converted, "category_converted": book.category_converted}) predictionDataframe = model.predict(dataframe) print("L'audiobook recommended for you is --> ", predictionDataframe) ``` The result is this: ``` audiobook recommended for you is' --> ['Catching Fire' 'In Charge of Moonlight' 'Catching Fire' ... 'Born a Crime' 'Born a Crime' 'Born a Crime'] ``` I attach the images of the result obtained: [![enter image description here](https://i.stack.imgur.com/i0K9D.png)](https://i.stack.imgur.com/i0K9D.png) I'm going to recommend a book among those included in the dataset based on the data inputs. In this case the data inputs are: `audioRuntime_converted` and `category_converted` (they are found in the other file that calls the function). Then in the dataset I go to search based on those 2 fields. I am sure that the procedure is correct as applied in another project, only problem is the output which gives me more values ​​instead of one.
2022/08/29
[ "https://Stackoverflow.com/questions/73526599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19865911/" ]
You have multiple lines in your dataframe, the [`.predict()`](https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html#sklearn.neighbors.KNeighborsClassifier.predict) function will run for every line of your dataset. So `len(predictionDataframe) == len(dataframe)`
I solved. The solution was simpler than expected. I thank everyone for trying to help me. The problem was that at the beginning when I do `def_init`, in the parameters I passed `book` instead of `insertedbook`. It is the same when I create the dataframe
949,425
Find the number of integer solutions to the equation $x\_1 + x\_2 + x\_3 = 28$, where $ 3 \leq x\_1 \leq 9$, $0 \leq x\_2 \leq 8$, and $7 \leq x\_3 \leq 17$ I'm having problems with this question. 1) I first tried reducing the range of the variables to $ 0 \leq x\_1 \leq 6$,$0 \leq x\_2 \leq 8$ and $0 \leq x\_3 \leq 10$. 2) That means I have to find the number of integer solutions for $x\_1' + x\_2' + x\_3' = 18$ but I found I cannot reduce the ranges any further. I have been told to use GPIE (General Principle of Inclusion and Exclusion) in this question but I would like to see other approaches as well. The answer given is 28.
2014/09/28
[ "https://math.stackexchange.com/questions/949425", "https://math.stackexchange.com", "https://math.stackexchange.com/users/48907/" ]
The equation $$x\_1 + x\_2 + x\_3 = 28$$ with the restrictions $3 \leq x\_1 \leq 9$, $0 \leq x\_2 \leq 8$, and $7 \leq x\_3 \leq 17$ is equivalent to the equation $$y\_1 + y\_2 + y\_3 = 18$$ where $y\_1 = x\_1 - 3$, $y\_2 = x\_2$, and $y\_3 = x\_3 - 7$ with the restrictions $0 \leq y\_1 \leq 6$, $0 \leq y\_2 \leq 8$, and $0 \leq y\_3 \leq 10$. Let $z\_1 = 6 - y\_1$, $z\_2 = 8 - y\_2$, and $z\_3 = 10 - y\_3$. Then a solution to the equation $x\_1 + x\_2 + x\_3 = 28$ with the given restrictions is equivalent to a solution of the equation $$6 - z\_1 + 8 - z\_2 + 10 - z\_3 = 18$$ in the non-negative integers. Simplifying yields $$z\_1 + z\_2 + z\_3 = 6$$ The number of solutions of this equation is equal to the number of ways two addition signs can be placed in a list of six ones. For instance, the list $$+ 1 1 1 1 + 1 1$$ corresponds to the solution $z\_1 = 0$, $z\_2 = 4$, and $z\_3 = 2$. Thus, we are selecting $2$ of the $6 + 2$ symbols to be addition signs, which can be done in $$C(6 + 2, 2) = C(8, 2) = \frac{8!}{2!6!} = \frac{8 \cdot 7}{2 \cdot 1} = 28$$ ways.
Break it down into 7 cases, starting with $x\_1'=0$ Then you only have one choice for the other two numbers, as they need to be maximal, so you have 1 choice. Each time $x\_1'$ goes up by 1, you get one more potential choice for $x\_2',x\_3'$, so you get $1+2+3+4+5+6+7=28$ possibilities
19,867,389
How can I combine $regex with $in in PyMongo? I want to search for either `/*.heavy.*/` or `/*.metal.*/`. I tried in python without success: ``` db.col.find({'music_description' : { '$in' : [ {'$regex':'/*.heavy.*/'} ]} }) ``` The equivalent in Mongo shell is: ``` db.inventory.find( { music_description: { $in: [ /heavy/, /metal/ ] } } ) ```
2013/11/08
[ "https://Stackoverflow.com/questions/19867389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1447885/" ]
Use python regular expressions. ``` import re db.col.find({'music_description': {'$in': [ re.compile('.*heavy.*'), re.compile('.*metal.*')]}}) ```
Why even bother using an $in? You're wasting processing by evaluating the field for each value within the list, and since each value is a regex it has its own performance considerations, Depending on how long your query strings get, it might be prudent just to wrap them up in one regex and avoid the $in query all together ``` import re db.col.find({'music_description': re.compile('heavy|metal')}) ``` similarly in mongo shell ``` db.inventory.find({music_description: /heavy|metal/}) ``` as for [user2998367]'s answer, you're wasting efficiency compiling a regex with greedy wildcards for the sole purpose of a match, the difference between re.search and re.match in python requires the use of the wildcards for re.search purposes, but re.match behaves as 'anywhere in string', as does MongoDB, its only really needed if you're intending to extract, which you'd need to do later after querying anyhow, or if you're reusing a compiled regex somewhere else that you specifically need re.search over re.match
14,650,411
In my windows phone 8 app I need to have a few UserControl which all of them have same functions (only the header not the body). I am wondered if i can have some thing like interface so i can inherit from that? (i could do it in ios with UIViewController)
2013/02/01
[ "https://Stackoverflow.com/questions/14650411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989027/" ]
If you're extending the same basic idea you may be best to look at creating a Custom Control and then adding what your body as Content inside it the control. You can then re-skin your custom control as you need in each case (and learn more about how controls work as a side-effect). It's a bit more work than creating a UserControl, but it sounds appropriate for what you're doing and is the idiomatic way of solving this kind of problem in XAML/.NET (WP, Windows Store, WPF). There is a good article on the differences between User Control and Custom Controls on [WindowsPhoneGeek](http://www.windowsphonegeek.com/articles/User-Control-vs-Custom-Control-in-Silverlight-for-WP7).
``` public abstract class MasterUserControl : UserControl { [...] } public class MyUserControl : MasterUserControl { } ``` Something like that?
34,587,282
I'm using VSTS as a build server, and while building I want to copy the bin folder contents to the root of the target, and also custom files from another folder to this target. [MSDN](https://msdn.microsoft.com/Library/vs/alm/Build/steps/build/publish-build-artifacts) suggests I use a minimatch pattern, but it's copying files with the subdirectory structure. I'm not interested in restoring the structure. For example, I am getting this folder structure: ``` Project MyProjectFiles bin x86 (it's build configuration) Project.exe Other project files Project.sln SomeScrips script1.ps1 ``` But I want to receive this folder structure: ``` Project.exe SomeScripts script.ps1 ``` Which minimatch pattern can I use for my requirements?
2016/01/04
[ "https://Stackoverflow.com/questions/34587282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1661966/" ]
For those who would like to have a PowerShell script to use in your build server, here is a working (at least, on my build server ;)) sample: ``` param ( [string] $buildConfiguration = "Debug", [string] $outputFolder = $PSScriptRoot + "\[BuildOutput]\" ) Write-Output "Copying all build output to folder '$outputFolder'..." $includeWildcards = @("*.dll","*.exe","*.pdb","*.sql") $excludeWildcards = @("*.vshost.*") # create target folder if not existing, or, delete all files if existing if(-not (Test-Path -LiteralPath $outputFolder)) { New-Item -ItemType Directory -Force -Path $outputFolder | Out-Null # exit if target folder (still) does not exist if(-not (Test-Path -LiteralPath $outputFolder)) { Write-Error "Output folder '$outputFolder' could not be created." Exit 1 } } else { Get-ChildItem -LiteralPath $outputFolder -Include * -Recurse -File | foreach { $_.Delete() } Get-ChildItem -LiteralPath $outputFolder -Include * -Recurse -Directory | foreach { $_.Delete() } } # find all output files (only when in their own project directory) $files = @(Get-ChildItem ".\" -Include $includeWildcards -Recurse -File | Where-Object {( $_.DirectoryName -inotmatch '\\obj\\' -and $_.DirectoryName -inotmatch '\\*Test*\\' -and $_.DirectoryName -ilike "*\" + $_.BaseName + "\*" -and $_.DirectoryName -ilike "*\" + $buildConfiguration )} ) # copy output files (overwrite if destination already exists) foreach ($file in $files) { Write-Output ("Copying: " + $file.FullName) Copy-Item $file.FullName $outputFolder -Force # copy all dependencies from folder (also in subfolders) to output folder as well (if not existing already) $dependencies = Get-ChildItem $file.DirectoryName -Include $includeWildcards -Exclude $excludeWildcards -Recurse -File foreach ($dependency in $dependencies) { $dependencyRelativePathAndFilename = $dependency.FullName.Replace($file.DirectoryName, "") $destinationFileName = Join-Path -Path $outputFolder -ChildPath $dependencyRelativePathAndFilename if (-not(Test-Path -LiteralPath $destinationFileName)) { Write-Output ("Copying: " + $dependencyRelativePathAndFilename + " => " + $destinationFileName) # create sub directory if not exists $destinationDirectory = Split-Path $destinationFileName -Parent if (-not(Test-Path -LiteralPath $destinationDirectory)) { New-Item -Type Directory $destinationDirectory } Copy-Item $dependency.FullName $destinationDirectory } else { Write-Debug ("Ignoring (existing destination): " + $dependency.FullName) } } } ``` Here is the script being used in a PowerShell build step: [![TFS 2015 Build - Output to single folder step](https://i.stack.imgur.com/mlGWB.png)](https://i.stack.imgur.com/mlGWB.png)
Make artifacts of each file you want to copy. Then create a 'copy file' task of each file of these artifacts. Then it doesn't copy the source tree structure.
26,880,914
I tried to customize spinner as follows where image is a 9 patch image. ``` <Spinner android:layout_width="fill_parent" android:layout_height="50dp" android:id="@+id/spinner" android:textSize="20sp" android:background="@drawable/image" /> ``` The result is this: [Spinner screenshot](https://drive.google.com/file/d/0B-esql9qpq7HeXpfdDVId0tMWUE/view?usp=sharing) The text is completely hidden by the image. How to make the text visible? Edit: I verified that I can see the text on spinner if I use the [image1](http://4.bp.blogspot.com/-gZRWCmgm6Zg/T3H-6sAuq3I/AAAAAAAAABo/51S8pNB9yrQ/s1600/btn_dropdown_normal.9.png). But if I use this [image2](https://drive.google.com/file/d/0B-esql9qpq7HVndNU0JqeVowWUU/view?usp=sharing) (created by yours truly) then I cannot see the text. Seems something is wrong with my 9 patch image. But I can't figure out what ?
2014/11/12
[ "https://Stackoverflow.com/questions/26880914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3459908/" ]
There is really nothing wrong in setting the spinner background directly as I have done. Of course you cannot have different "states" of the spinner then. The text was not visible because the 9 patch image was corrupted for some unknown reason. I recreated the image and I can see the text on the spinner now. One more thing: the text will not be visible if "content areas" are not defined on the 9 patch.
You need to set background of spinner as follows: In your layout xml : ``` <Spinner android:id="@+id/spinner1" style="@style/spinner_style" android:layout_width="match_parent" android:layout_gravity="center_vertical" android:gravity="center_vertical" android:layout_height="45dp" /> ``` Now in style.xml add a style for spinner as follows: ``` ` <style name="spinner_style"> <item name="android:background">@drawable/spinner_bg</item> <!-- <item name="android:layout_marginLeft">10dp</item> <item name="android:layout_marginRight">10dp</item> <item name="android:layout_marginBottom">10dp</item> <item name="android:paddingLeft">8dp</item> <item name="android:paddingTop">5dp</item> <item name="android:paddingBottom">5dp</item> --> <item name="android:paddingLeft">5</item> </style>` ``` Now make a xml named spinner\_bg.xml in drawable : ` ``` <item><layer-list> <item><shape> <gradient android:angle="90" android:endColor="@android:color/transparent" android:startColor="@android:color/transparent" android:type="linear" /> <padding android:left="2dp" android:right="2dp" /> </shape></item> <item> <bitmap android:gravity="center_vertical|left" android:src="your background drawable for spinner here" /> </item> </layer-list></item> ``` ` According to your question, below part of spinner\_bg.xml did the trick. ``` `<item> <bitmap android:gravity="center_vertical|left" android:src="your background drawable for spinner here" /> </item>` ``` Thats it.
17,244,745
So I want to be able to hide all the options and then show only the ones that don't include `hello_` in their value. This includes `hello_bye`, `hello_hello` etc. Anything that starts with `hello_` This is what I have so far: ``` jQuery(document).ready(function(){ jQuery("#metakeyselect > option").hide(); jQuery("#metakeyselect > option[//what goes here?//]").show(); }); ``` How do I show everything BUT options with values including hello\_?
2013/06/21
[ "https://Stackoverflow.com/questions/17244745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1555312/" ]
You can "hide" the ones whose value start with `hello_` using the [*attribute-starts-with* selector](https://stackoverflow.com/users/2464706/alex-morrise). As [Alex](https://stackoverflow.com/users/2464706/alex-morrise) pointed out correctly, not all browsers let you hide option elements though (see also [How to hide optgroup/option elements?](https://stackoverflow.com/q/2731668)). But you can remove them: ``` var hidden_options = jQuery("#metakeyselect > option[value^=hello_]").remove(); ``` or disable them: ``` jQuery("#metakeyselect > option[value^=hello_]").prop('disabled', true); ``` depending on what else you want to do with them.
You can use: ``` $(document).ready(function(){ var options = $('#metakeyselect > option'); var contains = "hello_"; options.each(function() { if($(this).val().indexOf(contains) != -1){ $(this).remove(); } }); }); ``` OR ``` $(document).ready(function(){ $("#metakeyselect > option").remove(); $("#metakeyselect > option[value*='hello_']").show(); }); ``` You will need to use remove() for options.
21,251,435
let me start by saying that I have no idea how to formulate this question, I have spend the last two days looking for some ways to to the following. I send some information encoded using base64 as follow.... Values are: **Lóms Gruñes** this values came from an input box beacuse of that I do this **$name = htmlentities(( $\_POST ['name'] ) , ENT\_NOQUOTES, 'UTF-8');** **$midn = htmlentities(( $\_POST ['midn'] ) , ENT\_NOQUOTES, 'UTF-8');** the output for this should be ``` L&oacute;ms Gru&ntilde;es ``` And that is what gets encode, until that everything is fine, and I can do whatever I need with that, in this case I'm going to encode it using base64 ``` $datas ='&name='. $name .'&midn='. $midn; $bd = base64_encode($datas); // Now lets send that info to another file.. header( 'Location: other.php?d=$db' ) ; ``` So the url will be something like **domain.com/other.php?d=TCZvYWN1dGU7bXMgR3J1Jm50aWxkZTtlcw==** So now lets decode it so that it can be saved... ``` $ds = base64_decode($_GET['d']); parse_str($ds, $params); $name = htmlentities($params['name'], ENT_NOQUOTES); $midn = htmlentities($params['midn'], ENT_NOQUOTES); ``` It looks pretty straight forward isn't it... but here is the problem because when I try to use the values nothing happen... lets say I just want to echo it... ``` echo $name . '<br>'; echo $midn; ``` What I get is **L** **Gru** so where is the ó and the ñ? ok, let say I don't encode anything so the URL will look like this... ``` domain.com/other.php?name=L&oacute;ms&midn=Gru&ntilde;es // and the I use echo like this: echo $_GET['name'] . '<br>'; echo $_GET['midn']; // the output is L Gru ``` Even if I put : header ('Content-type: text/html; charset=utf-8'); after the `<?php` ... nothing happen... so, the question... how can I get the `&oacute;` as a value or better yet, how can I send the í,ó,ñ,á...etc as is in the url domain.com/file.php?data=íÄÑó and retrive it as is and save it as is and display it as is... I;m not sure if this has some relevant information, the data is going to be saved in a DB, the DB is InnoDB, utf8\_general\_ci Thank you for taking the time...
2014/01/21
[ "https://Stackoverflow.com/questions/21251435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2293454/" ]
**In send\_message.php** Put both messages in the same object. I don't know why you call it `price`, but try like this: ``` $message = array('message' => $message, 'extra' => $data ); ``` **In GCM.php** ``` $fields = array( 'registration_ids' => $registatoin_ids, 'data' => $message, ); ``` **In your Android Service** ``` protected void onMessage(Context context, Intent intent) { //log the message in JSON format Log.i(TAG, "Received message >> " + intent.getExtras().toString()); //Retrieve message and extra String message = intent.getExtras().getString("message"); String newmessage = intent.getExtras().getString("extra"); //Now display the message displayMessage(context, message + newmessage); generateNotification(context, message + newmessage); } ```
you can write a JSON response that contain a multiple messages and the you get the JSON in android , parse it and get your multiple Messages .
4,172,336
Old way ------- When I used to load page asynchronously in projects that required the content to be indexed by search engines I used a really simple technique, that is ``` <a href="page.html" id="example">Page</a> <script type="text/javascript"> $('#example').click(function(){ $.ajax({ url: 'ajax/page.html', success: function(data){ $('#content').html(data); } }) }); </script> ``` edit: I used to implement the haschange event to support bookmarking for javascript users. New way ------- Recently Google came up with the idea of ajax crawling, read about it here: <http://code.google.com/web/ajaxcrawling/> <http://www.asual.com/jquery/address/samples/crawling/> Basically they suggest to change "website.com/#page" to "website.com/#!page" and add a page that contains the fragment, like "website.com/?\_escaped\_fragment\_=page" What's the benefit of using the new way? ---------------------------------------- To me it seems that the new way adds a lot more work and complexity to something that before I did in a simple way: I designed the website to work without ajax and then I added ajax and hashchange event (to support back button and bookmarking) at a final stage. From an SEO perspective, what are the benefits of using the new way?
2010/11/13
[ "https://Stackoverflow.com/questions/4172336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/462707/" ]
The advantage is not really applicable for you, because you are using progressive enhancement. The new Google feature is for applications written entirely in Javascript, which therefore can't be read by the crawler. I don't think you need to do anything here.
The idea behind it is that Javascript users can bookmark pages too, I think. If you take a look at your 'old' method, it's just replacing content on the page; there is no way to copy the URL to show the page in current state to other people. So, if you've implemented the new `#!` method, you have to make sure that these URLs point to the correct pages, through Javascript.
3,911,060
Is there a library function available in Haskell to compose a function with itself *n* times? For example I have this function: ``` func :: a -> a ``` and I want to do this: ``` func . func . func . func . func . func , ... ``` (up to *n* times, where *n* is only known at runtime). Note that the iterate function would not be appropriate for what I am doing, since I do not care about any intermediate results.
2010/10/12
[ "https://Stackoverflow.com/questions/3911060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13271/" ]
The `iterate` solution is fine, or you might like this one: the composition of `n` copies of `f` is `foldr (.) id (replicate n f)`.
``` \n -> appEndo . foldMap Endo . replicate n ```
10,557
How do you require a password to be entered when restoring from sleep or screen saver?
2009/07/22
[ "https://superuser.com/questions/10557", "https://superuser.com", "https://superuser.com/users/1978/" ]
1. Click the Apple icon at the top left of the screen on the menu bar. 2. Click "System Preferences...". 3. Click to Open "Security". Check "Require password to wake this computer from sleep or screen saver"
System Preferences -> Security -> Check "Require password to take this computer from sleep or screen saver"
63,207,664
I'm trying to insert data to a collection I created in Atlas MongoDB. The data is following: ```js [ { id: 1, performer: 'John Doe', genre: 'Rock', price: 25, day: 1, image: '/img/uploads/1fsd324fsdg.jpg' }, { id: 2, performer: 'Rebekah Parker', genre: 'R&B', price: 25, day: 1, image: '/img/uploads/2f342s4fsdg.jpg' }, { id: 3, performer: 'Maybell Haley', genre: 'Pop', price: 40, day: 1, image: '/img/uploads/hdfh42sd213.jpg' } ] ``` `I get the error : "Insert not permitted while document contains errors." What am I doing wrong? Please advise.
2020/08/01
[ "https://Stackoverflow.com/questions/63207664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13235849/" ]
This is reslved now, formatting was the problem.
It's better that you use MongoDB Compass and connect to it with a connection string: 1. click on the connection 2. click on the connection using mongodb compass 3. then get the compass downloaded from MongoDB according to required OS 4. but use connection string of connection to MongoDB application Once you connect to your Compass, you can use import data and then browse your file to use.
2,752
Besides the initial time investment of downloading & learning how to use a new tool ... what are some more reasons for a rational not to switch to P2Pool? (Some reasons to switch is a slightly higher payoff in P2Pool due to bonus donations, and the overall contribution to a more distributed Bitcoin network). Is running P2Pool more maintenance than using one of the larger pools? Is it more buggy, or has a lower total hashrate and thus higher variance?
2012/01/26
[ "https://bitcoin.stackexchange.com/questions/2752", "https://bitcoin.stackexchange.com", "https://bitcoin.stackexchange.com/users/78/" ]
1. Variance. Raw connection to p2pool will always have variance for a typical miner - if the pool is small there will be large pool-based variance, if it is large the share difficulty will be high and there will be large share-based variance. 2. Running a Bitcoin node is already nontrivial and going forward will become impossible for at-home miners. For example, some mining rigs run on a cheap USB flash drive, which may soon become insufficient to hold the blockchain. 3. Normal mining pools have additional features such as worker monitoring, SMS notifications, automatic conversion of NMC to BTC and so on. 4. Some of p2pool's suggested advantages are a bit exaggerated. The recent P2SH woes are a non-issue since miners who want to vote can simply go to a pool that votes as they want. The more generic concentration of power problem can alternatively be solved with smart miners (miners who generate blocks themselves or from an independent party, and submit shares with Merkle branches of the generation transaction which are accepted if it credits the pool). Because of these reasons, I believe the future will be small PPS pools which act as a proxy to p2pool (with or without the use of independent block-issuing nodes). These will have low fees, no variance, as many features as the pool operator wants to implement, and will not be highly centralized. Until we see more of these I don't think there's much justification for p2pool going mainstream.
Time investment is not to be discounted so lightly. In addition to that, inertia and lack of awareness probably have a role. There's also the need for extra computer resources (ram mostly) to run the bitcoind and p2pool daemons. There's a bit of a higher variance as well, since the pool is relatively small. If you do have some spare ram, and a bit of time, it certainly is a good idea to reduce hash power centralization.
73,398,235
I need to repeat the query if the field of the returned object has the value 'INPROGRESS' with a delay so as not to clog up the server. If another field value is returned, the loop stops and I perform some action in `subscribe()` with its response. My attempts so far have ended up with this code, where unfortunately the queries repeat infinitely. ``` this.service .query(id: number) .pipe( repeatWhen(obs => obs.pipe(delay(1000))), filter((response) => response.Status === 'INPROGRESS'), take(1), ) .subscribe(...) ```
2022/08/18
[ "https://Stackoverflow.com/questions/73398235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18634016/" ]
with a recursie function, something like this should do the job: ```js private myFunc(){ this.myRecursiveFunc(1).subscribe(response => console.log(response)); } private myRecursiveFunc(id: number, response?:any):Observable<any>{ if(response && response.Status !== 'INPROGRESS'){ return of(response); } return this.service.query(id).pipe( delay(1000), concatMap(response => this.myRecursiveFunc(id, response) ); } ```
* **RxJS 6.x** ``` this.service.query(id: number).pipe( repeatWhen(delay(1000)), skipWhile((response) => response.Status === 'INPROGRESS'), take(1), ).subscribe(...) ``` <https://stackblitz.com/edit/rxjs-cc1ekf> * **RxJS 7.5.x** ``` this.service.query(id: number).pipe( repeat({ delay: 1000 }), skipWhile((response) => response.Status === 'INPROGRESS'), take(1), ).subscribe(...) ``` <https://stackblitz.com/edit/rxjs-kafps9>
24,003,100
[This link here](https://stackoverflow.com/a/21362171/1751090) lists model class and view class properties to change in order to prompt the user for **email** and password log in, rather than the default **username** and password required by Asp.NET Identity Authentication. However, it does not demonstrate how to remove the *requirement of creating a username upon registration* for the user in Identity. Can someone point me to a resource that would allow me to completely remove the username requirement from Identity Authentication? I don't want my users to have to complete this extraneous step. UPDATE:: according to [this example here](https://stackoverflow.com/a/21362171/1751090) on Identity email-authentication, installing the Visual Studio 2013 Update 2 allows users to complete registration with *email, and NOT username*: ![enter image description here](https://i.stack.imgur.com/TDydR.png) Big yay.
2014/06/02
[ "https://Stackoverflow.com/questions/24003100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1751090/" ]
You have to set it to an anonymous function: ``` myList[i].onclick = (function() { var currentI = i; return function() { getMyTitle(myTitle[currentI]); } })(); ``` (taken from [here](https://stackoverflow.com/a/3495722/436282))
You need to use: ``` window.onload = myPageIsReady; ``` instead of ``` window.onload = myPageIsReady(); ``` The following is my solution, it creates one function getMyTitle and assigns it to onclick. Here is an example link of the code: <http://jsfiddle.net/3Xg3s/6/> ``` window.onload = myPageIsReady; function getMyTitle() { alert(this.title) }; function myPageIsReady() { var myList = document.getElementsByTagName("button"); for (var i = 0; i < myList.length; i++) { myList[i].onclick = getMyTitle; }; }; ```
5,846,562
``` string[] words = System.IO.File.ReadAllLines("word.txt"); var query = from word in words where word.Length > "abe".Length && word.StartsWith("abe") select word; foreach (var w in query.AsParallel()) { Console.WriteLine(w); } ``` Basically the word.txt contains 170000 English words. Is there a collection class in C# that is faster than array of string for the above query? There will be no insert or delete, just search if a string starts with "abe" or "abdi". Each word in the file is unique. `EDIT 1` This search will be performed potentially millions of times in my application. Also I want to stick with LINQ for collection query because I might need to use aggregate function. `EDIT 2` The words from the file are sorted already, the file will not change
2011/05/01
[ "https://Stackoverflow.com/questions/5846562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1024089/" ]
If you need to do search once there is nothing better than linear search - array is perfectly fine for it. If you need to perform repeated searches you can consider soring the array (n Log n) and search by any prefix will be fast (long n). Depending on type of search using dictionary of string lists indexed by prefix may be another good option.
If you search much often than you change a file with words. You can sort words in file every time you change list. After this you can use bisectional search. So you will have to make up to 20 comparisons to find any word witch match with your key and some additional comparisons of neighborhood.
18,977,350
In my project, there is a datagridview if there are no data and click on the UPDATE button, I should get error message. Here if I click directly on update button I am getting error message, but if I click on the datagridview ( even though there is no data in the datagridview ) and click on update, I am getting message as updated. Please tell what is code that I should use instead of (dataGridView2.SelectedCells.Count == 0). The code I am using is: ``` private void btnUpdate_Click(object sender, EventArgs e) { if (dataGridView2.SelectedCells.Count == 0) { MessageBox.Show("There are no any records to update"); } else { SqlConnection con = Helper.getconnection(); SqlCommand cmd = new SqlCommand(); cmd.Connection = con; con.Open(); cmd.CommandType = CommandType.Text; string PrjName = txtPrjNmae.Text; string Description = txtPrjdescription.Text; DateTime Date = dateUpdate.Value; dateUpdate.Format = DateTimePickerFormat.Custom; dateUpdate.CustomFormat = "dd/MM/yy"; string Size = txtPrjSize.Text; string Manager = txtPrjManager.Text; cmd.CommandText = "Update Projects set Description='" + Description + "', DateStarted='" + Date + "',TeamSize='" + Size + "',Manager='" + Manager + "' where ProjectName= '" + PrjName + "' "; MessageBox.Show("Project Details are updated"); dataGridView2.Update(); dataGridView2.Refresh(); cmd.ExecuteNonQuery(); con.Close(); } BindData3(); } ```
2013/09/24
[ "https://Stackoverflow.com/questions/18977350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1494174/" ]
You can create a private property: ``` @property (strong, nonatomic) NSString *searchedText; ``` and use it to check for equality: ``` -(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)newText{ if(![self.searchedText isEqualToString:newText]){ self.searchedText = [[NSString alloc] initWithString:newText]; //Do your magic } } ```
I have the same issue, I solved it by creating a ivar... This worked for me because I reload my table after calling this and I reset `textDidClear = NO;` in my reloadTable method. ``` - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText { if (([searchText isEqualToString:@""]) && (textDidClear == NO)) { textDidClear = YES; [_categoryManager loadCategoriesWithToken:nil]; } else if (textDidClear == NO) { textDidClear = NO; [_productManager loadProductsFromSearch:searchText tokenIdent:nil]; } } ```
8,970,213
Previously i have used restful wcf webservices to get the data from server.But now i have to access PHP webservices.Using WCF restful webservices I used to get data as : ``` { 1,books, //0th index 2,toys, //1st index . . . } ``` but wen i am getting data from php webservice it is coming as a single array similar to the format shown below ``` [ 1, // 0th index books, // 1st index 2, // 2nd index toys, // 3nd index . . . ] ``` Please tell me is is not possible in php to create a json array as it is created in WCF restful services ?? Above shown formats are only symbolic representation of the actual data what i am getting from webservices. Joomla 1.7.3 and virtuemart 2.0 is used by php developer to develop webservices and also web app is created in using 1.7.3 and virtuemart 2.0 only.
2012/01/23
[ "https://Stackoverflow.com/questions/8970213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/948041/" ]
Have a look at the PhoneGap discussion group: <https://groups.google.com/forum/?fromgroups#!searchin/phonegap/navigator.network.connection.type/phonegap/oAggxryQzrw/hE8uhwN3ONgJ> If you're using 1.6.0, you need to update res/xml/plugins.xml from ``` <plugin name="Network Status" value="org.apache.cordova.NetworkManager"/> ``` to be: ``` <plugin name="NetworkStatus" value="org.apache.cordova.NetworkManager"/> ``` (You need to remove the space in "Network Status")
There is another change when going from pre 2.3.0 to post 2.3.0. > > Before Cordova 2.3.0, the Connection object existed at: > navigator.network.connection. > > > To match the spec, this was changed to navigator.connection in 2.3.0. > > > navigator.network.connection still exists, but is now deprecated and > will be removed in a future release. > > > [2.7.0 docs](http://docs.phonegap.com/en/2.7.0/cordova_connection_connection.md.html) So change this ``` var networkState = navigator.network.connection.type; ``` To This ``` var networkState = navigator.connection.type; ``` Basically remove the network from your Javascript. Hope this helps.
192,006
I wish to set up a Kali Linux box on a cloud provider in order to perform same day penetration tests. The issue I am having is finding a cloud provider such as AWS, Azure etc. for this. For AWS they require an application to be filled for each penetration test which can take up to 2 days for a reply (which may be to ask more questions), and as far as I can see Azure and Google Cloud only provide guidance on incoming penetration testing rather than the box supplied by them being the origin of the traffic. When searching for an answer to this I similarly only seem to come up with answers for incoming rather than outgoing traffic. Are there any good cloud providers for penetration testers which don't require lengthy approvals per test? A one time application with a few days wait would be fine, but having to apply for each test would get in the way of performing same day testing.
2018/08/21
[ "https://security.stackexchange.com/questions/192006", "https://security.stackexchange.com", "https://security.stackexchange.com/users/184738/" ]
Azure is fine with Pen Tests as long as their infrastructure is not unlawfully used to access or disrupt other systems on Azure (or without) which you cannot prove that you have the authorization to modify or access. Expect to provide a detailed specification of the kind of tests you wish to conduct including times when you wish to carry them out.
If you google "remote server rental" you find many sites with less restrictive rules. Server hosting that is offshore often have very loose rules for the usage of the device. You'll just have to search pricing and the different rules/SLA agreements. I guess this doesn't technically qualify as "cloud" in the sense of it's a VPC virtualized on shared infrastructure... but it does answer the question of "how do I pentest remotely on a shared service?"
8,991
Looking at the increasing [NoSQL](http://pt.wikipedia.org/wiki/NoSQL) movement and considering that databases like [MongoDB](http://www.mongodb.org/) offers a new perspective in flexible data storage for GIS. What is the best way to store lines and polygons in JSON documents to take advantage of [2d indexes](http://www.mongodb.org/display/DOCS/Geospatial+Indexing) and spatial functions?
2011/04/26
[ "https://gis.stackexchange.com/questions/8991", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/1315/" ]
[GeoJSON](http://geojson.org/) here are the [SPECs](http://geojson.org/geojson-spec.html). Here's an example of a line and a polygon: ```js { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": {"type": "Point", "coordinates": [102.0, 0.5]}, "properties": {"prop0": "value0"} }, { "type": "Feature", "geometry": { "type": "LineString", "coordinates": [ [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0] ] }, "properties": { "prop0": "value0", "prop1": 0.0 } }, { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] ] }, "properties": { "prop0": "value0", "prop1": {"this": "that"} } } ] } ```
This is simply not true, *"to take advantage of spatial indexes in Mongo, you'd need a spatially indexed collection holding nothing but a record for each of the polygon's points, with an additional value for the record ID of your spatial record living in another collection, then use a bounding box query to get record IDs from one [collection] and select [record data] from the other [collection], effectively emulating a join."* I have USGS point data stored in a single Mongo collection with records that look like this: ``` > db.names.find({FEATURE_NAME: 'Mount Saint Helens', STATE_ALPHA: 'WA'}) { "_id" : ObjectId("4e262106d7a99b7db41a4919"), "_ID" : 1525360, "FEATURE_NAME" : "Mount Saint Helens", "FEATURE_CLASS" : "Summit", "STATE_ALPHA" : "WA", "STATE_FIPS" : 53, "COUNTY_NAME" : "Skamania", "COUNTY_FIPS" : "059", "COORDS" : [ -122.1944, 46.1912 ], "ELEV_IN_FT" : "8356" } ``` I am able to do bounding box queries on this data that return the entire record (without the need for another collection) just fine. Query: ``` > box = [[-126.562500,45.089036], [-123.750000,47.040182]] [ [ -126.5625, 45.089036 ], [ -123.75, 47.040182 ] ] > db.names.find({"COORDS" : {"$within" : {"$box" : box}}, FEATURE_CLASS: "Summit"}, {FEATURE_NAME: true, COUNTY_NAME: true, STATE_ALPHA: true, ELEV_IN_FEET: true}).limit(5); ``` Response: ``` { "_id" : ObjectId("4e2620f8d7a99b7db4146cec"), "FEATURE_NAME" : "Harlocker Hill", "STATE_ALPHA" : "OR", "COUNTY_NAME" : "Coos" } { "_id" : ObjectId("4e2620f8d7a99b7db414a349"), "FEATURE_NAME" : "Neskowin Crest", "STATE_ALPHA" : "OR", "COUNTY_NAME" : "Tillamook" } { "_id" : ObjectId("4e2620f8d7a99b7db414a105"), "FEATURE_NAME" : "Miles Mountain", "STATE_ALPHA" : "OR", "COUNTY_NAME" : "Tillamook" } { "_id" : ObjectId("4e2620f8d7a99b7db414934a"), "FEATURE_NAME" : "Mount Gauldy", "STATE_ALPHA" : "OR", "COUNTY_NAME" : "Tillamook" } { "_id" : ObjectId("4e2620f8d7a99b7db4149d06"), "FEATURE_NAME" : "Little Hebo", "STATE_ALPHA" : "OR", "COUNTY_NAME" : "Yamhill" } ``` Mongo also provides the ability to do nearest neighbor searches, as well as point in polygon searches. This is well documented at [mongodb.org](http://www.mongodb.org/display/DOCS/Geospatial+Indexing)
28,496,332
I get this Error when i run > > ionic build android > > > Error screenshot ![enter image description here](https://i.stack.imgur.com/ZYyhQ.jpg) ``` C:\Users\Ahmed\IonicProjects\first\firstIonicApp>ionic build android Running command: "C:\Program Files\nodejs\node.exe" C:\Users\Ahmed\IonicProjects \first\firstIonicApp\hooks\after_prepare\010_add_platform_class.js C:\Users\Ahme d\IonicProjects\first\firstIonicApp Running command: "C:\Program Files\nodejs\node.exe" C:\Users\Ahmed\IonicProjects \first\firstIonicApp\hooks\after_prepare\020_remove_sass_from_platforms.js C:\Us ers\Ahmed\IonicProjects\first\firstIonicApp Running command: C:\Users\Ahmed\IonicProjects\first\firstIonicApp\platforms\andr oid\cordova\build.bat ANT_HOME is set incorrectly or ant could not be located. Please set ANT_HOME. Built the following apk(s): ``` Also i want to know is it better to bootstrap ionic projects with yeoman? i already saw couple of tutorials doing that.
2015/02/13
[ "https://Stackoverflow.com/questions/28496332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2442918/" ]
based on this [link](https://blogs.oracle.com/rajeshthekkadath/entry/installing_ant_on_windows), you need to the perform the following: 1. Download and install [Ant](https://ant.apache.org/bindownload.cgi) 2. Set the ANT\_HOME environment variable to the location where Ant was installed (Right Click >> Properties >> Advanced >> Environment Variables ...) 3. Add **%ANT\_HOME%\bin** to your PATH 4. Open a command line and type "ant -version", and check if it is working.
It looks like you dont have apache ant installed.go to: <http://ant.apache.org/> and installed apache ant then create a ANT\_HOME varriable in your system varriables and add your ant location to your PATH varriable
249,468
I'm looking at stdint.h and given that it has uint16\_t and uint\_fast16\_t, what is the use for uint\_least16\_t what might you want that couldn't be done equally well with one of the other two?
2008/10/30
[ "https://Stackoverflow.com/questions/249468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10471/" ]
Say you're working on a compiler with: * `unsigned char` is 8 bits * `unsigned short` is 32 bits * `unsigned int` is 64 bits And unsigned int is the 'fastest'. On that platform: * `uint16_t` would *not* be available * `uint_least16_t` would be a 32 bit value * `uint_fast16_t` would be a 64 bit value A bit arcane, but that's what it's for. How useful they are is another story - I see the exact size variants all the time. That's what people want. The 'least' and 'fast' versions I've seen used pretty close to never (it's possible that it was only in example code - I'm really not sure).
Ah, the link Patrick posted includes this "The typedef name uint\_leastN\_t designates an unsigned integer type with a width of at least N, such that no unsigned integer type with lesser size has at least the specified width." So my current understanding is: uint\_least16\_t the smallest thing that is capable of holding a uint16 uint\_fast16\_t the fastest thing that is capable of holding a uint16 uint16\_t exactly a uint16, unfortunately may not be available on all platforms, on any platform where is is available uint\_least16\_t will refer to it. So if it were guaranteed to exist on all platforms we wouldn't need uint\_least16\_t at all.
58,818,833
This is a typescript and html problem. Let me describe the situation. There is a input box and a button. when I type in the input box it atomically shows the character by a paragraph which i typed in the input box. When I click the button a function `onClickAllow()` works. the function basically check a random value negative or positive. It also push the input text in the array. The output is: index\_number.input\_text with background color. When `Math.Random() > .5` the background color will be red otherwise green. My code also works. But the problem is when the color change it also change the previous content. [html code](https://i.stack.imgur.com/nljfw.jpg) [typescript code](https://i.stack.imgur.com/fCRde.jpg) [Output-1](https://i.stack.imgur.com/aDmZ9.jpg) [Output-2](https://i.stack.imgur.com/3VLX2.jpg) If you see Output-1 shows the 1st element with red background color but in Output-2 when the 2nd element comes with green background color, it also change the 1st element background color. But I want separate element with separate background color.
2019/11/12
[ "https://Stackoverflow.com/questions/58818833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12359788/" ]
*Component: typescript Templete: html* ```js array = []; status = ''; onClickButton(){ this.status = Math.random() > 0.5 ? 'negative' : 'positive'; this.array.push({name: 'name', type: this.status}); } ``` ```html <button (click)="onClickButton()">Button</button> <div *ngFor="let item of array; let i = index"> <p [ngStyle]="{backgroundColor: item.type == 'negative' ? 'red' : 'green'}">{{ i+1 }}.{{ item.name }}</p> </div> ``` This solution is working.
as far I understand you just want a color base of element position in the ngFor items list , this can be solve by get the index of each item and get color base of index. *componnet* ``` public getColor(index :number) : string { switch( index) { case 0 : return "#f00" case 1 : return "#0f0" case 2 : return "#00f" default: return "#abc" } } ``` *template* ```html <div *ngFor="let item of list;let i=index" [ngStyle]="{backgroundColor:getColor(i)}"> {{item.name}} </div> ``` [demo](https://stackblitz.com/edit/angular-jk4jv3) **Updated** a pipe will be a reusable solution ```js @Pipe({ name: 'color' }) export class ColorPipe implements PipeTransform { transform(index: number): any { switch( index) { case 0 : return "#f00" case 1 : return "#0f0" case 2 : return "#00f" default: return "#abc" } } } ``` *template* ```html <div *ngFor="let item of list;let i=index" [ngStyle]="{backgroundColor: i | color }"> {{item.name}} </div> ``` [**demo**](https://stackblitz.com/edit/angular-1e14be)
5,166,094
A lot of my pages have amll bits of jquery. Im thinking of putting them into one external file with one `$(document).ready(function() {` and everything in there. is this a good/bad idea? will each page be slower overall if there is more code to execute even if its not relevant to the page? i imagine each line of code in the external script gets executed when the **dom** is ready..? or is my understanding wrong?
2011/03/02
[ "https://Stackoverflow.com/questions/5166094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66975/" ]
> > will each page be slower overall if there is more code to execute even if its not relvamnt to the page? > > > The external script file may have some overheads for loading, but if you use the script on any number of pages more than one, external is a good idea; it'll be cached and be instant. > > i imagine each line of code in the external script gets executed when the dom is ready..? or is my understanding wrong? > > > Yes. If you wrap your code in a function as an argument to `$(document).ready()` it gets executed on `DOMContentLoaded`.
If you put all your bits of JS into one page - without calling them as functions- then, yes, they will get executed everytime you include them. It would be better to put the common functions into an external scripts and keep it there. This will increase your code reuse as well as speed up page load because your JS will be cached.
7,273,498
This is my code: ``` $myDiv = $('<div>1</div>'); $myDiv.each(function () { console.log(this.html()); }); ``` It produces an error because `this` should be `$(this)`. But wait. Isn't `$myDiv` a jQuery object in the first place, so that `this` must also be a jQuery object. If so, why should I wrap `this` inside of `$( )`?
2011/09/01
[ "https://Stackoverflow.com/questions/7273498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/707381/" ]
In that case `this` actually refers to the node. ``` $myDiv = $('<div>1</div>'); $myDiv.each(function () { console.log(this.innerHTML); }); // outputs 1 ```
According to the jquery documentation this is the expected behavior for the `$(selector).each()` They even give you an example for the case where "you want to have the jQuery object instead of the regular DOM element": <http://api.jquery.com/each/#example-1>
57,517,096
Computer gives me wrong result when choosing the largest number of three given numbers. I'm not sure if this is possible way to code this program. I'm new to C, but when we learned about Pascal in school, this is roughly how we made the program choose the largest number (by introducing another variable, in my case X). Sorry if this was posted before, can't seem to find it. ``` int max(int num1, int num2, int num3) { int result; int X; if (num1>num2) { num1 = X; } else { num2 = X; } if (num3>X) { num3 = result; } else { X = result; } return result; } int main() { printf("Result: %d", max(4, 10, 15)); return 0; } ``` I'd expect it to show me MAX number of 15, but it shows me some random, big number. NOTE: I'm also having problems with code format
2019/08/15
[ "https://Stackoverflow.com/questions/57517096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11881542/" ]
In C it is like in Pascal: the target of an assignment is on the left of the assignment operator ('=' in C, ':=' in Pascal) and the expression to assign is on the right. Just swap both sides and it works.
Other comments and answers have indicated why the OPs posted code did not result in the correct answer. The following direct approach is simple, quick, but does not scale well when there are a lot of numbers to choose from. ``` int max(int num1, int num2, int num3) { int X = num1; if( num2 > X ) X = num2; if( num3 > X ) X = num3; return X; } ```
46,247
I have view that uses url args: parent term id and term id/ids, so the url structure is like page/%/% Title pattern for this view is: %1(%2) However I have few pages with multi tids as second argument, so generated title is strange (very long). I am trying to change this title programmatically: ``` function bip_title_alter_views_post_render(&$view, &$output, &$cache) { if ($view->name == 'kategorie_artykulow' && $view->current_display == 'page_9') { $args = explode(' ', $view->args[1]); if (sizeof($args) < 2) { return; } $title_pattern = 'Archiwum Oświadczeń Majątkowych w %dr.'; $term = taxonomy_term_load($args[0]); if (! $term) { return; } $title = sprintf($title_pattern, $term->name); drupal_set_title($title); } } function bip_title_alter_module_implements_alter(&$implementations, $hook) { if ($hook == 'views_post_render') { $group = $implementations['bip_title_alter']; unset($implementations['bip_title_alter']); $implementations['bip_title_alter'] = $group; } } ``` but title remains the same, I am sure that I am altering proper view. Adding another display to view is not good option for me, because I have a lot existing urls and if I create another display with the same url structure and different args config always first display is handling request. **edit** I changed my custom module weight in system table to 9999 and I still see that title is altered after my module hook :/ It's so annoying
2012/10/10
[ "https://drupal.stackexchange.com/questions/46247", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/1178/" ]
I always use a [`hook_views_pre_view()`](http://drupalcontrib.org/api/drupal/contributions%21views%21docs%21views.api.php/function/hook_views_pre_view/7): ``` function mymodule_views_pre_view(&$view, &$display_id, &$args) { if ($view->name == "foo" && $view->current_display == "bar") { $view->display[$view->current_display]->display_options["title"] = $view->display[$view->current_display]->handler->options["title"] = "The New Title"; } } ``` This should then funnel up to be pulled in as the page title, but I never use views directly as pages.
I would use [hook\_views\_pre\_render](http://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7) and alter the views display title. Refer to <http://drupal.org/node/438370> as well.
29,316,735
I am working with SQL Server 2008. I have a table which does not contain any unique columns; how to get alternate rows from it? SQL Server table: ``` +-----+--------+ | id | name | |-----+--------| | 1 | abc | | 2 | pqr | | 2 | pqr | | 3 | xyz | | 4 | lmn | | 5 | efg | | 5 | efg | +-----+--------+ ``` As we've to come with at least one working suggestion with the question, I've tried below code; which is not so proper technique when fetching from a huge amount of data. Trial: ``` create table #tmp ( id int, name varchar(10), srNo int ) insert into #tmp select id, name, ROW_NUMBER() OVER (ORDER BY id) % 2 as srNo --,alternate rows from Employee select * from #tmp where srNo = 1 --or srNo = 0 ``` Above query gives out alternate rows i.e. 1st, 3rd, 5th *OR* 2nd, 4th, 6th etc. Please help me out with **proper way** *without `#tmp`* to achieve the goal!
2015/03/28
[ "https://Stackoverflow.com/questions/29316735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3682162/" ]
I'm taking student as a table name. Here is my answer -> 1. **For Even Row Number** - `> SELECT id from (SELECT rowno, id from student) where mod(rowno,2)=0` 2. **For Odd Row Number** - `> SELECT id from (SELECT rowno, id from student) where mod(rowno,2)=1`
``` declare @t table ( id int, name nvarchar(20) ) insert into @t Select 1, 'abc' union all Select 2, 'pqr' union all Select 2, 'pqr' union all Select 3, 'xyz' union all Select 4, 'lmn' union all Select 5, 'efg' union all Select 2, 'efg' Select * from( Select *, row_number() over(order by id) as rnum from @t ) t where rnum % 2 <> 0 ```
22,179,645
I am struggling to get an HTML5 video to play when arriving at the page via an AJAX request. If you refresh the page, or land directly on the page, it works fine. But when navigating to the page via AJAX it does not play. The code is: ``` <video id="video" autoplay="autoplay" loop="loop" muted="muted" poster="http://localhost/wp-content/themes/studioindigo/videos/contactbackground.jpg"> <source src="http://localhost/wp-content/themes/studioindigo/videos/contactbackground.mp4" type="video/mp4"> <source src="http://localhost/wp-content/themes/studioindigo/videos/contactbackground.webmhd.webm" type="video/webm"> <img src="http://localhost/wp-content/themes/studioindigo/videos/contactbackground.jpg" alt="your browser does not support html5 video"> </video> ``` I have tried firing the following code on success of AJAX page load: ``` video = document.getElementById('video'); video.load(); video.addEventListener('loadeddata', function() { video.play(); }, false); ``` And also simply: ``` video = document.getElementById('video'); video.play(); ``` I have also tried using plugins such as video.js, but to no avail. I can't help but think I am missing something really simple. Surely if the video is on the page and has autoplay set, then it should just play regardless of whether you arrive at the page via AJAX or directly? The AJAX request for the page only updates the #main element (which the video is inside) and the does history.pushState - could that be anything to do with it? It doesn't seem likely...
2014/03/04
[ "https://Stackoverflow.com/questions/22179645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3380291/" ]
For anyone struggling with the same issue, I found that after the ajax call the video had the property 'paused: true' even thought autoplay was set and I was calling video.play() on 'loadeddata'. The solution was to trigger video.play() when pause is detected. I also found that it worked smoother not having the 'autoplay' attribute on the video and became jerky after multiple initialisations. DOM: ``` <video id="video" loop muted> <source src="video.mp4" type="video/mp4"> <source src="video.webm" type="video/webm"> </video> ``` JS: ``` video = jQuery('#video').get()[0]; video.addEventListener('loadeddata', function() { video.play(); }); video.addEventListener('pause', function() { video.play(); }); ``` Also, for anyone wondering why I might want this ability, it is for a video playing on the background of a webpage, hence no need for user to play/pause it.
Potentially it's a syntax error, because you seem to have some PHP leaking into the HTML in the form of `'; ?>` at the end of the `poster` and `src` attributes.
65,302
The title says it all - how can you tell what folder a report is in using SOQL?
2015/02/04
[ "https://salesforce.stackexchange.com/questions/65302", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/-1/" ]
The field OwnerID is actually the folder ID for the Report object. I don't think you can get the folder using relationships, but you can query for reports in a particular folder: ``` select Name from Report where OwnerId in (select ID from Folder where DeveloperName = 'FolderName') ```
As of API 35, the [Report](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_report.htm) object has **FolderName** field. > > SELECT id, name, ownerId, folderName FROM Report > > > The `OwnerId` is the ID field from the **Folder** object, which is the Report Folder the report lives in. Note, the `FolderName` field is the label of the folder and not the unique name. So if you wanted to query for reports by their folder's unique developer name then filter by `OwnerId` instead like in [Daniel Hoechst's answer](https://salesforce.stackexchange.com/a/65309/987). ``` SELECT id, name FROM Report WHERE ownerId IN ( SELECT ID FROM Folder WHERE developerName = 'FolderName' ) ```
57,215,858
``` #include <initializer_list> struct Obj { int i; }; Obj a, b; int main() { for(Obj& obj : {a, b}) { obj.i = 123; } } ``` This code does not compile because the values from the `initializer_list` `{a, b}` are taken as `const Obj&`, and cannot be bound to the non-const reference `obj`. Is there a simple way to make a similar construct work, i.e. iterate over values that are in different variables, like `a` and `b` here.
2019/07/26
[ "https://Stackoverflow.com/questions/57215858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4108376/" ]
It does not work because in `{a,b}` you are making a copy of `a` and `b`. One possible solution would be to make the loop variable a pointer, taking the addresses of `a` and `b`: ``` #include <initializer_list> struct Obj { int i; }; Obj a, b; int main() { for(auto obj : {&a, &b}) { obj->i = 123; } } ``` See it [live](https://coliru.stacked-crooked.com/a/66ce858717dac524) Note: it is generically better to use `auto`, as it could [avoid silent implicit conversions](https://stackoverflow.com/a/32510343/8769985)
A wee bit ugly but you can do this, since C++17: ``` #define APPLY_TUPLE(func, t) std::apply( [](auto&&... e) { ( func(e), ...); }, (t)) static void f(Obj& x) { x.i = 123; } int main() { APPLY_TUPLE(f, std::tie(a, b)); } ``` It even would work if the objects are not all of the same type, by making `f` an overload set. You can also have `f` be a (possibly overloaded) local lambda . [Link to inspiration](https://stackoverflow.com/a/54641400/1505939). The `std::tie` avoids the problem in the original code because it generates a tuple of references. Unfortunately `std::begin` is not defined for tuples where all members are the same type (that would be nice!), so we can't use the ranged-based for-loop. But `std::apply` is the next layer of generalization up.
4,583,292
Reopening this question: [Does there exist a positive, decreasing, twice differentiable convex function such that $\int\_1^{\infty}\frac{(f'(x))^2}{f(x)}dx=\infty$?](https://math.stackexchange.com/questions/4579990/does-there-exist-a-positive-decreasing-twice-differentiable-convex-function-su?noredirect=1#comment9646428_4579990) **My trial:** I tried some simple $f(x)$ like monomials or exponentials, that did not work (of course I may have overlooked smth). So I thought of being more systematic and try to define: $$g(x)=\frac{f'(x)^2}{f(x)}$$ where $g(x)>0$ from the hypothesis. I tried than to express $f$ as a function of $g$ like this: $$f'^2=fg$$ $$f'=-\sqrt{f}\sqrt{g} \ (\text{take negative square root})$$ $$f'/\sqrt{f}=-\sqrt{g} \ (\text{divide by non-zero function})$$ and integrating from $1$ to $x$: $$\sqrt{f(x)}=\sqrt{f(1)}-\frac{1}{2}\int\_1^{x}\sqrt{g(x)}dx$$ so now we should find a positive $g(x)$s.t.: $$\int\_1^{+\infty}\sqrt{g(x)}dx <\infty,\int\_1^{+\infty}g(x)dx =\infty $$ , or prove that such a $g$ does not exist but since it is very easy to make errors with such manipulations (taking square roots, divisions by $f$) I stopped here... moreover, maybe I am overcomplicating things...
2022/11/23
[ "https://math.stackexchange.com/questions/4583292", "https://math.stackexchange.com", "https://math.stackexchange.com/users/89516/" ]
The idea of the following construction is to find functions $h$ such that the solution of the initial value problem $$ f'(x) = -h(f(x)) \, , \, f(0) = 1 $$ is defined for all $x \ge 0$ and has the desired properties. --- Let $h:(0, 1] \to \Bbb R$ be a function with the following properties: 1. $h$ is differentiable, positive, increasing, with $\lim\_{x \to 0+} h(u) = 0$. 2. $\int\_0^1 \frac{1}{h(u)} \,du= \infty$. 3. $\int\_0^1 \frac{h(u)}{u} \,du = \infty$. Then $H:(0, 1] \to \Bbb R$, $H(y) = \int\_y^1 \frac{1}{h(u)} \, du$ is strictly decreasing with $H(1) = 0$ and $\lim\_{y \to 0+} H(y) = \infty$, and we can define $$ f: [0, \infty) \to \Bbb R, f(x) = H^{-1}(x) \, . $$ $f$ is positive, strictly decreasing, with $f(0) = 1$ and $\lim\_{x \to \infty} f(x) = 0$. $f$ is differentiable with $$ f'(x) = \frac{1}{H'(f(x))} = - h(f(x)) \,. $$ This implies that $f'$ is differentiable and increasing (since $f$ is decreasing and $h$ is increasing), so that $f$ is twice differentiable and convex. Finally, $$ \int\_0^\infty \frac{f'(x)^2}{f(x)} \, dx = - \int\_0^\infty \frac{h(f(x)) f'(x)}{f(x)} \, dx = \int\_0^1 \frac{h(u)}{u} \, du = \infty $$ where we have substituted $u=f(x)$ in the last step. --- It remains to show that such a function $h$ exists. With the substitution $h(u) = 1/g(1/u))$ this is equivalent to finding a function $g: [1, \infty) \to \Bbb R$ with the following properties: 1. $g$ is differentiable, positive, increasing, with $\lim\_{x \to \infty} g(x) = \infty$. 2. $\int\_1^\infty \frac{g(x)}{x^2} \, dx = \infty$. 3. $\int\_1^\infty \frac{1}{x g(x)} \, dx = \infty$. We construct $g$ by defining sequences $$ 1 = x\_1 < y\_1 < \ldots < x\_n < y\_n < x\_{n+1} < \ldots $$ converging to infinity, and define $g$ such that $$ \int\_{x\_n}^{y\_n} \frac{1}{xg(x)} \,dx \ge 1 $$ and $$ \int\_{y\_n}^{x\_{n+1}} \frac{g(x)}{x^2} \,dx \ge 1 \, . $$ for each $n$. This guarantees that the conditions 2 and 3 are satisfied. The construction will also show that condition 1 is satisfied. We start by setting $x\_1 = 1$ and $g(1) = 1$. Now assume that everything is defined up to $x\_n$. We set $y\_n = x\_n e^{g(x\_n)}$ and $g(x) = g(x\_n)$ for $x\_n \le x \le y\_n$. Then $$ \int\_{x\_n}^{y\_n} \frac{1}{xg(x)} \,dx = \frac{1}{g(x\_n)} \log\frac {y\_n}{x\_n} = 1 \, . $$ Finally, set $x\_{n+1} = y\_n + 1$ and for $y\_n \le x \le x\_{n+1}$ $$ g(x) = g(y\_n) + C\_n \phi(x-y\_n) $$ where $\phi(x) = x^2 (3-2x)$ and $C\_n > 1$ is chosen so large that $\int\_{y\_n}^{x\_{n+1}} \frac{g(x)}{x^2} \,dx \ge 1$. Note that $\phi$ is strictly increasing on $[0, 1]$ with $\phi'(0) = \phi'(1) = 0$, so that the piecewise defined function $g$ is differentiable everywhere. This concludes the proof.
I don't see any mistakes in your reasoning. There is such $g$, but given required properties I doubt there is any nice expression of it from elementary functions. Given that we want integral of $\sqrt{g(x)}$ to converge and integral of $g(x)$ to diverge, we need $g(x)$ to take large values (otherwise we would just have $\sqrt{g(x)} > c\cdot g(x)$ near infinity). But for integral of $\sqrt{g(x)}$ to converge, we need $g(x)$ to take large values not very often. So, the idea is as follow: if $g(x)$ is $2^n$ on interval with length $2^{-n}$, then this interval contributes $1$ to integral of $g(x)$, but only $2^{-n/2}$ to integral of $\sqrt{g(x)}$. If there is such interval for every $n$, then integral of $g(x)$ diverges, while integral of $\sqrt{g(x)}$ can still converge. Let $w(x)$ be bump function: smooth, $w(x) = 0$ if $x \notin [0, 3]$, $w(x) = 1$ if $x \in [1, 2]$ and $0 \leq w(x) \leq 1$ if $x \in [0, 1] \cup [2, 3]$. Now, $h\_n(x) = 2^n \cdot w(2^n \cdot (x - 10n))$ satisfies properties we required: integral of $h\_n(x)$ is at least $1$, while integral of $\sqrt{h\_n(x)}$ is at most $3 \cdot 2^{-n/2}$. Note that $h\_n$ have disjoint supports for different $n$, so $\sum\_n \sqrt{h\_n(x)}\,dx = \sqrt{\sum\_n h\_n(x)}$. Now, let add $\exp(-x)$ for positivity, it doesn't affect convergence, and say $g(x) = \exp(-x) + \sum\limits\_{n=1}^\infty h\_n(x)$.
59,884,525
After spending the whole day with that problem... i need help. Node v12.14.1 mongoose v5.8.9 mongoDB v4.2.1 So everything is up to date. I tried many ways, but this is how it should work: ``` model.updateOne({_id:model_id},{$pull: {videos: {_id:video_id},{multi:true}) ``` but then i get ``` { n: 1, nModified: 0, ok: 1 } ``` So, it get found, no errors but it dosent remove/modify the object. Cant figure out what should be wrong.
2020/01/23
[ "https://Stackoverflow.com/questions/59884525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9016853/" ]
I'm sure someone will have a pure `plotly` solution for you, but here is a work around where we make `ggplot` objects, then convert to `plotly` ``` library(plotly) library(tidyverse) set.seed(0) x <- seq(from=0, to=9, by=1) y1 <- rnorm(10) y2 <- rnorm(10) y3 <- rnorm(10) y4 <- rnorm(10) p1 <- {ggplot(tibble(x, y1), aes(x,y1))+ geom_point(color = "blue")+ labs(x='', y='')+ theme_bw()+ theme(panel.border = element_rect(color = "black"))} %>% ggplotly() p2 <- {ggplot(tibble(x, y2), aes(x,y2))+ geom_point(color = "orange")+ labs(x='', y='')+ theme_bw()+ theme(panel.border = element_rect(color = "black"))} %>% ggplotly() p3 <- {ggplot(tibble(x, y3), aes(x,y3))+ geom_point(color = "green")+ labs(x='', y='')+ theme_bw()+ theme(panel.border = element_rect(color = "black"))} %>% ggplotly() p4 <- {ggplot(tibble(x, y4), aes(x,y4))+ geom_point(color = "red")+ labs(x='', y='')+ theme_bw()+ theme(panel.border = element_rect(color = "black"))} %>% ggplotly() subplot(p1, p2, p3, p4,nrows = 2, shareX = TRUE, shareY = TRUE) ``` [![enter image description here](https://i.stack.imgur.com/m6rp6.png)](https://i.stack.imgur.com/m6rp6.png)
Set shareX and shareY = FALSE to preserve borders. N.B. if you set shareX or shareY = TRUE also in the code provided by SEAnalyst you will see that some borders are not preserved as well.
55,982
The backstory: I've purchased a DVD via online download (from EZTakes.com). The files appear in this kind of directory tree: ``` DVD Name +-- VIDEO_TS/ | +-- (various video files) +-- cover/ | +-- (a couple of .jpgs of the DVD cover art) +-- content.info ``` I'm trying (on a Mac using Disk Utility) to burn this to a DVD. I've created a DVD/CD master image of this structure in a couple of different ways and then burned them, none of which have produced a DVD that is viewable in my DVD player. Here's what I've tried so far: 1. Make an image of the whole structure shown above. Basically, pointed Disk Utility at the "DVD Name" folder. 2. Make an image of the whole structure shown above, minus what seems to be metadata that might not be necessary - I removed the cover subdirectory as well as the content.info file, and pointed Disk Utility at the "DVD Name" folder. 3. Make an image of part of the structure above. Basically, pointed Disk Utility at the "VIDEO\_TS" folder. So I'm wondering what contents the filesystem image needs to have. What's the right structure so that my DVD will play in a regular DVD player? Oh, I believe the medium itself isn't an issue. I'm using DVD-R discs, and both DVD players I tried these burns on claim to be able to play DVD+/-R discs.
2009/10/15
[ "https://superuser.com/questions/55982", "https://superuser.com", "https://superuser.com/users/4997/" ]
In a technical sense, the VIDEO\_TS folder already contains the video data in DVD format. A Video DVD is the contents of this VIDEO\_TS folder burned onto a DVD+/-R disc in a hybrid ISO9660+UDF filesystem. As Steve Rowe has mentioned, Video DVDs use UDF v1.02. See Doom9's [DVD Structure article](http://www.doom9.org/index.html?/dvd-structure.htm) for details of the filetypes. When burned as a Video DVD, the files in the VIDEO\_TS folder are layed out on the disc in a particular order. For example (notice the files are not layed out in alphabetical order): ``` VIDEO_TS.IFO -- VIDEO_TS.* is the first play item VIDEO_TS.VOB VIDEO_TS.BUP VTS_01_0.IFO -- VTS_01 is the first title set VTS_01_0.VOB -- the _0.VOB is the title set's menu VTS_01_1.VOB -- the _[1-9].VOB is the title set's video content VTS_01_2.VOB VTS_01_0.BUP VTS_02_0.IFO -- IFOs contain navigational information VTS_02_0.VOB -- VOBs contain Video, Audio & Subtitle streams VTS_02_1.VOB VTS_02_0.BUP -- BUPs are backup IFOs ``` Many data burning utilities can create Video DVDs, but you need to make sure they don't try to burn as a data DVD -- data DVDs won't necessarily lay out the files in the proper order, and may use the wrong filesystem for the disc. If you have the `mkisofs` command available (in the Terminal on MacOSX and Linux, or Windows with Cygwin), or the `hdiutil` command on OSX, you can make a ready-to-burn ISO with one of the following commands ([source](http://www.macosxhints.com/article.php?story=20070612161317338)): ``` # INPUT_FOLDER is the folder that contains the VIDEO_TS mkisofs -f -dvd-video -udf -V VOLUMENAME -o OUTPUT.iso /path/to/INPUT_FOLDER hdiutil makehybrid -iso -joliet -udf -udf-version 1.02 -default-volume-name "VOLUMENAME" -o OUTPUT.iso /path/to/INPUT_FOLDER ``` The output ISO file can be burned with any burning utility program.
The format of the disc for a DVD is [UDF](http://en.wikipedia.org/wiki/Universal_Disk_Format). When playing back a DVD on a computer, this is what is used to access the files. However, older consumer disc players don't use this structure to read the disc. Instead they use the alternate ISO-9660 file structure. Make sure you are burning your disc as UDF 1.02 or UDF + ISO 9660 if you want the most compatibility with consumer players.
3,836,999
Warning: I have no clue about how to work with XML. I have a simple application whose only purpose is to persist ten properties about an object (a log, if you will). I wrote it rapidly and it writes the properties by appending them to a plain text file. Problem solved. Now, I read that for simple applications like this one XML would be a good alternative. I don't plan to change my script (being so simple, it works very well), but that left me thinking. Say you want to create a log using XML. How do you write an entry to it? Do you read the whole XML file, append the entry, and rewrite the whole thing again? What I don't understand is how to "append" to an XML file, considering that you cannot "append" to the middle of a plain text file without reading it, parsing it, and writing it again. Please orient me. Cheers.
2010/10/01
[ "https://Stackoverflow.com/questions/3836999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104427/" ]
If I **really** had to do this, I'd structure the XML so that it took look entries as children of the root element, open the file, readbackwards until I was at the start of the closing tag for the root element, write the new elements, and then write the root element again. Mostly though, I just wouldn't do it. XML is not a good format for log entries (and I'm speaking as a big fan of XML). I **might** find it useful to have each entry as an XML fragment, but even that is unlikely. If you really need an XML log format, log in a more sensible format for logging, and then produce XML reports on those logs as needed. If you rotate your log files (e.g. writing to appLog20101001.log today and appLog20101002.log tomorrow), then you can optimise by persisting the XML files for logs that'll no longer be appended to.
It really depends on the language that you are using for writing your application, but most modern languages have a library, either in their base framework or as an external, called an XML parser. It's a library used to read and write XML files. What is important to see is that XML is a very hierarchical data structure, so you can't directly go into the file as text file and write to it.
11,582
So we've all probably had this situation: you debug some problem, only to realize it was caused by a config change you made six months ago, and you can't remember why you did it. So you undo it and fix the problem, and now some other problem comes back. Oh yeah, NOW I remember! Then you fix it properly. It's because you didn't take proper notes, you fool! But what's a good way to do this? In engineering we have loads of software meant to help us detect and track changes. Source control, code reviews, and so on. Every change is tracked, every change requires a comment as to what it is. And typical engineering departments require good comments so that in six months when you're figuring out why you broke it like that, you can use a historical 'blame' feature or binary search builds to pinpoint the problem. These tools are very effective communication tools and historical records. But in serverland, we have 500 different services, all with different ways of configuring them. And they don't always have a text format (consider setting permissions on a folder or altering the pagefile location) though they may have a textual representation. In our environment, we check in what config files that we can into Perforce, but there are very few of those. Can't exactly check in the Active Directory DB..though perhaps a dump that could be diff'd... In the past I have tried keeping a manual change log in our wiki, but it's super hard to maintain the discipline to do this (I know, not a good excuse, but it really is tough). MY QUESTION: What strategies and tools do you use to cope with this problem of tracking configuration changes to your servers? -- Update -- Note: I'm not looking for shared-note taking tools (I'm familiar with OneNote, etc) so much as automated tools specifically meant to help with tracking server changes. There's no comprehensive tool for tracking server config changes, but perhaps there are some for specific applications like GPO's. Also I am very interested in *specific strategies* that you've found useful. "We share notes in Sharepoint" is pretty vague. How do you maintain the discipline? What format do you use to track your changes? How do you organize your change data? I'd really like examples as well as ideas.
2009/05/23
[ "https://serverfault.com/questions/11582", "https://serverfault.com", "https://serverfault.com/users/1920/" ]
I have been at 4 or 5 companies now I don't really remember. We all had this problem. None of us have solved it 100 percent, but at the company I am at now we have what I think is the best strategy to date. Sharepoint/Wiki/Evernote/PINs * Sharepoint + moan all you want...it has some very nice list features. + IP address lists + inventory + service accounts and use + change notification logs * Wiki + How-to's + long range task lists * Evernote + my partner and I use this to put everything we don't want in Wiki + more how-to's that are technical in nature + scratch notes we both need to see + task accounting for the week + contractor task lists + evernote clipper makes it easy to screen shot AD/rights settings + available everywhere * PINs + Password repository
If all you want to do is *track* changes and not manage the whole process (i.e., via Chef or Puppet), just `rsync` your `etc` directory (wherever that might be) into a local git repo. ``` for HOST in alpha bravo charlie delta ...; do rsync -avz --exclude-from=exclusions -e ssh admin@$HOST:/opt/local/etc/ ./$HOST done ``` You can, of course, add other sources as needed.
72,148,751
Im trying to follow a larval tutorial and make a controller. This is what I have so far and it works for the guy in the video but mine says controller not found. I don't know what to do to fix it. Thank you! **web.php file:** ``` Route::get('/', [PagesController::class, 'home']); ``` **PagesController.php file:** ``` <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\PagesController; class PagesController extends Controller { public function home() { return view('welcome', [ 'foo' => 'bar' ]); } } ``` [PagesController.php file](https://i.stack.imgur.com/r2vTk.png) [Error Message](https://i.stack.imgur.com/yEhYY.png) [Web.php file](https://i.stack.imgur.com/IfHMc.png)
2022/05/07
[ "https://Stackoverflow.com/questions/72148751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19057852/" ]
I think somethings it happens due to cache of routes you added before ``` php artisan optimize:clear ``` Command to clear all cache And then check does this get('/') route is binded to home() method on conrtoller using ``` php artisan route:list ``` I hope its resolve your issue..
why did you use this in PagesController.php : `use App\Http\Controllers\PagesController;` This is wrong. you must remove this line of code in PagesController.php
58,709,724
I have a table with several columns where some of them are arrays of the same length. I would like to unnest them to get a result with values from arrays in separate rows. So having table like this one: [![input table](https://i.stack.imgur.com/zXvMd.png)](https://i.stack.imgur.com/zXvMd.png) I would like to get to: [![output table](https://i.stack.imgur.com/o4sP5.png)](https://i.stack.imgur.com/o4sP5.png) This is how it works for one of those array columns: ``` WITH data AS ( SELECT 1001 as id, ['a', 'b', 'c'] as array_1, [1, 2, 3] as array_2 UNION ALL SELECT 1002 as id, ['d', 'e', 'f', 'g'] as array_1, [4, 5, 6, 7] as array_2 UNION ALL SELECT 1003 as id, ['h', 'i'] as array_1, [8, 9] as array_2 ) SELECT id, a1 FROM data, UNNEST(array_1) as a1 ``` Is there some elegant way how to unnest both arrays at once? I would like to avoid unnesting each column separately and then joining everything together.
2019/11/05
[ "https://Stackoverflow.com/questions/58709724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3249293/" ]
Below is for BigQuery Standard SQL ``` #standardSQL SELECT id, a1, a2 FROM data, UNNEST(array_1) AS a1 WITH OFFSET JOIN UNNEST(array_2) AS a2 WITH OFFSET USING(OFFSET) ```
You can use `with offset` and a `join`: ``` WITH data AS ( SELECT 1001 as id, ['a', 'b', 'c'] as array_1, [1, 2, 3] as array_2 UNION ALL SELECT 1002 as id, ['d', 'e', 'f', 'g'] as array_1, [4, 5, 6, 7] as array_2 UNION ALL SELECT 1003 as id, ['h', 'i'] as array_1, [8, 9] as array_2 ) SELECT id, a1, a2 FROM data cross join UNNEST(array_1) as a1 with offset n1 JOIN UNNEST(array_2) as a2 with offset n2 on n1 = n2 ```
12,138,433
Let's suppose I have a C file with no external dependency, and only const data section. I would like to compile this file, and then get a binary blob I can load in another program, where the function would be used through a function pointer. Let's take an example, here is a fictionnal binary module, f1.c ``` static const unsigned char mylut[256] = { [0 ... 127] = 0, [128 ... 255] = 1, }; void f1(unsigned char * src, unsigned char * dst, int len) { while(len) { *dst++ = mylut[*src++]; len--; } } ``` I would like to compile it to f1.o, then f1.bin, and use it like this in prog.c ``` int somefunc() { unsigned char * codedata; f1_type_ptr f1_ptr; /* open f1.bin, and read it into codedata */ /* set function pointer to beginning of loaded data */ f1_ptr =(f1_type_ptr)codedata; /* call !*/ f1_ptr(src, dst, len); } ``` I suppose going from f1.c to f1.o involves -fPIC to get position independance. What are the flags or linker script that I can use to go from f1.o to f1.bin ? Clarification : I know about dynamic linking. dynamic linking is not possible in this case. The linking step has to be *cast func pointer to loaded data*, if it is possible. Please assume there is no OS support. If I could, I would for example write f1 in assembly with PC related adressing.
2012/08/27
[ "https://Stackoverflow.com/questions/12138433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11589/" ]
You should consider building a shared library (**.dll** for windows, or **.so** for linux). Build the lib like this : ``` gcc -c -fPIC test.c gcc -shared test.o -o libtest.so ``` If you want to load the library dynamically from your code, have a look at the functions **dlopen(3)** and **dlsym(3)**. **Or** if you want to link the library at the compile time, build the program with ``` gcc -c main.c gcc main.o -o <binary name> -ltest ``` **EDIT:** *I'm really not sure about what I will say here, but this could give you a clue to progress in your research ...* If you don't want to use **dlopen** and **dlsym**, you can try to read the symbol table from the **.o** file in order to find the function address, and then, **mmap** the object file in memory with the read and execute rights. Then you should be able to execute the loaded code at the address you found. But be carefull with the other dependencies you could meet in this code. You can check man page `elf(5)`
Use a cast function pointer. Here's an example: ``` #include <stdio.h> int main() { unsigned char *dst, *src; int len; void (*f1)(unsigned char *, unsigned char *, int); *(void **)(&f1) = 0x..........; f1(src,dst,len); return 0; } ``` To do any more, you'd really need a linker and a dynamic loader.
56,451,814
I have some images containing single or multiple faces, but I want to select only one face if image have multiple faces inside. I used OpenCV python to detect face with haar-cascade which is do perfectly, but I cannot select specific face from images with multiple face detector. My code is as bellow: ``` cascPath = "Python35\\Lib\\site-packages\\cv\\data\\haarcascade_frontalface_default.xml" faceCascade = cv2.CascadeClassifier(cascPath) listing = os.listdir(path\of\images) print("Detection face of new individual images") for file in listing: im = (path1 + '\\' + imagePath + '\\' + file) imag = cv2.imread(im) imag = imutils.resize(imag, width=500) gray = cv2.cvtColor(imag, cv2.COLOR_BGR2GRAY) # Detect faces in the image faces = faceCascade.detectMultiScale(gray) print("Founded face is {} faces which are {}".format(len(faces), faces)) if len(faces)>1: i = 0 for (x, y, w, h) in faces: cv2.rectangle(imag, (x, y), (x + w, y + h), (255, 0, 0), 2) cv2.putText(imag, "Face #{}".format(i), (x - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2) i = i + 1 cv2.imshow("im", imag) cv2.waitKey(0) cv2.destroyAllWindows() var = int(input("Which face you want to detect it")) faces = faces[var] print("Selected face is", faces) print("type of selected face",type(faces)) print("the drawing face is", faces) # Draw a rectangle around the face for (x, y, w, h) in faces: cv2.rectangle(imag, (x, y), (x + w, y + h), (255, 0, 0), 2) roi_gray = gray[y:y + h, x:x + w] roi_color = imag[y:y + h, x:x + w] cv2.imshow("face", roi_color) cv2.waitKey(0) cv2.destroyAllWindows() ``` This code work successfully if image contains only one face, but when there are multiple face and I want to select one of them by entering the index of it, I get the following error. ``` for (x, y, w, h) in faces: TypeError: 'numpy.int32' object is not iterable ``` Can anyone please help me when is the problem, I select the already founded rectangle, why reject it.
2019/06/04
[ "https://Stackoverflow.com/questions/56451814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10597829/" ]
When defining a variable of a specific type, this type has to be "known" to the compiler at this point. If the types you want to use are all defined in the same file, just make sure that you define each type before you use it the first time for a variable/parameter definition. If the types are defined in different files, make header files (e.g. "teacher.h") and include this header wherever needed: ``` // teacher.h: class teacher { public: int teacherNo=999; }; // main.cpp: #include "teacher.h" int main() { teacher t; cout<< t.teacherNo; } ```
You should add the header file of teacher to the other class. If you have teacher.h file, the add the following line of code to your other class: `#include "teacher.h"` That should probably fix your problem. You can read more about how you divide classes here: <https://www.learncpp.com/cpp-tutorial/89-class-code-and-header-files/> Hope it helped!
66,376,670
Git beginner here... I use it with Visual Studio exclusively. I've made 18 commits since the last push to the remote server and commit number 5 has a large file in it that I did not intent to be in there. Because it is over 100MB, I cannot push to the remote server. How do I edit that old commit and remove that file?
2021/02/25
[ "https://Stackoverflow.com/questions/66376670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8250234/" ]
If you can use the command-line git tool, it's easy. Assuming your remote tracking branch is `origin/master`: `git rebase -i origin/master` This will bring up an editor containing a list of your unpushed commits. Find the commit you want to edit, change the word `pick` to `edit`, save and exit. You should see a message stating that you're now editing the commit in question. Now just: ``` git rm big_bad_file git commit --amend git rebase --continue ``` And you're done.
Well, you can delete commit number 5 from commit history. `git log` -to see the various commit, with their hash values and use `git reset hash value`- to uncommit that from history and also remove form staging area and then you can delete that file and commit again
18,481
I have had a paper accepted for a conference this summer, which presents the preliminary results of my PhD research. However, I'd like to present my final results at another conference in the fall, the deadline for which is in a few weeks, and which requires a full paper submission. My question is: would it be unethical to submit the first paper (in a re-structured form) in the hope that it will get accepted for the later conference, and then subsequently update the results before the final deadline?
2014/03/24
[ "https://academia.stackexchange.com/questions/18481", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/13392/" ]
> > "May I submit a paper to another conference that is essentially the same as a paper that is already published or accepted for publication?" > > > **NO** \* > > "May I substantially change the content of an accepted conference paper after peer review?" > > > **NO** \* \* Unless it is disclosed to, and permitted by, the PC/editor.
To add to @ff524's absolutely correct answer, you can still submit to that second conference. All you need to do is cite your first paper, state that this paper only adds results A,B,C. It is possible that the modest additions to your first paper are enough to merit publication on their own; however you must be honest and let the editors/referees decide this. In short, you may submit your updated paper, provided you are completely honest about its differences with the previously published work. If indeed those differences are trivial (as suggested by the title of the question), then obviously this is pointless.
7,386,612
I am having a Java application and a .NET application both residing in two different machines and need to design a communication layer between these two applications. Any inputs or ideas would be really helpful. Below mentioned is the nature of interaction between these two applications. * Java applications sends large amounts of data to the .NET application * Data latency should be kept to a minimum * .NET application should also be able to request for some data (synchronously/asynchronously)
2011/09/12
[ "https://Stackoverflow.com/questions/7386612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/939940/" ]
The easyest way .Net and Java can talk is using Web-Services - we have done in my company with much success (using apache's cxf and standard code on the .Net side). But if latency and size are the main requirements, you should use Sockets - both platforms offer a pretty extensive socketing frameworks and it would give you the best performance possible.
We have had good experiences with providing web services with JAX-WS (part of standard runtime in Java 6). They explicitly list .NET compatibility as a goal and is well supported in IDE's. The Endpoint.publish() mechanism allow for small, simple deployments.
5,392,470
I am using jquery templates on both the server-side and client-side. I'm using the jqtpl and express modules on Node.js for the server, and I have jquery and its template plugin for the client. Wherever possible the client recieves JSON instead of html, and builds the template itself, using the HTML5 history api to change url and allow session navigation. If this isn't possible, the server does the templating instead and sends html. Both the server and the client have the exact same templates, but the server has them in the form of 12 .html files, and the client has them in the form of an object in a .js file. Each time I change or add a template, I have to alter the client .js file to be the same, which is a bit of a pain. What I would like to do is have the .js file dynamically take all of the .html files in my templates folder and compile them into an object. Once I had finished development, this file would be cached, as it no longer needs to look for changes.
2011/03/22
[ "https://Stackoverflow.com/questions/5392470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/671229/" ]
Given the way that XML serialization works, I do not believe the structure you are looking for will be possible from a straight Object -> XML structure as in your example you have more than one root node. If you had something where there was a container node, then individual ImageData elements within them, or a single over arching element to bundle them together you might be able to get by with it.
The structure you're showing is not valid XML because is containing more then one root node, so you can forget about XmlSerializer. If you want to handle easily with such a xml similar structures I suggest [Html Agility Pack](http://htmlagilitypack.codeplex.com/)
18,735,462
Is there an equivalent `min()` for the keys in an array? Given the array: ``` $arr = array(300 => 'foo', 200 => 'bar'); ``` How can I return the minimum key (`200`)? Here's one approach, but I have to imagine there's an easier way. ``` function minKey($arr) { $minKey = key($arr); foreach ($arr as $k => $v) { if ($k < $minKey) $minKey = $k; } return $minKey; } $arr = array(300 => 'foo', 200 => 'bar'); echo minKey($arr); // 200 ```
2013/09/11
[ "https://Stackoverflow.com/questions/18735462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/834525/" ]
This also would be helpful for others, ``` <?php //$arr = array(300 => 'foo', 200 => 'bar'); $arr = array("0"=>array('price'=>100),"1"=>array('price'=>50)); //here price = column name echo minOfKey($arr, 'price'); function minOfKey($array, $key) { if (!is_array($array) || count($array) == 0) return false; $min = $array[0][$key]; foreach($array as $a) { if($a[$key] < $min) { $min = $a[$key]; } } return $min; } ?> ```
``` $arr = array( 300 => 'foo', 200 => 'bar' ); $arr2=array_search($arr , min($arr )); echo $arr2; ```
9,699,292
how to stop all running worker threads in an android application without stoping the main thread? Any example for this?
2012/03/14
[ "https://Stackoverflow.com/questions/9699292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1268608/" ]
**in java, dont supply the method to stop thread.** you can only `interrupt` thread, but the thread must in the state which can be interrupt, like `sleep`, `wait`, etc... **or you can using some tricks to make the thread throw exception**, such as: > > 1.if the thread is connect the network, you want to stop thread, you can close the network connection, will throw the ioexception; > > > 2.if the thread is read the file, you can close the stream to throw ioexception; > > > 3.if the thread is query the database, you can close the database > > > so it depend on your thread working.
There are **two ways** to do it. **Make the threads interrupted** ``` Thread.interrupt() ``` Does it solve the problem? No it doesn't.The thread will only be interrupted only if they are in blocking/waiting state. Calling thread.interrupted doesn't stop a thread. Then how does it help? The code that you are trying to Run. Make a check in operations like long running network operations,DB operations.This way you can interrupt most of the threads. **Kill the process and restart it** ``` Kill the app process and restart it from zygote (It might not be for all devs) ```
49,172,110
When i create a new div on the same document body, lets say a stack of divs, i loose the references to the .ts funtions on the previous div, i've tryed to emulate this with a button, so i have the div with: ``` <div id="foo"> <button type="button" id="btn1" (click)="clickButton()">Click Me</button> </div> ``` This works.. Now i click on one function on that div that creates a new div with new content, the new created button (click)="clickButton()" works on that last div, but not works anymore on the previous one (the opened one in first place) (the button only works on the last opened div, but not on the previous divs.. ) my .ts has: ``` clickButton = function() { alert("button clicked"); }; ``` ps: im working with angular4 and typescript:
2018/03/08
[ "https://Stackoverflow.com/questions/49172110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5270397/" ]
without a stack trace and some code, a specific anser will be hard to find, so here is a general method for these things: ### Part 1 "what was running before": recreate your old environment, by digging through the logs, reverting to a backup etc. then run: ``` lein deps :tree 2>&1 > old-lein-dependencies ``` the `2>&1` part ensures that the version range and conflict warnings are included in the output. Mark down the leiningen version and java version: ``` lein version ``` ### Part 2: "what is running now" Repeat the steps and record the same information as before: ``` lein deps :tree 2>&1 > new-lein-dependencies lein version java -version ``` ### Part 3: Diff and Compare pick through all the differences ``` diff -u old-lein-dependencies new-lein-dependencies ``` there will be a big block of differences at the top where lein prints all the important warnings. The final clue is almost always here, though it's often not easy to recognise up right away. ### Part 4: Do Science go through every version change, starting from the initial configuration by pinning the versions in the project.clj until you find the change that breaks things. A convenient way to pin these is with the `:managed-dependencies` block in the project.clj file. It looks something like this: ``` :managed-dependencies [[http-kit "2.3.0-alpha4"]] ``` and repeat the process of switching out versions till you get a handle on where the change was introduced. For me this has almost always been the result of using a version range in a dependency rather than a specific version. I'm not too enthusiastic about version ranges anymore :-/
So I could not compare the previous setup as it was on a machine that was wiped clean. I found that an error had crept into one of the math formulas executed by the tool which basically called itself repeatedly resulting in the stack overflow error.
52,628,185
In my rails project I called 'bundle install' in the terminal to add a gem but received the following error message: > > Traceback (most recent call last): > 3: from /Users/usr/.rvm/gems/ruby-2.5.1/bin/ruby\_executable\_hooks:24:in `<main>' > 2: from /Users/usr/.rvm/gems/ruby-2.5.1/bin/ruby_executable_hooks:24:in`eval' > 1: from /Users/usr/.rvm/gems/ruby-2.5.1/bin/bundle:23:in `<main>' > /Users/usr/.rvm/gems/ruby-2.5.1/bin/bundle:23:in`load': cannot load such file -- /Users/usr/.rvm/rubies/ruby-2.5.1/lib/ruby/gems/2.5.0/gems/bundler-> 1.16.5/exe/bundle (LoadError) > > > My operating system is macOS High Sierra. Any suggestions on how to overcome this error would be much appreciated.
2018/10/03
[ "https://Stackoverflow.com/questions/52628185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7938133/" ]
Use DOMDocument to do that: ``` $dom = new DOMDocument; $dom->loadHTML($yourstring); $xp = new DOMXPath($dom); foreach($xp->query('//text()') as $textNode) { echo $textNode->nodeValue, PHP_EOL; } ```
There is an `strip_tags()` function that does it without further configurations ``` <?php $input = '<html><head><title>Nice page</title></head><body>Hello World <a href=http://cyan.com title="un lien">Ceci est un lien</a><a>sdfaf</a><br /><a href=http://www.riven.com> Et ca aussi <img src=wrong.image title="et encore ca">dd</a><body></html>'; print( strip_tags($input) ); ```
29,583,048
Here is the exact error message: ``` Exception in thread "main" java.lang.NullPointerException at Application.main(Application.java:22) ``` I've tried to fix it with what I know... what am I doing wrong? My code: ``` public class Application { private String guitarMaker; public void setMaker(String maker) { guitarMaker = maker; } public String getMaker() { return guitarMaker; } public static void main (String[] args) { Application[] guitarists; guitarists = new Application[1]; guitarists[0].setMaker("Example maker"); System.out.println("My guitar maker is " + guitarists[0].getMaker()); } } ```
2015/04/11
[ "https://Stackoverflow.com/questions/29583048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4778083/" ]
I did your layout and while explaining it will take some time, better a **[fiddle](https://jsfiddle.net/alvaromenendez/t8e01cou/1/)** so you can check it out. And, as I need to input code, this is the simple css involved: ``` * { box-sizing: border-box; } .container { width:100%; max-width:600px; border:2px solid black; margin: 0 auto; padding:10px; } .row { height:100px; /*set height*/ border:2px solid blue; width:100%; margin-bottom:10px; padding:10px; } .col1 { border:2px solid red; width:100%; height:100%; } .col2 { border:2px solid green; width:49%; float:left; height:100%; margin-right:2%; } .col2:last-child {margin-right:0; } .col3 { border:2px solid brown; width:32%; float:left; height:100%; margin-right:2%; } .col3:last-child {margin-right:0; } ``` (and btw. it is responsive)
What might be a better solution, long term, would be to use the bootstrap framework (developed by twitter), which is very simple to use and has a lot of perks: > > Bootstrap includes a responsive, mobile first fluid grid system that appropriately scales up to 12 columns as the device or viewport size increases. It includes predefined classes for easy layout options, as well as powerful mixins for generating more semantic layouts. > > > <http://getbootstrap.com/css/#grid>
22,517,616
I am trying to run this program with the command ./box2 5 ``` /* * box2.c * * Created on: Mar 19, 2014 * Author: Ian */ #include <stdio.h> void printchars(char c, int n); int main( int argc, char*argv) { int n = argv[1]; printchars('*', n); return 0; } void printchars(char c, int n) { int x; for (x = n + 2 ; x > 0; x--) { if (x != 1 && x != n) { printf("%c", c); int count = n; while (count - 2 != 0) { printf(" "); count--; } } else { int num = n; while (num != 0) { printf("%c", c); num--; } } printf("\n"); } } ``` I always get the error Segmentation Fault(core dumped) each time i try it. ``` ***** * * * * * * * * * * ***** ``` This is what I should get. I have no idea what to do to fix this. I get no errors when I compile and that error is the only thing that comes up when I try to run the program.
2014/03/19
[ "https://Stackoverflow.com/questions/22517616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3015970/" ]
This is wrong: ``` int main( int argc, char*argv) ``` since `argv` must be declared as a ptr-to-ptr-to-char. Likewise, this: ``` int n = argv[1]; ``` can't work. You need something like ``` int main(int argc, char **argv) ... int n = atoi(argv[1]); ```
Change `int main( int argc, char*argv)` to `int main( int argc, char**argv)`.
42,160,544
``` [09.02.2017 - 10:40:06][NOTICE] - Start looping through invoices from Teamleader.. [08.02.2017 - 10:24:26][NOTICE] - Start looping through invoices from Teamleader.. [08.02.2017 - 10:29:24][NOTICE] - Start looping through invoices from Teamleader.. ``` This is the code for producing the above output: ``` var data = allText.split("\n"); for(var i = 0, len = data.length; i < len; i++){ console.log(data[i]); } ``` Is it possible to sort the array on the given date and time? here is an example of how it should look like: ``` [09.02.2017 - 10:40:06][NOTICE] - Start looping through invoices from Teamleader.. [08.02.2017 - 10:29:25][NOTICE] - Start looping through invoices from Teamleader.. [08.02.2017 - 10:24:26][NOTICE] - Start looping through invoices from Teamleader.. ```
2017/02/10
[ "https://Stackoverflow.com/questions/42160544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5501950/" ]
You can sort the array as you want with the sort function in which you can specify on which base it should be sorted: Here an example that will fit your needs: ```js var data = [ "[09.02.2017 - 10:40:06][NOTICE] - Start looping through invoices from Teamleader]", "[08.02.2017 - 10:24:26][NOTICE] - Start looping through invoices from Teamleader]", "[08.02.2017 - 10:29:24][NOTICE] - Start looping through invoices from Teamleader]" ]; data.sort( function(a, b){ // a and b are two elements in the list that are supposed to be compared var a_date = a.substring(1, 22); //take only date from string var b_date = b.substring(1, 22); //take only date from string // We compare those strings to order it. if ( a_date < b_date ) return 1; if ( a_date > b_date ) return -1; return 0; } ); console.log(data); ``` An [here](http://www.w3schools.com/jsref/jsref_sort.asp) you can find some references to the sort function in JS
You can use the function `sort()` on your array with a comparaison function to compare the date. I don't know what you are trying to compare but here is a simple example. ``` [/*...*/].sort(function(a, b){ //here a and b stand for your dates. you will need to adjuste your code to make it works since we have very little information about it. return Date.compare(a, b); }); ```
7,660,944
I ran my website through a web tool that evaluates SEO weight of elements and in the report it says that certain parts, like Description and other meta tags are missing... Also as a thumbnail of my site it shows a default server page. At the same time it shows the list of other pages that are linked from index page. I checked and this AGENT is not blocked in robots.txt Now, how can that be? [Demo](http://www.woorank.com/en/www/usabilitest.com)
2011/10/05
[ "https://Stackoverflow.com/questions/7660944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/434218/" ]
[`Date.toString();`](http://download.oracle.com/javase/1.4.2/docs/api/java/util/Date.html#toString%28%29) does **always** format your String that way. You should a SimpleDateFormat to format the `Date` object to the String you want. The JavaDoc of the [`Date.toString();`](http://download.oracle.com/javase/1.4.2/docs/api/java/util/Date.html#toString%28%29) method says: > > Converts this Date object to a String of the form: > > > > ``` > dow mon dd hh:mm:ss zzz yyyy > > ``` > >
Read below document :- <http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html> hope help u above link.
73,641,045
I am trying to find a string occurring before my grep result. ``` before = text1234 foo = 1234 bar = 1234 var = words before = text2345 foo = 2345 bar = 2345 etc = 2345 var = words ``` I am using grep `grep -n var *` to get the results of var. But I am trying to find the first occurrence of `before` before the grepped line. I have tried using the `grep -B 10` option, but since the lines are variable it is not exactly what I want. The ideal result would return: ``` before = text1234 before = text2345 ``` I think there is some sed/awk magic that would help, but I am not sure what it could be based on my google-fu
2022/09/07
[ "https://Stackoverflow.com/questions/73641045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19944265/" ]
One option using `awk` is to match `before =` at the start of the string and then store the line. Then when you encounter `var =` at the start of the string, check if there is a stored value for `before =` and then print that value. ``` awk ' /^before =/ {b=$0; next} /^var =/ && b {print b; b=""} ' file ``` Output ``` before = text1234 before = text2345 ``` --- Another option using a field separator of `=` and checking the first field values: ``` awk -F" = " ' $0 == "" {b="";next} $1 == "before" {b=$0; next} $1 == "var" && b {print b; b=""} ' file ```
Another `awk` approach that works with shown example data: ```bash awk '/^before /,/^var /{if ($1 == "before") print}' file before = text1234 before = text2345 ```