text
stringlengths
70
452k
dataset
stringclasses
2 values
Remove function from mutable set I want to store an object's method in a mutable Set. I can add the method without a problem, but cannot remove it: scala> import scala.collection.mutable.Set import scala.collection.mutable.Set scala> class c { | def f(value: Double) { | println(value) | } | } defined class c scala> val o = new c o: c = c@4b08e64d scala> val s = Set.empty[Function1[Double, Unit]] s: scala.collection.mutable.Set[Double => Unit] = Set() scala> s add o.f res0: Boolean = true scala> s.size res1: Int = 1 scala> s remove o.f res2: Boolean = false scala> s.size res3: Int = 1 If I create a set for holding an object of type c, everything works as expected. scala> val s2 = Set.empty[c] s2: scala.collection.mutable.Set[c] = Set() scala> s2 add o res4: Boolean = true scala> s2.size res5: Int = 1 scala> s2 remove o res6: Boolean = true scala> s2.size res7: Int = 0 Is what I want to do possible? Your wish to "… store an object's method in …" is flatly impossible. Methods are not first-class entities and cannot be treated as values. But their 1st-class counterpart, functions, can. Nonetheless, the down-side is that they don't have meaningful identities and are not readily equality-testable. Thus they dont' work well for the purpose of storage in and retrieval from a collection. o.f is analogous to a function pointer but is really not. scala> o.f _ res6: Double => Unit = <function1> scala> res6.## res7: Int =<PHONE_NUMBER> scala> o.f _ res8: Double => Unit = <function1> scala> res8.## res9: Int = 509798553 Is it possible? Mais oui! C'est possible! scala> import reflect.runtime.universe._ import reflect.runtime.universe._ scala> import reflect.runtime.currentMirror import reflect.runtime.currentMirror scala> currentMirror reflect o res12: reflect.runtime.universe.InstanceMirror = instance mirror for c@5a8c6475 scala> typeOf[c] res13: reflect.runtime.universe.Type = c scala> .declaration(TermName("f")) res14: reflect.runtime.universe.Symbol = method f scala> res12 reflectMethod res14.asMethod res15: reflect.runtime.universe.MethodMirror = method mirror for c.f(value: scala.Double): scala.Unit (bound to c@5a8c6475) scala> val ms = Set.empty[MethodMirror] ms: scala.collection.mutable.Set[reflect.runtime.universe.MethodMirror] = Set() scala> .add(res15) res16: Boolean = true scala> ms.remove(res15) res17: Boolean = true Edit: Ignore my French, that is mirror-specific anyway, so it is not an improvement. In other words, use java reflection. scala> classOf[c].getMethod("f", classOf[Double]) res23: java.lang.reflect.Method = public void c.f(double) scala> res23.## res24: Int = 521628901 scala> classOf[c].getMethod("f", classOf[Double]) res25: java.lang.reflect.Method = public void c.f(double) scala> res25.## res26: Int = 521628901 in other words, val x = o.f _; s add x; s remove x;. @som-snytt In your third block of code, you are not accessing o's instance method, you are accessing c's method. Is that correct? @bwroga yes, it's the same as res14, you can create a func val to invoke it (currying the instance, as it were) but that's not useful for comparison. I could imagine a case class that pairs a method and instance.
common-pile/stackexchange_filtered
Uniqueness of Monic Polynomial of Least Degree in Extension Field $K$ Let $K$ be an extension field of $F$, and let $\alpha \in K$ be algebraic. Suppose that $f(x) \in F[x]$. Prove that $f(x)$ is the unique monic polynomial of least degree with f($\alpha$) = $0$. My thinking is that if $f(x)$ isn't unique, then there exists another polynomial of $g(x)$ of the same degree. And, if that's the case, then these two polynomials would divide each other, which means $f(x)$ is not irreducible. Is this correct? Or am I missing pieces, or completely misunderstanding things? Thank you for your help. Hint $\ $ If $,f(a) = 0 = g(a),$ and $,f\ne g,$ then $,a,$ is also a root of their difference, a nonzero lower degree polynomial (lower since both are monic of equal degree, so lead terms cancel). @BillDubuque But if $f(x)$ and $g(x)$ are supposedly the lowest degree polynomials, then no lower degree polynomial can exist, right? Is that the contradiction? Exactly. That contradiction concludes the proof. Oh, just answer my own question? I can do that? (sorry, new to MSE) Yes, and it means you will get feedback (e.g. I corrected your division to a difference). Either $f(x)$ divides $g(x)$ or the vice versa . Let WLOG;$g(x)|f(x)\implies f(x)=g(x)q(x)+r(x)$ where $\deg r(x)<\deg g(x)$... $f(a)=0\implies r(a)=0$ which is false as $\deg r(x)<\deg g(x)\le\deg f(x)$ Hence $r=0\implies f(x)=cg(x);c\text{is a constant}$ But that is false as $f,g$ are monic.So $f=g$ Suppose $f(x)$ isn't unique. Then, there exists another monic polynomial of least degree $g(x)$ such that $g(\alpha)$ = $0$. $\implies f(\alpha) = 0 = g(\alpha)$. Since $f \ne g$, $\implies \alpha$ is also a root of a lower degree polynomial $h = $ $f - g$; ($h$ is nonzero and of lower degree since $f$ and $g$ are different, monic nonzero polynomials. So, we have cancelling leading terms, and $h$ consists of the difference of the remaining terms, which are not equal since $f \ne g$, and therefore nonzero). however, since $f$ and $g$ are of least degree, there cannot exist a polynomial $h$ of lower degree. $\therefore g$ cannot exist, and $f$ is unique. From the discussion above. You should explicitly justify why $h$ has lower degree (and is nonzero). Alright, I'll add in why I think that is. Note that the difference needn't be monic, so is not immediately a counterexample, but it does yield a monic since .... Is it because $f$ and $g$ are of lowest degree, so the difference would just be a constant? Hint: if $a$ is a root of $h$ then it is a root of $ch$ too. Use that to make it monic.
common-pile/stackexchange_filtered
Set fragment contents before or after adding? I'm basically trying to create this quiz system, where I have a template of questions, and I dynamically change the content of the questions: For example: Who directed movie X? - Incorrect answer director - Correct answer director - Incorrect answer director - Incorrect answer director I will replace X with some movie that I select from my database. Following the question will have 4 selectable options (also generated based on question), and the user can only click one of them. The question and answers are all inside a fragment .xml file. I'm trying to change the contents of the fragment before displaying it. I've read the android documents, but this section doesn't seem to have been written in enough detail. public class QuizTemplate extends ActionBarActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_quiz_template); if (savedInstanceState == null) { PlaceholderFragment firstFragment = new PlaceholderFragment(); // Trying to set question before I commit transaction // firstFragment.setQuestion("IT WORKS!"); FragmentManager manager = getSupportFragmentManager(); manager.beginTransaction() .add(R.id.container2, firstFragment).commit(); // Tried to execute pending transactions, then find view manager.executePendingTransactions(); PlaceholderFragment firstFragment = (PlaceholderFragment) manager.findFragmentById(R.id.container2); RadioButton answer1 = (RadioButton) firstFragment.getView().findViewById(R.id.answer1); RadioButton answer2 = (RadioButton) firstFragment.getView().findViewById(R.id.answer2); RadioButton answer3 = (RadioButton) firstFragment.getView().findViewById(R.id.answer3); RadioButton answer4 = (RadioButton) firstFragment.getView().findViewById(R.id.answer4); TextView question = (TextView) firstFragment.getView().findViewById(R.id.question); question.setText("test"); answer1.setText("test"); // ... and so on } } Fragment Class public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_quiz_template, container, false); return rootView; } public void setQuestion(String text){ TextView textView = (TextView) getView().findViewById(R.id.question); textView.setText(text); } } (layout) fragment_quiz_template.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.moviequiz.QuizTemplate$PlaceholderFragment" > <TextView android:id="@+id/question" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="65dp" android:text="@string/hello_world" /> <RadioButton android:id="@+id/answer2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/answer3" android:layout_below="@+id/answer3" android:layout_marginTop="28dp" android:onClick="changeQuestion" android:text="@string/hello_world" /> <RadioButton android:id="@+id/answer3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/answer4" android:layout_below="@+id/answer4" android:layout_marginTop="17dp" android:onClick="changeQuestion" android:text="@string/hello_world" /> <RadioButton android:id="@+id/answer4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/answer1" android:layout_centerHorizontal="true" android:layout_marginTop="16dp" android:onClick="changeQuestion" android:text="@string/hello_world" /> <RadioButton android:id="@+id/answer1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/answer4" android:layout_below="@+id/question" android:layout_marginTop="40dp" android:onClick="changeQuestion" android:text="@string/hello_world" /> </RelativeLayout> None of my approaches have worked, as my app crashes upon reaching the quiz (Nothing in the log?). Any ideas what could be going wrong? EDIT: Fixed my log, it now tells me: Unable to start activity ComponentInfo: java.lang.NullPointerException So my guess is when I call something like RadioButton answer1 = (RadioButton) firstFragment.getView().findViewById(R.id.answer1); answer1 is null. But why is this the case if I execute pending transactions? what crashes your app ? we can't know if you haven't posted your log :| My log actually doesn't display anything upon crashing. You're talking about LogCat right? Yes, that should show something ! here is a link about communication with other fragments/activities. A SO answer here Your code that generates the UI in the fragment takes time to execute. I believe that even though you are committing the transactions, the UI is still not ready when you are trying to access it. Don't forget that your fragment lifecycle is linked to your activity lifecycle yet you are expecting to access the fragment UI in the OnCreate method of your activity. Consider instead using the callback pattern to communicate between your activities and fragments. http://developer.android.com/training/basics/fragments/communicating.html Using this pattern, you can call your activity code when you are sure the UI is complete and available. I have just implemented this, but the problem is now how do I know when the fragment is done being loaded by the UI? Nvm, just figured out onActivityCreated() will handle that. Thanks!
common-pile/stackexchange_filtered
Return DOM element in render function of React component I have an external library that renders some custom js controls. The library returns a DOM element that can be inserted in to the page. I am creating wrapper for this library in React. I have it all wired up except I'm not sure how to allow the render function to accept the DOM element as its return render() { if (this.state.someType) { let customControl = new this.state.someType(); var node = customControl.getNode(); return node; //This is an HTMLDOMElement i.e. div or span } return <div>Loading Custom Control...</div>; } I am able to debug the code and everything is working properly. The node is what I expect but the html on the page is never replaced. Render a normal JSX div. Use ref inside. Inside the ref callback use .appendChild(node) See https://reactjs.org/docs/refs-and-the-dom.html Here's a simple example. render() { const newNode = document.createElement('p'); return <div ref={(nodeElement) => {nodeElement && nodeElement.appendChild(newNode)}}/> } ref will also be called when element is unmounted resulting in nodeElement being undefined for the call. You should include a check nodeElement && nodeElement.appendChild... This is a good answer as it contains the code example that could go along with the accepted answer. The above commend regarding nodeElement being undefined is also helpful and could be included in this code example.
common-pile/stackexchange_filtered
how to get price of an in app purchase item on my server using product id I have a receipt verification server. iOS application sends me the receipt, I validate the receipt using Apple's api, and I return a json with the required fields for the app. In the process if the user's subscription is started, I want to log that subscription with the price of the product. However I do not have the information for the price in the receipt. I just have product id. Is there an API for me to just ask Apple for the price of a given product id? Thanks in advance There's no way to get the price of the product from your server. If you have access to AppStoreConnect for your application, you can use the AppStoreConnect API to drill down to prices for product IDs, it requires you to set up a shared secret to make use of the API: https://developer.apple.com/documentation/appstoreconnectapi I have the access and can make requests but couldn't find the endpoint for drilling into product information I have checked this endpoint but there is no price information here https://developer.apple.com/documentation/appstoreconnectapi/read_in-app_purchase_information I think what you are allowing for is here: https://developer.apple.com/documentation/appstoreconnectapi/list_all_in-app_purchases_for_an_app That endpoint also does not give me any price information. It returns only attributes like inAppPurchaseType, state etc. I am facing the same problem. AppStore api does not provide prices for products or not even provide prices for Tiers. But you can get the price of the products from your client end. So on the client-side, when a purchase is successful, post the product's price and transactionId. This way you can match the transactionId and know the price of that sale. But you have to be aware of the price differences. SKProduct only gives you localized price, so your obtained info from client will be localized. You have to convert them to the same currency to have a meaningful result. If you have in app purchase id, you can get price information from this url. Set territory value acc https://api.appstoreconnect.apple.com/v1/inAppPurchasePriceSchedules/{in_app_purchase_id}/manualPrices?filter[territory]=USA&include=inAppPurchasePricePoint
common-pile/stackexchange_filtered
Speeding Up Python This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together: Firstly: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization? Secondly: When writing a program from scratch in python, what are some good ways to greatly improve performance? For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C? Regarding "Secondly: When writing a program from scratch in python, what are some good ways to greatly improve performance?" Remember the Jackson rules of optimization: Rule 1: Don't do it. Rule 2 (for experts only): Don't do it yet. And the Knuth rule: "Premature optimization is the root of all evil." The more useful rules are in the General Rules for Optimization. Don't optimize as you go. First get it right. Then get it fast. Optimizing a wrong program is still wrong. Remember the 80/20 rule. Always run "before" and "after" benchmarks. Otherwise, you won't know if you've found the 80%. Use the right algorithms and data structures. This rule should be first. Nothing matters as much as algorithm and data structure. Bottom Line You can't prevent or avoid the "optimize this program" effort. It's part of the job. You have to plan for it and do it carefully, just like the design, code and test activities. @AbidRahmanK It's at archive.org: http://web.archive.org/web/20101225202706/http://www.cs.cmu.edu/~jch/java/rules.html Rather than just punting to C, I'd suggest: Make your code count. Do more with fewer executions of lines: Change the algorithm to a faster one. It doesn't need to be fancy to be faster in many cases. Use python primitives that happens to be written in C. Some things will force an interpreter dispatch where some wont. The latter is preferable Beware of code that first constructs a big data structure followed by its consumation. Think the difference between range and xrange. In general it is often worth thinking about memory usage of the program. Using generators can sometimes bring O(n) memory use down to O(1). Python is generally non-optimizing. Hoist invariant code out of loops, eliminate common subexpressions where possible in tight loops. If something is expensive, then precompute or memoize it. Regular expressions can be compiled for instance. Need to crunch numbers? You might want to check numpy out. Many python programs are slow because they are bound by disk I/O or database access. Make sure you have something worthwhile to do while you wait on the data to arrive rather than just blocking. A weapon could be something like the Twisted framework. Note that many crucial data-processing libraries have C-versions, be it XML, JSON or whatnot. They are often considerably faster than the Python interpreter. If all of the above fails for profiled and measured code, then begin thinking about the C-rewrite path. Nowadays pandas (http://pandas.pydata.org/) should be added to that numbers crunching bit, i think. The usual suspects -- profile it, find the most expensive line, figure out what it's doing, fix it. If you haven't done much profiling before, there could be some big fat quadratic loops or string duplication hiding behind otherwise innocuous-looking expressions. In Python, two of the most common causes I've found for non-obvious slowdown are string concatenation and generators. Since Python's strings are immutable, doing something like this: result = u"" for item in my_list: result += unicode (item) will copy the entire string twice per iteration. This has been well-covered, and the solution is to use "".join: result = "".join (unicode (item) for item in my_list) Generators are another culprit. They're very easy to use and can simplify some tasks enormously, but a poorly-applied generator will be much slower than simply appending items to a list and returning the list. Finally, don't be afraid to rewrite bits in C! Python, as a dynamic high-level language, is simply not capable of matching C's speed. If there's one function that you can't optimize any more in Python, consider extracting it to an extension module. My favorite technique for this is to maintain both Python and C versions of a module. The Python version is written to be as clear and obvious as possible -- any bugs should be easy to diagnose and fix. Write your tests against this module. Then write the C version, and test it. Its behavior should in all cases equal that of the Python implementation -- if they differ, it should be very easy to figure out which is wrong and correct the problem. String concatenation is not that bad in Python 2.5. Data point on generators: 2:1 (v2.5.2), 1,5:1,5 (v3.0) - list vs. generators for a processor-hungry function that I've tested yesterday (that is performance is the same on py3k, generators loose on v2.5) To add to that comment: the reason that string concatenation isn't that bad in 2.5 (and 2.6) is that there is a specific optimisation for this case in CPython (but not necessarily any other Python implementation). Tony, can you supply details of the optimization? @John, do you convert the Python equivalent to C using Cython or do you just re-write in C? Does it make a difference? First thing that comes to mind: psyco. It runs only on x86, for the time being. Then, constant binding. That is, make all global references (and global.attr, global.attr.attr…) be local names inside of functions and methods. This isn't always successful, but in general it works. It can be done by hand, but obviously is tedious. You said apart from in-code optimization, so I won't delve into this, but keep your mind open for typical mistakes (for i in range(10000000) comes to mind) that people do. Cython and pyrex can be used to generate c code using a python-like syntax. Psyco is also fantastic for appropriate projects (sometimes you'll not notice much speed boost, sometimes it'll be as much as 50x as fast). I still reckon the best way is to profile your code (cProfile, etc.) and then just code the bottlenecks as c functions for python. I'm surprised no one mentioned ShedSkin: http://code.google.com/p/shedskin/, it automagically converts your python program to C++ and in some benchmarks yields better improvements than psyco in speed. Plus anecdotal stories on the simplicity: http://pyinsci.blogspot.com/2006/12/trying-out-latest-release-of-shedskin.html There are limitations though, please see this I hope you've read: http://wiki.python.org/moin/PythonSpeed/PerformanceTips Resuming what's already there are usualy 3 principles: write code that gets transformed in better bytecode, like, use locals, avoid unnecessary lookups/calls, use idiomatic constructs (if there's natural syntax for what you want, use it - usually faster. eg: don't do: "for key in some_dict.keys()", do "for key in some_dict") whatever is written in C is considerably faster, abuse whatever C functions/modules you have available when in doubt, import timeit, profile This won't necessarily speed up any of your code, but is critical knowledge when programming in Python if you want to avoid slowing your code down. The "Global Interpreter Lock" (GIL), has the potential to drastically reduce the speed of your multi-threaded program if its behavior is not understood (yes, this bit me ... I had a nice 4 processor machine that wouldn't use more than 1.2 processors at a time). There's an introductory article with some links to get you started at SmoothSpan. Run your app through the Python profiler. Find a serious bottleneck. Rewrite that bottleneck in C. Repeat. What if the main bottlenecks are due to library functions that are already written in the NumPy sort of optimized C style? People have given some good advice, but you have to be aware that when high performance is needed, the python model is: punt to c. Efforts like psyco may in the future help a bit, but python just isn't a fast language, and it isn't designed to be. Very few languages have the ability to do the dynamic stuff really well and still generate very fast code; at least for the forseeable future (and some of the design works against fast compilation) that will be the case. So, if you really find yourself in this bind, your best bet will be to isolate the parts of your system that are unacceptable slow in (good) python, and design around the idea that you'll rewrite those bits in C. Sorry. Good design can help make this less painful. Prototype it in python first though, then you've easily got a sanity check on your c, as well. This works well enough for things like numpy, after all. I can't emphasize enough how much good design will help you though. If you just iteratively poke at your python bits and replace the slowest ones with C, you may end up with a big mess. Think about exactly where the C bits are needed, and how they can be minimized and encapsulated sensibly. The above comment only makes sense if you can't use psyco and pyrex for some reason. (Pyrex is a particularly easy way to compile most python language features down to C code and declare variables whose types are compatible with C types, so that they will be handled as such in the compiled code.) Alex, psyco and pyrex doesn't give you a general solution for c-like speed now, and it may never get there. That being said, getting too worried about execution speed is often bad: premature optimization. If you know you need it though, c is often the best way to get there in python. It's often possible to achieve near-C speeds (close enough for any project using Python in the first place!) by replacing explicit algorithms written out longhand in Python with an implicit algorithm using a built-in Python call. This works because most Python built-ins are written in C anyway. Well, in CPython of course ;-) https://www.python.org/doc/essays/list2str/ Just a note on using psyco: In some cases it can actually produce slower run-times. Especially when trying to use psyco with code that was written in C. I can't remember the the article I read this, but the map() and reduce() functions were mentioned specifically. Luckily you can tell psyco not to handle specified functions and/or modules. This is the procedure that I try to follow: import psyco; psyco.full() If it's not fast enough, run the code through a profiler, see where the bottlenecks are. (DISABLE psyco for this step!) Try to do things such as other people have mentioned to get the code at those bottlenecks as fast as possible. Stuff like [str(x) for x in l] or [x.strip() for x in l] is much, much slower than map(str, x) or map(str.strip, x). After this, if I still need more speed, it's actually really easy to get PyRex up and running. I first copy a section of python code, put it directly in the pyrex code, and see what happens. Then I twiddle with it until it gets faster and faster. The canonical reference to how to improve Python code is here: PerformanceTips. I'd recommend against optimizing in C unless you really need to though. For most applications, you can get the performance you need by following the rules posted in that link. If using psyco, I'd recommend psyco.profile() instead of psyco.full(). For a larger project it will be smarter about the functions that got optimized and use a ton less memory. I would also recommend looking at iterators and generators. If your application is using large data sets this will save you many copies of containers. Besides the (great) psyco and the (nice) shedskin, I'd recommend trying cython a great fork of pyrex. Or, if you are not in a hurry, I recommend to just wait. Newer python virtual machines are coming, and unladen-swallow will find its way into the mainstream. A couple of ways to speed up Python code were introduced after this question was asked: Pypy has a JIT-compiler, which makes it a lot faster for CPU-bound code. Pypy is written in Rpython, a subset of Python that compiles to native code, leveraging the LLVM tool-chain. For an established project I feel the main performance gain will be from making use of python internal lib as much as possible. Some tips are here: http://blog.hackerearth.com/faster-python-code There is also Python → 11l → C++ transpiler, which can be downloaded from here.
common-pile/stackexchange_filtered
count business days in calculation Continuing from my previous question: case when date column is greater than sysdate then 'Y' One thing I forgot to consider was including working days in the calculation. Here is the query: select v.voyage "Voyage" ,v.service "Service" ,to_char(vp.eta_date, 'MONTH dd, yyyy') "ETA" ,case when v.service = 'USA' then to_char(vp.eta_date - 2, 'MONTH dd, yyyy') else 'n/a' end as "Notice" ,case CASE WHEN v.service = 'USA' AND vp.eta_date - 2 > sysdate THEN 'Y' ELSE 'N' end as "Sent" from table So I need to exclude Saturday and Sunday in the calculation above. I tried to add this in the where clause: to_char(vp.eta_date, 'DY') NOT IN ('SAT', 'SUN') But the calculation does not seem to be working. If I take vp.eta_date - 5, and I'll use December 22, 2021 for example. I should get the following date: December 16th But I am getting December 17th. This of course leads me to believe that what I tried is not working. How do I fix this? how does adding that to a where clause change the date subtraction? @OldProgrammer - That makes sense. You can compare the date to the date at the start of the ISO week and then increase the number of days depending on which day of the week it is: CASE WHEN v.service = 'USA' AND vp.eta_date - CASE TRUNC(vp.eta_date) - TRUNC(vp.eta_date, 'IW') WHEN 0 THEN 4 -- Monday WHEN 1 THEN 4 -- Tuesday WHEN 2 THEN 2 -- Wednesday WHEN 3 THEN 2 -- Thursday WHEN 4 THEN 2 -- Friday WHEN 5 THEN 2 -- Saturday WHEN 6 THEN 3 -- Sunday END > SYSDATE THEN 'Y' ELSE 'N' END as "Sent" Thank you so much for your help. How would I work it into this: when v.service = 'USA' then to_char(vp.eta_date - 2, 'MONTH dd, yyyy') Just replace 2 with the CASE expression. I have another case that is 5 instead of 2. So it would look like this: when v.service = 'USA' then to_char(vp.eta_date - 5, 'MONTH dd, yyyy') Thoughts? If you subtract 5 working days then there will always be two weekend days in that range so just subtract a total of 7 days. I was working on it right when I saw your comment. Thank you so much for your help. Accepting your answer.
common-pile/stackexchange_filtered
jQuery - strange function behaviour I have the UL list and the code which selects the all parents of the selected LI element (https://stackoverflow.com/a/8883690/106616). Now, I want to clear the selection when I select the other LI element. To do so, I've created that code: (simply, before select the new path, I iterate through the array to clear the previous selection, then I clear the array and while selecting the new path I add new items to that array) $('#nav li').click(function () { //clear the previous selection $.each(myArray, function (i, v) { console.log('loop: ' + v); $('#nav li a[href="' + v + '"]').css('background-color', 'Green'); }); myArray.lenght = 0; //add the new selection $(this).children('a').each(function (item) { myArray.push($(this).attr('href')); console.log('adding: ' + $(this).attr('href')); $(this).css('background-color', 'Red'); }); }); but, that code generates that output if I select the 1st path. adding: #/1210 loop: #/1210 adding: #/1209 loop: #/1210 loop: #/1209 adding: #/1208 If I select the e.g. 2nd path, the output is: loop: #/1210 loop: #/1209 loop: #/1208 adding: #/1188 loop: #/1210 loop: #/1209 loop: #/1208 loop: #/1188 adding: #/1187 I think the output should be (the 2nd path selection) loop: #/1210 loop: #/1209 loop: #/1208 adding: #/1188 adding: #/1187 Can someone explain this for me ? What exactly is the problem? The only one I see is that myArray.lenght = 0; has length misspelled. Instead of changing the background of the actual path to red, only the forst (the top-most) element is red, the others are green The click event originates from an a element. So catch it first before it bubbles to the first li, and make all the as default. Then continue with my solution $('#nav a').click(function() { $('#nav a').css('background-color', 'green'); }); $('#nav li').click(function () { $(this).children('a').css('background-color', 'red'); }); But it's much better to do this whole thing with CSS classes: $('#nav a').click(function() { $('#nav a.current').removeClass('current'); }); $('#nav li').click(function () { $(this).children('a').addClass('current'); }); And in CSS: #nav a { background-color: green; } #nav a.current { background-color: red } Your menu likely has nested li elements so when you click on one, the event bubbles up, triggering your callback and clearing previously selected elements. You can prevent the event from bubbling and just select all of the ancestor li elements to set their children's styles. $('#nav li').click(function () { //clear the previous selection $('#nav li > a').css("background-color", "green"); //add the new selection $(this).parentsUntil("#nav", "li").children("a").css("background-color", "red"); return false; //Prevent the default action and prevent the event from bubbling up. }); You may also want to use a class and define styles for those instead of using inline styles. It is more maintainable in the future if you decide you don't like the colors or want additional styling.
common-pile/stackexchange_filtered
Assigning values to individual array items and calling them If you want to create an array and assign individual values to each item within that array, is this done by declaring the array and then declaring each individual variable within the array separately? : let animals = [ "cat", "dog" ]; let cat = "kitty"; let dog = "doggy"; If this is the correct method, then how would you call an item from the array using, for example, animals[Math.floor(Math.random() * animals.length)] but get the value of the individual variable (e.g. "kitty") and not just the variable name (cat)? Research is not painful you know, and most of the time gets answers faster than posting a question about it and waiting for someone to answer. You'd probably be better off storing them in a JSON object, not an array. I've spent 2 days looking for an answer to this to no avail... ^ I meant a JavaScript object, not a JSON object. See my answer. I doubt that this is a good way of doing what you actually want to do but if you have an array of strings and these strings represent a key in an object you can do the following: const someObject = { cat : "kitty", dog : "doggy" }; const keys = ["cat","dog"]; console.log( someObject[keys[Math.floor(Math.random()*keys.length)]] ) As stated in my comment, you would want to store these in an object. JavaScript objects work with key/value pairs, so each key on the left needs a corresponding value. let animals = { cat: "kitty", dog: "doggy", horse: "horsey" } let animalNames = Object.values(animals) console.log("Random animal: " + (animalNames[Math.floor(Math.random() * animalNames.length)])) console.log(animals.cat) console.log(animals.dog) console.log(animals.horse) Please see There's no such thing as a "JSON Object" and What is the difference between JSON and Object Literal Notation?
common-pile/stackexchange_filtered
scrollview does not scroll in second viewcontroller , but only in first home viewcontroller in my application i have one CameraAppViewController, from it i navigate to another view controller the OverlayViewController and from it i navigate to another view controller ScrollerViewController. I want to have a uiscrollview at the scrollerviewcontroller, but it does not scroll. However when i put the same code for uiscrollview at the first CameraAppViewController it scrolls. I tried all the tricks for changing the content size of the scrollview in comparison to the frame of the view , but nothing worked. I think that the code is correct since it works at the one view controller. I even tried to put it to another project and it worked to both the first and second view controllers. I would appreciate any help. The code i use is the following: UIImage *image1=[UIImage<EMAIL_ADDRESS>UIImage *image2=[UIImage<EMAIL_ADDRESS>UIImage *image3=[UIImage<EMAIL_ADDRESS>NSMutableArray *allImages=[[NSMutableArray alloc] init]; [allImages addObject:image1]; [allImages addObject:image2]; [allImages addObject:image3]; self.view.backgroundColor = [UIColor redColor]; UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; scroll.pagingEnabled = YES; scroll.scrollEnabled = YES; scroll.clipsToBounds = YES; NSInteger numberOfViews = 3; for (int i = 0; i < numberOfViews; i++) { CGFloat yOrigin = i * self.view.frame.size.width; UIView *awesomeView = [[UIView alloc] initWithFrame:CGRectMake(yOrigin, 0, self.view.frame.size.width, self.view.frame.size.height)]; UIImageView *imageView=[[UIImageView alloc] initWithImage:[allImages objectAtIndex:i]]; [awesomeView addSubview:imageView]; awesomeView.backgroundColor = [UIColor colorWithRed:0.5/i green:0.5 blue:0.5 alpha:1]; [scroll addSubview:awesomeView]; } scroll.contentSize = CGSizeMake(self.view.frame.size.width * numberOfViews, self.view.frame.size. height+10); [self.view addSubview:scroll]; This sounds to me like you need to check your delegate connections. I saw your edit, but it was rejected cause you should have put it in your question. Are you setting the delegate in the OverlayViewController as in: @interface OverlayViewController : UIViewController <UIScrollViewDelegate> First do this in .h : @interface SecondViewController : UIViewController <UIScrollViewDelegate> Then do this in .m : UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0,self.view.frame.size.width, self.view.frame.size.height)]; self.scroll.delegate = self;
common-pile/stackexchange_filtered
Solving initial value problem that isn't easily separated We are supposed to write a program to solve the following initial value problem numerically using 4th order Runge-Kutta. That algorithm isn't a problem and I can post my solution when I finish. The problem is, separating it out cleanly into something I can put into Runge-Kutta. $$\exp(-x^\prime)=x^\prime-x+\exp(-t^3)$$ $$x(0)=1$$ Any ideas what type of ODE this is called? I feel more confident with CS skills and programming numerical methods than I do in math... so any insights into this problem would be helpful. This is called an implicit ODE. One method to solve it would be to convert it into a differential-algebraic equation (DAE) and then use a method for solving DAEs. There are DAE solvers based on Runge-Kutta methods. Another possibility is to do a nonlinear solve in the function for computing the right-hand side of the ODE. I mean the following. The standard form for ODE solvers is $x' = f(t,x)$ and if you implement a Runge-Kutta method, your program has to be able to evaluate the function $f$. For your equation, $f(t,x)$ is the solution of $e^{-y} = y - x + e^{-t^3}$, seen as an (algebraic) equation in $y$. If you know a method to solve this equation numerically, you can use that inside your Runge-Kutta program.
common-pile/stackexchange_filtered
How can I redirect an unauthorized user to a login page? I have my own login page. If any user access any page directly (without login), I want to redirect unauthorized user to a login page. How is it possible? Using Generic Handler, is there a chance? Or how can I do it? You can set this behaviour in the web.config Example: (this enables authentication) <authentication mode="Forms"> <forms cookieless="AutoDetect" protection="All" slidingExpiration="true" loginUrl="~/login.aspx"/> </authentication> <authorization> <deny users="?"/> </authorization> (the specified path is excluded from authentication. meaning you can access the file/directory without authentication. useful for image, scripts, styles directories) <location path="login.aspx"> <system.web> <authorization> <allow users="*" /> </authorization> </system.web> </location> Understand, though, that use must now employ the FormsAuthentication class (as explained here: http://msdn.microsoft.com/en-us/library/aa480476.aspx ) Basically the redirect after a successful login must be authorized else it will just keep bouncing your user back to the login aspx.
common-pile/stackexchange_filtered
Teamcity10 + .Net 4.6.1 = wrong MSBuild path After installation .Net 4.6.1 on TeamCity BuildAgents machine I have error in buildstep where I have to use MSBuild 2015. Error say: Unable to find MSBuild at C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe\MSBuild.exe, please check MSBuild environment variable to target to Microsoft .NET Framework 2.0/3.5/4.0 or Mono installation directory Where I can define again path of MSBuild? When I go to Agents >> Agent Parameters >> Environment Variables I have parameter like that: msbuild C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe Uninstall .nets (4.5.1,4.5.2,4.6.1) ane MSbuild and MSbuild Tools did not work. Also try setup new agent but at the end I had the same problem. Try to change msbuild version in build configuration. Already tried that option. Already tried that option. Once it worked (I had change version from 2015:14 for 2015:none), now I have problem on every versions combination. I found solution. I have edited: buildAgent.properties At the end of file I just add: env.msbuild=C:\Program Files (x86)\MSBuild\14.0\Bin Now in Agent Properties is only path without EXE file in.
common-pile/stackexchange_filtered
Searching files in directory using regex and grep So I have to find every file in the /etc directory that start with a,b or c what i have is: grep -l '/^[a-cA-C].*/g' /etc/* though i keep getting every file in the /etc directory. I use grep -lto get every file (I guess using find or grep doesn't matter '/^[a-cA-C].*/g' to find everything that starts with a,b or c uppercase or lowercase followed by zero or more characters ending with a global search so it doesn't stop after the first match I know the regex is right cause i've checked it with a regex-checker online. EDIT: found the solution --> ls /etc/[a-cA-C]* You'd use the command 'ls' rather than 'grep', to find files in a directory. The 'ls' command does not take grep's regular expressions, instead it takes arguments that the shell uses it's own "pattern-matching" to expand to a file list - see http://wiki.bash-hackers.org/syntax/pattern for example. EDIT: Ooops, sorry - did you mean files whose CONTENTS start with 'a', 'b' or 'c'? I mean if there is a file in /etc directory which names start with a,b or c. For example apple.txt it has to return it but if there is a file named windows.txt it should not return the windows file. Great - then my original comment applies, so use the 'ls' command with the patterns in that link :) Here my example: find ./ -type f -exec basename {} \; | grep -Ei '^(a|b|c)' It search recursively and find all files, but return in output only basename of file, is it ok for you? You can try this one: find | grep '^\./[abc]'
common-pile/stackexchange_filtered
Master Public name, Internal name, etcd member pre-built DNS records doesn't resolve to Master external IP address on GCE I created a k8s cluster on GCE (Google Compute Engine) using Kops. After creating the cluster, ran kops validate cluster command which threw following error. unexpected error during validation: unable to resolve Kubernetes cluster API URL dns: lookup api.apic.gcpdemo.cloudtechexpert.net on x.x.x.x.254:53: no such host I looked at the DNS records in managed zone created using Cloud DNS service on GCP and noticed that all following records are pointing to some random IP address which I'm not even able to ping. Do I need to manually point them to master IP address? Is it a known issue? DNS Records api.apic.gcpdemo.cloudtechexpert.net api.internal.apic.gcpdemo.cloudtechexpert.net etcd-a.internal.apic.gcpdemo.cloudtechexpert.net etcd-events-a.internal.apic.gcpdemo.cloudtechexpert.net I don’t think you need to point it to the master IP address manually. Yes, there is a known networking issue going on within the GCP, can you confirm what GKE version are you using? So that I can confirm if it’s related to a known networking issue. Was it working fine before? When you first noticed this issue? Please specify the timestamp along with the time zone. Did you perform any upgrade or configuration changes after which you start to experience this issue? @MuhammadEbaduddin, Thanks for your response. I'm using GCE (NOT GKE) to install the k8s cluster using Kops. This is the 1st time, I'm creating k8s cluster on GCE.
common-pile/stackexchange_filtered
Relation between COM and WinRT I didn't get a clear understanding of similarities/differences or the relation itself between COM (Component Object Model) and WinRT (Windows Runtime). In my understanding both of them are there to provide a "runtime engine" to enable component to communicate... Is that the CLR (Common Language Runtime)? WinRT came in with Windows 8 to enable a common platform for many languages. What I didn't get here is that, did WinRT replace COM? Are they the same? COM is "just" a binary-interface standard for software component (from wikipedia). There is no runtime, no set of base/utility classes (well, there are some, like cross thread/process marshaling, the registry, COM+, but you can do COM without it). COM is used absolutely everywhere in Windows, used in clients and servers, because it's, in its deep heart, "just" a vtable binding contract. WinRT is a full blown API on top of COM (again, no engine). So, it comes with a set of base classes. It's defacto very oriented for UI applications (Windows Store). WinRT also comes with a set of services (metadata, type system, deployment/store, etc.). An useful WinRT introduction is available here: WinRT demystified The CLR is the execution engine that powers .NET programs. It can be used on clients and servers. For example, the garbage collector is implemented there. In fact, it's been ported to other platforms than Windows these last years as an open source project: CoreCLR The Windows CLR uses COM only for some of its work, mostly for communicating with the Windows platform. WinRT does not uses the CLR. *"(...) but you can do COM without it)." -- That's only true for in-process objects which support the current apartment. You can load a DLL and call DllGetClassObject yourself, but this is a really bad practice if you intend to interop with other COM objects. Also, both COM and WinRT provide a lot of infrastructure, accessible through library calls and base classes. So, although they don't define a compulsory and extensive "runtime" like CLR or JVM, they have their "runtime" libraries and classes. @acelent - I never said you couldn't do complex COM. The most simple COM isn't even about Dlls, or interop, it's just a binary contract. I'm arguing the other way around: you shouldn't perform any of the "complexities" of COM yourself. And that there is a library, a set of helper and base classes and a lot of bookkeeping in COM. Windows kernel is written in C language and Windows component are written in C++. When your front end application(say Visual Basic or c#) needs to intact with these components, you need some type of mechanism/standard to interact with these components. This interaction mechanism//standard is called COM. As per Microsoft "COM is a platform-independent, distributed, object-oriented system for creating binary software components that can interact". Please note that you do not need .Net run-time to interact with COM component. It can be called by using old languages like Visual Basic, VC++ etc. Now most the application being developed in .Net and .Net applications have to interact with windows components. Microsoft build a layer(API) on the top of windows component, so that .Net application can be interact with windows component smoothly. This layer is WinRT. As a front end developer, you need to interact with WinRT and WinRT will interact with Windows Component on your behalf. For .Net Applications, WinRT will replace COM eventually. but for Non .Net applications, COM is still alive. WinRT is the base API for metro/modern applications. It is not a COM replacement.
common-pile/stackexchange_filtered
ParallelCollectionRDD.reducebykey(_-_) is not giving correct result I am trying to get value for below reduceByKey function on RDD, however it is not giving the correct result. scala> val test =sc.parallelize(( (1 to 5).map(x=>("key",x)))).reduceByKey(_-_).collect res62: Array[(String, Int)] = Array((key,-3)) Then I tried doing following calculation scala> List (1,2,3,4,5).reduce(_-_) res65: Int = -13 Is this happening because there is no guaranty of order in RDD operations and so reduce function is getting applied in any order whereas in case of List order is guaranteed so reduce function is behaving correctly. This is not a bug but an expected behavior. If you open the doc for reduceByKey you may see (emphasis is mine): Merge the values for each key using an associative and commutative reduce function. Those two properties are essential for parallelization: Associativity means that (a ∗ b) ∗ c = a ∗ (b ∗ c) (where ∗ is operation) Commutativity means a ∗ b = b ∗ a Subtraction is neither associative nor commutative. Thus the result of reduceByKey is undefined. Actually even Scala standard library GenTraversable.reduce says (again emphasis is mine) Reduces the elements of this collection or iterator using the specified associative binary operator. The order in which operations are performed on elements is unspecified and may be nondeterministic. So the claim "whereas in case of List order is guaranteed so reduce function is behaving correctly" is also false. The order on List is an implementation details and theoretically might be changed at any time (although in practice this is not likely to happen because of performance considerations). Just in case you wonder how -3 can be achieved, here is one possible explanation: (-1 - -2 - -3) - (-4 - -5) So it is because of associative and commutative law which subtract operation is not compliant. @ChandramohanSawant Almost. I'd say that it is because the result is undefined if the operation does not conform to the laws (or rather can be any of a quite a few choices). In practice if you think about how Spark is implemented inside, you can clearly see that they can't at the same time do parallel processing and preserve the sequential logic. Since Spark is used for the parallelization, the conforming to the sequeential logic was given up.
common-pile/stackexchange_filtered
Get second, third and so on values I have this problem here The problem has been solved, but my question is how can I get the second value from that, or the third one. The sheet will have many tables and at some point I will need a total for each table. Also, is there any solution to automatically find the the array number which contain date row for each table (instead defining this manually). Hope my explanation make sense. Thank you! Kind regards, L.E. Test file Your question would be much easier to understand if I could look at your spreadsheet. It's very difficult to see any detail on the image. I have added a test file... If I understood your question correctly, instead of breaking the loop when a match to "Total" is found do whatever is needed to be done within the loop like so... var today = toDateFormat(new Date()); var todaysColumn = values[5].map(toDateFormat).map(Number).indexOf(+today); var emailDate = Utilities.formatDate(new Date(today),"GMT+1", "dd/MM/yyyy"); for (var i=0; i<values.length; i++){ if (values[i][0]=='Total'){ nr = i; Logger.log(nr); var output = values[nr][todaysColumn]; // Do something with the output here I"m assuming you email it } } The loop will keep going and find every "Total" and do the same thing. This answer assumes that the "Totals" are in the same column. You can get fancier with this if you only want certain tables to send and not others, but this should get you started. I didn't quite understand the second part of your question... "Also, is there any solution to automatically find the the array number which contain date row for each table (instead defining this manually). Hope my explanation make sense." I'm guessing you want all the rows that contain "Total" in the specific column. You could instantiate a variable as an empty array like so, var totals = [];. Then instead of sending the email or whatever in the first loop you would push the row values to the array like so, totals.push(nr+1) . //adding 1 gives you the actual row number (rows count from 1 but arrays count from 0). You could then simply loop through the totals array and do whatever you wanted to do. Alternatively you could create an array of all the values instead of row numbers like totals.push(values[nr][todaysColumn]) and loop through that array. Lots of ways to solve this problem! Ok based on our conversation below I've edited the "test" sheet and updated the code. Below are my edits All edits have been made in your test sheet and verified working in Logger. Let me know if you have any questions. Spreadsheet: Added "Validation" Tab Edited "Table" tab so the row with "Email Address" in Column A lines up with the desired lookup values (dates or categories)...this was only for the first two tables as all the others already had this criteria. Code: Create table/category selector... In the editor go to File >> New >> HTMLfile Name the file "inputHTML" Copy and paste the following code into that file <!DOCTYPE html> <html> <head> <base target="_top"> </head> <body> <form class="notice_form" autocomplete="off" onsubmit="formSubmit(this)" target="hidden_iframe"> <select id="tables" onchange="hideunhideCatagory(this.value)" required></select> <p></p> <select id="categories" style="display:none"></select> <hr/> <button class="submit" type="submit">Get Total</button> </form> <script> window.addEventListener('load', function() { console.log('Page is loaded'); }); </script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript"> // The code in this function runs when the page is loaded. $(function() { var tableRunner = google.script.run.withSuccessHandler(buildTableList); var catagoryRunner = google.script.run.withSuccessHandler(buildCatagoryList); tableRunner.getTables(); catagoryRunner.getCategories(); }); function buildTableList(tables) { var list = $('#tables'); list.empty(); list.append('<option></option>'); for (var i = 0; i < tables.length; i++) { if(tables[i]==''){break;} list.append('<option>' + tables[i] + '</option>'); } } function buildCatagoryList(categories) { var list = $('#categories'); list.empty(); list.append('<option></option>'); for (var i = 0; i < categories.length; i++) { if(categories[i]==''){break;} list.append('<option>' + categories[i] + '</option>'); } } function hideunhideCatagory(tableValue){ var catElem = document.getElementById("categories"); if(tableValue == "Total Calls By Date" || tableValue == "Total Appointments by Date"){ catElem.style.display = "none" document.required = false; }else{ catElem.style.display = "block" document.required = true; } } function formSubmit(argTheFormElement) { var table = $("select[id=tables]").val(), catagory = $("select[id=categories]").val(); console.log(table) google.script.run .withSuccessHandler(google.script.host.close) .getTotal(table,catagory); } </script> </body> <div id="hiframe" style="display:block; visibility:hidden; float:right"> <iframe name="hidden_iframe" height="0px" width="0px" ></iframe> </div> </html> Edits to Code.gs file Replace code in Code.gs with this... //This is a simple trigger that creates the menu item in your sheet function onOpen() { var ui = SpreadsheetApp.getUi(); ui.createMenu('Run Scripts Manually') .addItem('Get Total','fncOpenMyDialog') .addToUi(); } //This function launches the dialog and is launched by the menu item function fncOpenMyDialog() { //Open a dialog var htmlDlg = HtmlService.createHtmlOutputFromFile('inputHTML') .setSandboxMode(HtmlService.SandboxMode.IFRAME) .setWidth(200) .setHeight(150); SpreadsheetApp.getUi() .showModalDialog(htmlDlg, 'Select table to get total for'); }; //main function called by clicking "Get Total" on the dialogue...variables are passed to this function from the formSubmit in the inputHTML javascript function getTotal(table,catagory) { function toDateFormat(date) { try {return date.setHours(0,0,0,0);} catch(e) {return;} } //get all values var values = SpreadsheetApp .openById("10pB0jDPG8HYolECQ3eg1lrOFjXQ6JRFwQ-llvdE2yuM") .getSheetByName("Tables") .getDataRange() .getValues(); //declare/instantiate your variables var tableHeaderRow, totalRow, tableFound = false; //begin loop through column A in Tables Sheet for (var i = 0; i<values.length; i++){ //test to see if values have already been found if so break the loop if(tableFound == true){break;} //check to see if value matches selected table if (values[i][0]==table){ //start another loop immediately after the match row for(var x=i+1; x<values.length; x++){ if(values[x][0] == "Email Address"){ //This header needs to consistantly denote the row that contains the headers tableHeaderRow = x; tableFound = true; }else if(values[x][0] == "Total"){ totalRow = x; break; } } } } Logger.log("Header Row = "+tableHeaderRow) Logger.log("Total Row = "+ totalRow) var today = toDateFormat(new Date()) var columnToTotal; if(catagory==''){ columnToTotal = values[tableHeaderRow].map(toDateFormat).map(Number).indexOf(+today); }else{ columnToTotal = values[tableHeaderRow].indexOf(catagory); } var output = values[totalRow][columnToTotal]; Logger.log(output); var emailDate = Utilities.formatDate(new Date(today),"GMT+1", "dd/MM/yyyy"); //here is where you would put your code to do something with the output } /** The functions below are used by the form to populate the selects **/ function getTables(){ var cFile = SpreadsheetApp.getActive(); var cSheet = cFile.getSheetByName('Validation'); var cSheetHeader = cSheet.getRange(1,1,cSheet.getLastRow(),cSheet.getLastColumn()).getValues().shift(); var tabelCol = (cSheetHeader.indexOf("Tables")+1); var tables = cSheet.getRange(2,tabelCol,cSheet.getLastRow(),1).getValues(); return tables.filter(function (elem){ return elem != ""; }); } function getCatagories(){ var cFile = SpreadsheetApp.getActive(); var cSheet = cFile.getSheetByName('Validation'); var cSheetHeader = cSheet.getRange(1,1,cSheet.getLastRow(),cSheet.getLastColumn()).getValues().shift(); var catagoriesCol = (cSheetHeader.indexOf("Catagory")+1); var catagories = cSheet.getRange(2,catagoriesCol,cSheet.getLastRow(),1).getValues(); return catagories.filter(function (elem){ return elem != ""; }); } Thank you for your answer, but I already had this done. This problem was solved in the link I provided, but if you can have a look at the file I have updated in my comment would be much easier to understand. I need a loop to find all Totals and then return first Total (row number) when I call it (this was solved using break), then I need second total when I call it and so on .... Also, var todaysColumn = values[5].map(toDateFormat).map(Number).indexOf(+today); ... this is for the second part. As you can see, I have todaysColumn which contains dates. For the first table (look at the file), this will be a fixed value, but I will have more tables and in time I might add some new emails and I need something to find the row with the date for the second (maybe third) table later ... hope make sense.... Thank you! I think this makes sense, and should be doable. You have tables (Total Calls By Date, Total Appointments By Date, Overall, Client 1 etc..) and you wish to get totals for specific items from specific tables and different times and email them? I'll have a look...could you please load your existing code into the test file. Thanks much appreciated. Would you be willing to indicate the exact way the code is run? Trigger (onchange or timed), menu item etc... Also How do you determine whether it's the first or other table to get and send the total from. Additionally, I noticed that only the first two tables have dates the rest (client 1, client 2 etc...) have items. Is this a typical format...do you every need to mine a total from these? Would a functionality of selecting which table you wish to get the total from be helpful? I would like to get total from all tables and totals by current date from tables with date rows. Thank you Thanks Andrei, so for the client/overall columns you want the total for each of the types (Calls Bookings Conversions Booked Appointments Cancelled Appointments Declined Appointments)? Also will you always want all the totals on all the tables or only specific ones at specific times? Just on request ... there will be a button or sub-menu ... thank you !!! Ok...check out rest as well as my edits above and let me know what you think. If his works for you please mark the answer as accepted. Andrei, I discovered an issue with parts of the code and am in in the midst of trouble shooting... Ok got everything working...I made a slight alteration for the test that displays the value in the popup when you select the item to get a total form. Thank you! I'll have a look now! is there any chance to get exactly the same result without using HTML form? To have all Totals rows (index number) in an array and call it based on client or store them in variables? Thank you! You could probably code a script to executive on a timed trigger that gathers all the information based on your predefined list of criteria into a JSON object then pull that information using an in-cell dropdown in conjunction with an onedit trigger.
common-pile/stackexchange_filtered
Can a kraken fling a creature grappled in its mouth, or swallow something grappled in its tentacles? The kraken has the following three actions (bold emphasis mine): Bite. Melee Weapon Attack: +17 to hit, reach 5 ft., one target. Hit: 23 (3d8 + 10) piercing damage. If the target is a Large or smaller creature grappled by the kraken, that creature is swallowed, and the grapple ends. While swallowed, the creature is blinded and restrained, it has total cover against attacks and other effects outside the kraken, and it takes 42 (12d6) acid damage at the start of each of the kraken's turns. If the kraken takes 50 damage or more on a single turn from a creature inside it, the kraken must succeed on a DC 25 Constitution saving throw at the end of that turn or regurgitate all swallowed creatures, which fall prone in a space within 10 feet of the kraken. If the kraken dies, a swallowed creature is no longer restrained by it and can escape from the corpse using 15 feet of movement, exiting prone. Tentacle. Melee Weapon Attack: +17 to hit, reach 30 ft., one target. Hit: 20 (3d6 + 10) bludgeoning damage, and the target is grappled (escape DC 18). Until this grapple ends, the target is restrained. The kraken has ten tentacles, each of which can grapple one target. Fling. One Large or smaller object held or creature grappled by the kraken is thrown up to 60 feet in a random direction and knocked prone. If a thrown target strikes a solid surface, the target takes 3 (1d6) bludgeoning damage for every 10 feet it was thrown. If the target is thrown at another creature, that creature must succeed on a DC 18 Dexterity saving throw or take the same damage and be knocked prone. I believe the intention here is that any creature grappled by the Bite attack can be swallowed, and any creature grappled by a Tentacle can be thrown via Fling. However, by RAW, it seems as though a creature can be grappled by a Tentacle and then immediately swallowed by the next Bite attack, or they can be grappled by the Bite attack and then throw via Fling. Am I reading this correctly, or am I missing some subtle wording that makes it work RAW like how I assume it's supposed to work RAI? The Kraken grapples only with tentacles One important thing you seem to have missed is that unlike most creatures that have the ability to swallow, the kraken's bite attack does not grapple its target. Therefore, it is safe to assume that a kraken is supposed to be swallowing targets grappled by its tentacles. Similarly, because the bite attack does not grapple, flinging a target grappled by the bite does not apply. "the kraken's bite attack does not grapple its target" - Yeah, that'll explain it! Thanks. While completely stupid on the kraken's part, the kraken could also opt to not use its multiattack option at all and simply use the grapple action as part of a normal attack (it would only get one attempt and would deal no damage), at which point it would still be allowed to fling or eat the creature the next turn. D&D 5e does not have "grappled by bodypart X", you are either grappled by a Kraken or you're not. How you end up grappled is irrelevant. @Theik You need a free hand to grapple. A Kraken has no grasping appendages other than tentacles, so if it grapples, it uses a tentacle. @MarkWells Uses a tentacle for the grapple action, yes. But then as far as the rules are concerned, the creature is grappled by the kraken, not grappled by its tentacle.
common-pile/stackexchange_filtered
Merging scalaz-stream input processes seems to "wait" on stdin I have a simple program: import scalaz._ import stream._ object Play extends App { val in1 = io.linesR("C:/tmp/as.txt") val in2 = io.linesR("C:/tmp/bs.txt") val p = (in1 merge in2) to io.stdOutLines p.run.run } The file as.txt contains five as and the file bs.txt contain 3 bs. I see this sort of output: a b b a a b a a a However, when I change the declaration of in2 as follows: val in2 = io.stdInLines Then I get what I think is unexpected behaviour. According to the documentation 1, the program should pull data non-deterministically from each stream according to whichever stream is quicker to supply stuff. This should mean that I see a bunch of as immediately printed to the console but this is not what happens at all. Indeed, until I press ENTER, nothing happens. It's quite clear that the behaviour looks a lot like what I would expect if I was choosing a stream at random to get the next element from and then, if that stream was blocking, the merged process blocks too (even if the other stream contains data). What is going on? 1 - well, OK, there is very little documentation, but Dan Spiewak said very clearly in his talk that it would grab whoever was the first to supply data The problem is in the implementation of stdInLines. It is blocking, it never Task.forks a thread. Try changing the implentation of stdInLines to this one: def stdInLines: Process[Task,String] = Process.repeatEval(Task.apply { Option(scala.Console.readLine()) .getOrElse(throw Cause.Terminated(Cause.End)) }) The original io.stdInLines is running the readLine() in the same thread, so it always waits there until you type something.
common-pile/stackexchange_filtered
Centered Menu w/ CSS jsFiddle I need to center my fixed header nav that is using an unordered list. The middle list item is left empty as I am putting a background image there in its place. Right now it "looks" centered though if you rubberband the browser window you can see that it is not. I can achieve almost middle by reducing the width from 960px to ~780px but I don't want to have to do that. I'm sure I'm overlooking something simple here. Thanks! HTML: <header> <nav> <ul> <li><a class="active" href="#">Home</a></li> <li><a href="#">Portfolio</a></li> <li><a href="#">Services</a></li> <li class="logo"></li> <li><a href="#">Blog</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul> </nav> </header> CSS html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; } /* HTML5 display-role reset for older browsers */ article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } body{ background-color: #ebebeb; } nav { width: 960px; margin: 0 auto; } ul{ list-style-type: none; text-align: center; } li{ display: inline-block; height: 120px; float: left; text-align: center; line-height: 120px; margin-right: 30px; } .logo { height: 130px; width: 164px; background:url(http://samaradionne.com/img/typeBlack.png) no-repeat; } section.stretch{ float: left; height: 1500px; width: 100%; } header{ width: 100%; background: #fff; border-bottom: 1px solid #aaaaaa; position: fixed; z-index: 10; text-align: center; } header a{ color: #969696; text-decoration: none; font-family: sans-serif; text-transform: uppercase; } Check out this thread/answer: http://stackoverflow.com/a/8228669/1375372 I was able to get the header to center by adding "display: inline-block;" to the ul element. and another thread (there must be hundreds) http://stackoverflow.com/a/14511370/1340674 Could also use an inline-table ul { display:inline-table; } http://jsfiddle.net/2GG7Y/13/ You could take the CSS table a step further with li { display:table-cell; } Though, these elements will work in most browsers, you may want to cross test for fallbacks. I like that you're working with tables & cells, which I think would allow me to use vertical-align also would it not? Ideally I'd like to remove the line-height to the li so that it centers vertically with the logo. If you wanted to do that you could just nix the ul display style and go with display:inline-block on your li style. I would move the image outside of the ul as an actual img myself, just to be on the safe side. If (for some awful reason CSS was disabled or not loading), your logo would still show. Plus it's readable content for SEO. alt text for the win. Check out this fiddle. It also uses responsive widths so you're not stuck with a 960px block of content. http://jsfiddle.net/2GG7Y/16/ Add display: inline-block; to the ul and it will properly center Working fiddle: http://jsfiddle.net/2GG7Y/12/ FYI - I did not see the above comments when I answered, they were posted at the same time I suppose set ul to display:inline-block; ul{ list-style-type: none; text-align: center; display:inline-block; } demo: http://jsfiddle.net/2GG7Y/10/
common-pile/stackexchange_filtered
Laravel 5.4 loads welcome page once, then errors out. What's going on? I'm trying to learn Laravel, but it's not working. As the title indicates, I can load the install laravel (via composer create-project --prefer-dist laravel/laravel blog) and run php artisan serve and I get the welcome screen. The issue is that it literally only loads once. I don't even have to make any changes to anything, and if I refresh the page I get a huge stack trace. Whoops, looks like something went wrong. (1/1) FatalThrowableError Call to undefined function Illuminate\Session\ctype_alnum() in Store.php (line 557) at Store->isValidId('YffDpw0QPtFWQR1ax2IoLUxS7BDl2WLhRrw2XEQg')in Store.php (line 546) at Store->setId('YffDpw0QPtFWQR1ax2IoLUxS7BDl2WLhRrw2XEQg')in StartSession.php (line 116) at StartSession->Illuminate\Session\Middleware\{closure}(object(Store))in helpers.php (line 950) at tap(object(Store), object(Closure))in StartSession.php (line 117) at StartSession->getSession(object(Request))in StartSession.php (line 100) at StartSession->startSession(object(Request))in StartSession.php (line 58) at StartSession->handle(object(Request), object(Closure))in Pipeline.php (line 148) at Pipeline->Illuminate\Pipeline\{closure}(object(Request))in Pipeline.php (line 53) at Pipeline->Illuminate\Routing\{closure}(object(Request))in AddQueuedCookiesToResponse.php (line 37) at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))in Pipeline.php (line 148) at Pipeline->Illuminate\Pipeline\{closure}(object(Request))in Pipeline.php (line 53) at Pipeline->Illuminate\Routing\{closure}(object(Request))in EncryptCookies.php (line 59) at EncryptCookies->handle(object(Request), object(Closure))in Pipeline.php (line 148) at Pipeline->Illuminate\Pipeline\{closure}(object(Request))in Pipeline.php (line 53) at Pipeline->Illuminate\Routing\{closure}(object(Request))in Pipeline.php (line 102) at Pipeline->then(object(Closure))in Router.php (line 576) at Router->runRouteWithinStack(object(Route), object(Request))in Router.php (line 535) at Router->dispatchToRoute(object(Request))in Router.php (line 513) at Router->dispatch(object(Request))in Kernel.php (line 176) at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))in Pipeline.php (line 30) at Pipeline->Illuminate\Routing\{closure}(object(Request))in TransformsRequest.php (line 30) at TransformsRequest->handle(object(Request), object(Closure))in Pipeline.php (line 148) at Pipeline->Illuminate\Pipeline\{closure}(object(Request))in Pipeline.php (line 53) at Pipeline->Illuminate\Routing\{closure}(object(Request))in TransformsRequest.php (line 30) at TransformsRequest->handle(object(Request), object(Closure))in Pipeline.php (line 148) at Pipeline->Illuminate\Pipeline\{closure}(object(Request))in Pipeline.php (line 53) at Pipeline->Illuminate\Routing\{closure}(object(Request))in ValidatePostSize.php (line 27) at ValidatePostSize->handle(object(Request), object(Closure))in Pipeline.php (line 148) at Pipeline->Illuminate\Pipeline\{closure}(object(Request))in Pipeline.php (line 53) at Pipeline->Illuminate\Routing\{closure}(object(Request))in CheckForMaintenanceMode.php (line 46) at CheckForMaintenanceMode->handle(object(Request), object(Closure))in Pipeline.php (line 148) at Pipeline->Illuminate\Pipeline\{closure}(object(Request))in Pipeline.php (line 53) at Pipeline->Illuminate\Routing\{closure}(object(Request))in Pipeline.php (line 102) at Pipeline->then(object(Closure))in Kernel.php (line 151) at Kernel->sendRequestThroughRouter(object(Request))in Kernel.php (line 116) at Kernel->handle(object(Request))in index.php (line 53) at require_once('/home/jonathan/Dropbox/Projects/laravel/blog/public/index.php')in server.php (line 21) I've run the following commands to try to remedy the problem php artisan clear-compiled php artisan cache:clear php artisan route:clear php artisan view:clear and I still don't get a welcome page again. I'm running Laravel Framework 5.4.33 on php7 on openSUSE Tumbleweed. What to do? Missing file? Maybe Laravel isn't loading that Session class? You need to install the PHP ctype extension Do check the Laravel docs to ensure that you install all required PHP extensions That fixed it. I'll accept the answer when I can. I didn't see the extensions listed in the page you linked, but I'll do some more searching.
common-pile/stackexchange_filtered
ag (the silver searcher) does not automatically search recursively When performing ag pattern it only searches in the files in the current directory, even when providing --depth NUM>1. Performing ag pattern ./** looks in all subdirectories as well. I am currently using the :Ag command with fzf-vim which also only searches files in the current directory and not any subdirectories. I seem to recall ag searching recursively before, especially with :Ag without any customizations. Is it default behaviour to not search subdirectories for ag? All other fzf searches looks recursively. I have tried different ag commands but expect ag/:Ag to search recursively by default. Which version of ag? I have 2.2.0 and it definitely does recurse. Check whether any of the files in IGNORING FILES in the man page are affecting you. Agree with @JoeP. I have 2.2.0 and mine searches recursively by default. Maybe ignoring/hidden could be the cause, see further at ag (the_silver_searcher) definition of hidden dir and including hidden dirs in search path and related questions.
common-pile/stackexchange_filtered
Array Values as Object Properties with PDO I want to store array values as object properties. I am following an example for mysqli but I want to use PDO instead. I have a user class: class User { public $id; public $username; public $password; public $first_name; public $last_name; public static function find_all_users(){ global $database; $result_set = $database->query($sql); return $result_set; } //end method } //end User class I have connected to my database using the following database class. Note: The constants DB_SERVER etc. are defined elsewhere and included in a file class Database{ public $connection; function __construct(){ $this->open_db_connection(); }//end of constructor public function open_db_connection(){ try{ $this->connection = new PDO('mysql:host='. DB_SERVER .';dbname='. DB_NAME, DB_USER, DB_PASSWORD); $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); }catch(PDOException $e){ echo 'Server Error: ' . $e->getCode(; }//end catch block }//end of method public function query($sql){ $stmt = $this->connection->prepare($sql); $stmt->execute(); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); return $result; } //end query method $database = new Database(); I want to create an object from the User class and use that class' properties to access my data. $user = new User(); $user->id = $result_set['id']; $user->username = $result_set['username']; $user->password = $result_set['password']; $user->first_name = $result_set['first_name']; $user->last_name = $result_set['last_name']; echo $user->id; In mysqli this is would be done by putting the following: public static function find_all_users(){ global $database; $result_set = $database->query($sql); mysqli_fetch_array($result_set); return $result_set; } //end method The error I get is "Undefined index: id" "Undefined index: username" "Undefined index: password" "Undefined index: first_name" "Undefined index: last_name" I think my error is from the fetchAll(PDO::FETCH_ASSOC). I should be getting a value from my echo statement. echo $user->id; What is a better fetch method that works similarly to mysqli_fetch_array for PDO? Below is when I print_r $result_set: You haven't asked a question. What's the problem? ... and even after the last edit, you didn't clarify the situation. Please, tell what's the exact problem, why and what you want to get. You are making a PDO connection but then have a call to mysqli_fetch_array() which isn't going to work. find_all_users should just return the value from $database->query($sql). Although $sql doesn't seem to be defined anywhere either... If you want an object why not use PDO::FETCH_OBJ fetchAll() returns a 2-dimensional array. You need to loop over the elements: $all_users = array(); foreach ($result_set as $result) { $user = new User(); $user->id = $result['id']; $user->username = $result['username']; $user->password = $result['password']; $user->first_name = $result['first_name']; $user->last_name = $result['last_name']; $all_users[] = $user; echo $user->id; } So where is $result_set coming from? @Dharman I assumed it was $result_set = $db->query("SELECT ...");
common-pile/stackexchange_filtered
webpack get source file not transpiled on browser I would like to see on browser original source code (in development environment) for debug. I'm having some problem with sourcemaps. For example in this question I'll use the source code of a React component src/DefaultLoadingComponent.js: const DefaultLoadingComponent = ({ SkeletonProps = {} }) => { const classes = makeStyles(themeMaker)(); return ( <Skeleton animation="pulse" variant="rect" height={40} className={classes.rounded5} {...SkeletonProps} /> )} Using devtool: "source-map" File with .map extension is created under dist folder, in browser I can't see source files, so I'm not able to debug. Inside dist/main.js.map I can see source code as expected. const DefaultLoadingComponent = ({\n SkeletonProps = {}\n}) => {\n\n const classes = makeStyles(themeMaker)(); \n\n return ( \n <Skeleton \n animation=\"pulse\" \n variant=\"rect\" \n height={40} \n className={classes.rounded5}\n {...SkeletonProps}\n />\n ) I get the same result using: devtool: false, plugins: [new webpack.SourceMapDevToolPlugin({ filename: '[name].js.map', publicPath: absolute_url_to_dist_folder })] Using devtool: "eval-source-map" File with .map extension is not created under dist folder, in browser I can see transpiled files under /top/webpack-internal://. The content depends on babel-loader configuration or .babelrc content. Here is devDependencies related to babel in package.json: "@babel/core": "^7.14.6" "@babel/plugin-proposal-class-properties": "^7.14.5", "@babel/preset-env": "^7.14.5", "@babel/preset-react": "^7.14.5", "babel-loader": "^8.2.2" Here is .babelrc file content: { "presets": [ [ "@babel/preset-env", { "modules": "auto", "targets": { "browsers": [ "last 2 Chrome versions", "last 2 Firefox versions", "last 2 Safari versions", "last 2 iOS versions", "last 1 Android version", "last 1 ChromeAndroid version", "ie 11" ] } } ], ["@babel/preset-react"] ], "compact" : "auto", } On browser under top/webpack-instal://src/DefaultLoadingComponent.js I get: var DefaultLoadingComponent = function DefaultLoadingComponent(_ref) { var _ref$SkeletonProps = _ref.SkeletonProps, SkeletonProps = _ref$SkeletonProps === void 0 ? {} : _ref$SkeletonProps; var classes = (0,_mui_styles__WEBPACK_IMPORTED_MODULE_2__.default)(_lib_theming__WEBPACK_IMPORTED_MODULE_1__.default)(); return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement(_mui_material_Skeleton__WEBPACK_IMPORTED_MODULE_3__.default, _extends({ animation: "pulse", variant: "rect", height: 40, className: classes.rounded5 }, SkeletonProps)); }; Webpack version is: 5.39.0, here is the content of webpack.config.js: { context: __dirname, entry: {main: './src/index.js'}, output: { path: path.resolve( __dirname, '../dist', ), filename: '[name].js', publicPath: '/', library: 'MyLib', }, devtool:'source-map', module: { rules: [ { test: /\.js$/, use: { loader: 'babel-loader', }, exclude: path.resolve(__dirname, 'node_modules/'), }, { test: /\.css$/, use: ['style-loader', 'css-loader', 'postcss-loader'], }, { test: /\.s[ac]ss$/i, use: [ // Creates style nodes from JS strings 'style-loader', // Translates CSS into CommonJS 'css-loader', // Compiles Sass to CSS 'sass-loader', ], }, { test: /\.(png|j?g|svg|gif)?$/, loader: 'file-loader', options: { publicPath:'/wp-content/plugins/myplugin/lib/dist' }, }, ], }, plugins: [ new CleanWebpackPlugin({}), ], } Any way to debug on not transpiled files on browser? As I know that you might see your source code under webpack > . > youSourceHere rather than webpack-internal All configurations was fine. Chrome had Javascript source maps not enabled. Now webpack is configured in this way: devtool: mode === 'development' ? 'eval-cheap-module-source-map' : 'source-map', Source files are under webpack://MyLib/./src/
common-pile/stackexchange_filtered
How to make an iOS AVPlayer recover from a network stall? When I disconnect my device from the Internet while playing a video on an AVPlayer, it stalls after a few seconds but doesn't recover when I reconnect the Internet link. How can I make it recover from that state? I can detect when it runs out of playback buffer and stalls but the problem is to resume the playback when the Internet link is reconnected. I have the same problem http://stackoverflow.com/questions/28059019/avplayer-cannot-resume-upon-wifi-drops-in-ios-8
common-pile/stackexchange_filtered
Retrieving emails that I dumped in Feb and would like to get them back Is it possible to retrieve emails that I deleted in Feb as I didn't think I needed them but in hind sight should have kept them ? Sorry, but no - it's not possible - after 30 days, it's gone. Quoting from here: Notes about deleted emails If you delete an email, it stays in your Trash for 30 days. After 30 days, emails are permanently deleted from the trash. There's only one copy of every Gmail email. If you deleted an email from one place, like a label or a device, it is deleted from Gmail entirely. Gmail groups all replies to an original email together in a single conversation. When you click or tap delete, the entire conversation is deleted, including the original email and any replies. The first point it the one who's relevant for you, but I kept the other two for general knowledge and for the next time an email is deleted.
common-pile/stackexchange_filtered
Elasticsearch remove special characters (from non ascii based language) For english, I could use something like "specialCharactersFilter": { "pattern": "[^A-Za-z0-9]", "type": "pattern_replace", "replacement": "" } } to remove non-text characters. However, for non-ascii language such as asian, the above filter removes all valid non-special characters. How to remove special characters from asian language? If it is Java regex engine in place here, you may use "pattern": "[^\\p{L}\\p{Nd}]" I don't know what you mean by java regex engine , but it seems to work.. (i guess because Elasticsearch is java based and I guess you mean that.) Elasticsearch uses different regex engines, sometimes Lucene, sometimes, java.util.regex. it took some time (7 min to pick an answer ) after posting question It looks like the regex flavor used in pattern_replace filter is java.util.regex. To remove any characters other than any Unicode letter and decimal digit, you may use "specialCharactersFilter": { "pattern": "[^\\p{L}\\p{Nd}]", "type": "pattern_replace", "replacement": "" } To make sure you only keep ASCII digits and remove all Hindi, Tamil etc. digits, you may use a variation like "pattern": "[^\\p{L}0-9]" See the regex demo.
common-pile/stackexchange_filtered
SVN: "repository moved permantly" error when adding a new folder under root I am having a strange problem with SVN: SVN is located in http://local/svn (linux + apache), where I have several repos: http://local/svn/repo1, http://local/svn/repo2 etc My SVN client is in Windows and the folder is c:\mysvn. When I commiting an existing sub-folder (e.g. http://local/svn/repo1/folder1), everything works OK! When I add and try to commit a new sub-folder in Windows (e.g. c:\mysvn\repo1\folder2) I get the error: "Repository moved permantly to http://local/svn/repo1; please relocate" When I try to relocate, I get the same error. This happens to all repos I have. It didn't happen before, but I can not recall any recent changes on the CentOS server. Here is my /etc/httpd/conf.d/subversion.conf <Location /svn> DAV svn SVNParentPath /var/www/svn AuthType Basic AuthName "Subversion repos" AuthUserFile /etc/svn-users Require valid-user </Location> And the access_log file from apache: <IP_ADDRESS> - - [21/Nov/2013:11:14:10 +0200] "OPTIONS /svn/archives HTTP/1.1" 401 482 "-" "SVN/1.8.4 (x64-microsoft-windows) serf/1.3.2 TortoiseSVN-<IP_ADDRESS>01" <IP_ADDRESS> - gary [21/Nov/2013:11:14:10 +0200] "OPTIONS /svn/archives HTTP/1.1" 301 325 "-" "SVN/1.8.4 (x64-microsoft-windows) serf/1.3.2 TortoiseSVN-<IP_ADDRESS>01" <IP_ADDRESS> - gary [21/Nov/2013:11:14:10 +0200] "PROPFIND /svn/archives HTTP/1.1" 301 325 "-" "SVN/1.8.4 (x64-microsoft-windows) serf/1.3.2 TortoiseSVN-<IP_ADDRESS>01" Thank you I finally found a workaround, based on this message http://tigris-scm.10930.n7.nabble.com/TortoiseSVN-1-4-0-Build-7195-fails-when-Apache-sends-301-Redirect-td39856.html I added the following line in subversion.conf BrowserMatch "TortoiseSVN" redirect-carefully
common-pile/stackexchange_filtered
SQL Server Reporting Services LocalDB doesn't exist error I've been trying to view deployed reports in SSRS using Visual Studio 2015 and SQL Server 2014, but this is the error message I've been receiving: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. The specified LocalDB instance does not exist. ) This is what my connection string looks like: Data Source=(localdb)\VIRAJ-PC;Initial Catalog=AdventureWorks2012 I've done numerous things to troubleshoot this problem including editing the firewall settings to open ports 1433 and 1434 that need to be accessed, made sure that the MSSQLSERVER service was running, configured the local server to allow incoming connections, have turned on TCP/IP and Named Pipes protocols through the configuration manager, and have checked to see if the LocalDB instance is running through sqllocaldb.exe in the command line (it is running). If it matters at all, I'm using SQL Server Management Studio 2016. I don't want to have to do an uninstall as I've done so two or three times already because of previous errors and have gone through a lot of configuration so if there's a way to fix this without having to just reinstall, I would appreciate it. Do you get this error during the deploy process, or after the deploy succeeds when running the report? Is the SSRS service local, or remote? After the deploy succeeds and when running the report. The SSRS service is local. Are you sure the the database is on the (localdb) instance? Or, do you have a full version of SQL Server installed, and the database is there? It seems odd that adventure works would be on (localdb). Yep, AdventureWorks is on (localdb), I attached it to the instance manually. Do you think putting AdventureWorks under a different instance would possibly help things or no? I can't say for sure, it may be worth a try. It is strange that SSRS can't seem to find (localdb). Then again, there may limitations with (localdb) that are keeping that from happening.
common-pile/stackexchange_filtered
How to create a model and its generic relations on one page I have this setup: class Observation(models.Model): start_time = models.DateTimeField() measurements = generic.GenericRelation(Measurement) class Measurement(models.Model): variable = models.ForeignKey(Variable) value = models.CharField(max_length=300, blank=True) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') These are simplified models of course. Measurement needs to be generic because it is also used elsewhere. I want to make a page on which I can create an Observation and the related Measurements. The user should be able to add Measurements that are not yet present on the observation. I have a working ModelForm for Measurement. I keep running into relations not existing, and I think I am making a silly mistake involving generic_inlinemodelform. I have searched but cannot find an example for this. Can anyone help me out, either by providing an example or linking to it? You should be able to save them using commit = False in your views. forms.py: class MeasurementForm(forms.ModelForm): class Meta: model = Measurement fields = ('variable', 'value') class ObservationForm(forms.ModelForm): class Meta: model = Observation template: <form method='POST> <legend>Observation</legend> {{ observation_form.as_p }} <legend>Measurement</legend> {{ measurement_form.as_p }} <input type='submit' value='submit' /> </form> views.py: def new_observation(request): if request.method=='POST': observation_form = ObservationForm(request.POST) measurement_form = MeasurementForm(request.POST) if observation_form.is_valid() and measurement_form.is_valid(): observation_instance = observation_form.save() measurement_instance = measurement_form.save(commit=False) measurement_instance.content_object = observation_instance measurement_instance.save() return HttpResponseRedirect(observation_instance.get_absolute_url()) else: observation_form = ObservationForm() measurement_form = MeasurementForm() context = { 'observation_form':observation_form, 'measurement_form':measurement_form,} return render_to_response('add-observation.html', context, context_instance=RequestContext(request)) That looks promising, I just need multiple measurements per observation so I'll try to translate this to formsets myself and then get back to you hey @dyve it's been a while but I just stumbled upon this question. Could you please share how you eventually solved this? Somehow never saw that last comment. I ended up using something based on this solution and a custom form generator that added the specific fields for each variable based on the observation instance.
common-pile/stackexchange_filtered
1 Steven Lara: The construction crew started from the valley floor and they're working upward. That's standard practice - you always begin highway construction at the lowest elevation point. 2 Atkins: But why not just start from both ends and meet in the middle? Wouldn't that be faster? 3 Steven Lara: Think about drainage and material flow. Water naturally runs downhill, so if you're doing excavation and grading from the bottom up, you can control runoff better. 4 Atkins: That makes sense for the earthwork, but what about when they lay the actual road surface? I noticed they're banking those curves pretty steeply. 5 Steven Lara: That's superelevation - banking the roadway toward the inside of the curve. When a vehicle goes around a curve, it needs centripetal force to stay on the circular path. 6 Atkins: Like when you're on a bike and lean into turns? 7 Steven Lara: Exactly, but cars can't lean. So the road surface itself provides part of that inward force through banking. The steeper the bank, the faster vehicles can safely navigate the curve. 8 Atkins: But there must be a limit. If you bank it too much, wouldn't slow vehicles slide toward the inside? 9 Steven Lara: Good catch. Engineers balance superelevation with friction between tires and pavement. They consider design speed, curve radius, and typical traffic
sci-datasets/scilogues
Why does mvvmcross close current activity when StartActivityForResult is being called? I am new to mobile cross platform development. I am using Xamarin and Mvvmcross to create an application. The problem I am currently faced with is that when I want to make a request to turn on a Bluetooth, calling StartActivityForResult(), my active activity is closing and after clicking on the dialog activity is not shown back. When I used this method before on a simple Xamarin.Android applicaiton it worked as expected, showing a dialog request for turning on bluetooth while activity is on the background still active. The similar problem is also happens when I am using an Intent to start an activity for sending an e-mail via built-in mail app. After sending an e-mail I am not redirected to my application back and my application is being suspended. Here is my method: [Activity(NoHistory = true, ScreenOrientation = ScreenOrientation.Portrait)] public class MainView : MvxAppCompatActivity { ... protected override void OnViewModelSet() { base.OnViewModelSet(); ... var bluetoothAdapter = BluetoothAdapter.DefaultAdapter; if(!bluetoothAdapter.IsEnabled) RequestEnableBluetooth(); ... } public void RequestEnableBluetooth() { Intent turnOnBtIntent = new Intent(BluetoothAdapter.ActionRequestEnable); StartActivityForResult(turnOnBtIntent, 0); } ... } MvvmCross does nothing like that. It is Android that does this. It does not give you any guarantee that your Activity lives on when it goes into background, it may kill it off whenever it likes. However, your problem is that you are using NoHistory = true on your Activity this way no one can return to this Activity when navigated away from it.
common-pile/stackexchange_filtered
Real time usage and difference between left outer join and right outer join If Left outer join is used(select table A left outer join table B), I can have null values in right table(Table B) when data is not matching with left table(Table A). If I change the select query order (select table B left outer join table A), now I can have null data in Table A. So, same operation can be performed by using left outer join. So, what is the use of right outer join? Please help me to get solution on this. For two tables you can reverse the order of the tables and switch the join type from left <-> right and it will be semantically the same. When more than one table is involved this is not the case though. I give an example of that here left outer join and right outer join are, in a sense, redundant. You can write a query using only one of them. They are both provided for the same reason that < and > are both provided. Sometimes one or the other makes more sense for a given logical operation. As for me, I strive to write queries using only join and left outer join. The left outer join makes more sense to me, because it says "keep all the rows in the first table, along with matching rows in other tables". This doesn't mean that right outer join is wrong, just that different people understand things in different ways. Indeed it true that you can do everything with LEFT and INNER joins and of course , but very few times I founded that mixing LEFT, RIGHT and INNER I could show a kind of dependency flow in the query. those few times, I payed special attention to write down the explanation. I think that the remark was times longer that the joins themselves. Of course the Cartesian logic becomes a nightmare @LuisLL . . . I commend you. I am very practiced in SQL with many years of experience writing quite complicated queries and working with other people's code. Yet, whenever I see different types of joins mixed in a from clause, I have stop and think hard about which records are coming from where and which are being filtered -- unless all the joins are the same. known note -- when I wrote this, only God and I understood what I was doing. Now God only knows. I'm very experienced dealing with in SQL bizarre queries, and my experience show that I must dedicate time ahead in those things, because if not, a when I need to come back to them, I'll dedicate more time to convince myself that the query really does the work I intended then... The difference is simple – in a left outer join, all of the rows from the “left” table will be displayed, regardless of whether there are any matching columns in the “right” table. In a right outer join, all of the rows from the “right” table will be displayed, regardless of whether there are any matching columns in the “left” table. Hopefully the example that we gave above help clarified this as well. Should I use a right outer join or a left outer join? Actually, it doesn’t matter. The right outer join does not add any functionality that the left outer join didn’t already have, and vice versa. All you would have to do to get the same results from a right outer join and a left outer join is switch the order in which the tables appear in the SQL statement. SELECT * from TableA LEFT JOIN TableB Same as SELECT * from TableB RIGHT JOIN TableA SELECT * FROM TableA LEFT JOIN TableB All rows in TableA and matching rows in TableB. If no matching row is found in TableB then all the columns of TableB will be replaced by null Example: TableA rows 1 2 3 Table B rows 2 3 4 TableA LEFT JOIN TableB will give the following tuples: (1 NULL) (2 2) (3 3) TableA RIGHT JOIN TableB will give the following tuples: (2 2) (3 3) (NULL 4) TableA OUTER JOIN TableB the following tuples: (1 NULL) (2 2) (3 3) (NULL 4)
common-pile/stackexchange_filtered
Do functionals agree almost everywhere if they agree except on the real-analytic functions? Let $C^\infty(M)$ be the set of smooth functions on some manifold $M$, and suppose we have a pair of functionals $$S_1,S_2:C^\infty(M)\to \mathbb{R}$$ which agree except on the subspace of real-analytic functions. Can we then say that "$S_1=S_2$ almost everywhere"? "Almost everywhere" usually refers to a subset of measure zero when there is some natural measure on the space. Do you have one in mind for $C^\infty(M)$? There are other ways to express that subsets are "thin" in some sense without using a measure, e.g. if they are first Baire category. Which one to use depends on the purpose, what do you want to use your "almost everywhere" for? In my case, $M=S^1$, so I guess I really meant to ask this question with respect to the Wiener measure. Is the answer known in this case? As I recall, Wiener measure is supported on continuous nowhere differentiable functions, so the entire $C^\infty(M)$ has measure $0$. Haha that answers my question then - thanks!
common-pile/stackexchange_filtered
Better chances of getting in if university would like to review my incomplete application? I had recently applied to a somewhat niche Master's program (~100 applicants for ~20 places per year, according to the University's statistics) at a top university (top 5 QS in various disciplines)¹. One of the reasons I hadn't considered this program seriously is because some of my professors limited the number of letters they could write. Given this constraint, I wanted to optimize my chances of getting an admit by applying to other less-competitive programs which also didn't require 3 recommendations while still being a good fit. So, I just filled random information just so I could submit². A few days later, as expected, I got an email stating that my application would not be assessed. However, I now received another email stating that the admissions committee would like to review my application if the references are received. My question is (assuming I'm allowed to edit my references): Does the fact that the committee would still like to review my incomplete application mean that I have a good chance of getting in? i.e. I would like to know if it is worth it to "spend" 3 recommendation letters on this program now? ¹ I mention the ranking only to provide context while keeping the question general. ² I know it was pointless, but I had to "submit" because of reasons I cannot disclose. I thought that since it was incomplete, the admissions committee wouldn't need to waste any time on it. This is not really a question that can be answered here, as it depends on individual factors. I think this is a decision that you have to make: how much would like to get into this program? Is it worth to YOU to spent the recommendation letters? This might also be dependent if you are already accepted somewhere else. To me it seems to signify only that they don't have enough obviously qualified candidates and seek to expand the pool. Better than nothing, but only they can say. Now I'm curious how big people think "niche" is.
common-pile/stackexchange_filtered
Could not open input file: artisan error in react laraval-mix application I have added laravel-mix in my `React application. Below is my code My webpack.mix.js looks like the following let mix = require('laravel-mix'); mix.js('src/scripts.ts', '/dist/') .sass('src/styles.scss', '/dist/') .options({ processCssUrls: false, }) .disableSuccessNotifications() .webpackConfig({ module: { rules: [ { test: /\.tsx?$/, loader: 'ts-loader', exclude: /node_modules/, }, ], }, resolve: { extensions: ['*', '.js', '.jsx', '.vue', '.ts', '.tsx'], }, }); My package.json scripts and dependeinces looks like the following: "scripts": { "dev": "npm run development", "development": "mix", "watch": "mix watch", "watch-poll": "mix watch -- --watch-options-poll=1000", "hot": "mix watch --hot", "prod": "npm run production", "production": "mix --production" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/preset-react": "^7.18.6", "@types/node-polyglot": "^2.4.2", "@types/react": "^17.0.14", "@types/react-dom": "^17.0.9", "@typescript-eslint/eslint-plugin": "^4.28.4", "@typescript-eslint/parser": "^4.28.4", "eslint": "^7.31.0", "eslint-config-prettier": "^8.3.0", "eslint-plugin-prettier": "^3.4.0", "laravel-mix": "^6.0.25", "prettier": "^2.3.2", "sass": "^1.35.2", "sass-loader": "^12.1.0", "stylelint": "^13.13.1", "stylelint-config-idiomatic-css": "^1.1.0", "stylelint-config-sass-guidelines": "^8.0.0", "stylelint-config-standard": "^22.0.0", "ts-loader": "^9.2.3", "typescript": "^4.3.5" }, I am able to successfully compile the application using npm run dev I also get notifications on my desktop Laravel Mix Build Successful, but when I run php artisan serve I get the below error Could not open input file: artisan Anyone has gone through this problem? I am in the root directory when I run this command.
common-pile/stackexchange_filtered
Files does not write into correct partition I created partitions using fdisk and the partitions will automatically attached during startup as I registered them in /etc/fstab as shown: proc /proc proc defaults 0 0 /dev/mmcblk0p1 /boot vfat defaults 0 0 /dev/mmcblk0p4 /mnt/mmcblk0p4 ext4 defaults 0 0 When i type in df -h : Filesystem Size Used Avail Use% Mounted on /dev/root 3.6G 3.1G 279M 92% / devtmpfs 433M 0 433M 0% /dev tmpfs 438M 0 438M 0% /dev/shm tmpfs 438M 19M 419M 5% /run tmpfs 5.0M 4.0K 5.0M 1% /run/lock tmpfs 438M 0 438M 0% /sys/fs/cgroup /dev/mmcblk0p1 44M 23M 21M 53% /boot /dev/mmcblk0p4 3.6G 1.8G 1.6G 53% /mnt/mmcblk0p4 I have a script to write JSON file into /mnt/mmcblk0p4/json/ directory using cronjob every minute. When i unmount using sudo umount -l /mnt/mmcblk0p4 I found out that some JSON files are exist exactly same directory of /mnt/mmcblk0p4/json/ , and the JSON files are using / spaces but not /mnt/mmcblk0p4 's. I seems can't find any related article regarding to this situation. I believed that the JSON files are write into the root partition during startup when the /mnt/mmcblk0p4 partition is still not yet mounted properly. My Questions: How can I prevent this from happening? Any help will be appreciated. Thanks! Use mountpoint to check if /mnt/mmcblk0p4 is a mount point and take the appropriate action in your script (mount, wait, ...). For example, this will echo "Yes" if /mnt/mmcblk0p4 is a mountpoint: $ mountpoint /mnt/mmcblk0p4 && echo "Yes" Thanks @Eduardo. it's works!
common-pile/stackexchange_filtered
How to ignore a local variables list in text? I'm writing the readme (in org-mode) for a new emacs mode, and in the installation instructions we have how to enable the mode on a per-file basis: or at the end of your file: #+BEGIN_SRC emacs-lisp ! Local Variables: ! mode: f90-namelist ! End: #+END_SRC The problem is that this puts the README.org file into our new f90-namelist-mode and not org-mode. Putting another local variables list at the end of the file with # mode: org doesn't work, although putting # -*- enable-local-variables: query -*- lets me accept or reject all of the local variables, and emacs then determines the major mode from the .org file extension. This then precludes having any other local variables I might like to include. Is there a more elegant way to include a literal local variables list in the text? The start of the local variables list should be no more than 3000 characters from the end of the file, and must be on the last page if the file is divided into pages, so you can add a page break before the real list of local variables @giordano Ah, I didn't grok the bit about page breaks! Using C-q C-l to include one worked. Thanks! If you add this as an answer, I'll accept it. Quoting from the Emacs manual: The start of the local variables list should be no more than 3000 characters from the end of the file, and must be on the last page if the file is divided into pages. So to make sure your in text local variables will be ignored, add a page break (C-q C-l) before the real list of local variables or at the end of the file if you don't have local variables: or at the end of your file: #+BEGIN_SRC emacs-lisp ! Local Variables: ! mode: f90-namelist ! End: #+END_SRC ^L This will work for all local variables, not only the major mode. If you don't want to export the page break, just comment it, as suggested by @lunaryorn. You may want to put the page break into a comment to prevent it from being exported. See Comment Lines in the Org manual. @lunaryorn thanks for your suggestion, but if you don't export the page break you'll run into the same problem also in the exported file, so it might not be a good idea commenting it. On the other hand, some exporters might choke at page breaks. And often you don't want to edit the exported file itself. It's exported, after all :) But of course, it depends on the specific situation. Here's how iostream header looks like: // Standard iostream objects -*- C++ -*- ... This is the standard way to specify the mode not only in Emacs, but on the whole of Linux, for all editors, which choose to parse it. I recommend you to go this way. Also, enabling local variables is a faux pas from my viewpoint, as it can lead to a mess that Microsoft Word had with VBA: viruses everywhere. Source code or documents should not execute themselves. This doesn't work because emacs parses the local variables list after the -*- line, so including -*- mode: org -*- doesn't work. I should also point out that we do also include this as a way of specifying our mode, but the problem is Emacs parsing what is supposed to be literal text.
common-pile/stackexchange_filtered
How to pass an array from C to Java over JNI without making a copy in C I have int left = ..., top = ..., width = ..., height = ...; void *pixels = GetScreenshot(left, top, width, height); // use JNI to call SaveImageToGallery ::free(pixels); in Java I have public void SaveImageToGallery(int[] pixels, int width, int height) { // ... } How do I pass pixels to Java function SaveImageToGallery using JNI without making a copy of them? This might be a duplicate of this question: http://stackoverflow.com/questions/3944717/pass-an-array-back-from-a-jni-function-to-without-copying-it (I didn't vote it as one, though, because I have the ability to close Java posts with one flag, and I'm not sure enough to do that here.) We can't do that, but if you have the possibility of changing the signature of SaveImageToGallery() to accept a direct NIO buffer instead of a Java array, then it would be possible with NewDirectBuffer().
common-pile/stackexchange_filtered
use Kallisto in galaxy I want to use Kallisto for sequence alignment in Galaxy. Its description is: a program for quantifying abundances of transcripts from bulk and single-cell RNA-Seq data, or more generally of target sequences using high-throughput sequencing reads. However, I found this field empty: there is no option available for the reference transcriptome. How I use a reference sequence? Can I leave the other configuration by default? this is the link of the tool: https://usegalaxy.org/root?tool_id=toolshed.g2.bx.psu.edu/repos/iuc/kallisto_quant/kallisto_quant/<IP_ADDRESS> You have to click on the dropdown menu and select "Use transcriptome from history", which will allow you to specify your own file. I suspect the default will be built-in human transcriptome. Solution is not tested, so let us know if it actually works.
common-pile/stackexchange_filtered
Yet another 'could not find or load main class' error I have done my due diligence with respect to this problem. I have done searches on google and stackoverflow regarding this problem, and I have tried them all, and am still running into this problem. I am on MS Windows 7 Enterprise. I am running java <IP_ADDRESS>. I have a simple X.java file package p; public class X { public static void main(String[] args) { } } I am compiling the class using "javac -classpath . X.java". I have verified it creates a X.class file. I try to run the program using: java -classpath . p.X I get the error "Error: Could not find or load main class p.X" I have tried using a CLASSPATH environment variables, I have tried -classpath .\X.class, I have tried -cp .\X.class, I have tried -cp ., I have tried all combinations of those things. Nothing seems to work. Help. Your class is in package p so java expects it to load from a subdirectory p. Create a subdirectory p, move X.class into p and then run java -classpath . p.X again. you pleae try this example : you go to your package folder.set your class path for your java class on the folder. c:/p> set classpath = "c:/jdk/bin"; c:/p>javac x.java c:/p>java x.java
common-pile/stackexchange_filtered
create a subdirectory within a new subdirectory in python. Error message Hello I am trying to create a subdirectory called eeg within another subdirectory in the following way: for idx in range(0,5): path = '/Users/fred/Dropbox/1_Mon_Switch/Statistiques/Python/RenameFileBids/Raw/' dest_dir = "{}{}{:02d}{}".format(path,'sub-',idx,'/eeg/') os.mkdir(dest_dir) When I run this code I have the following error message : FileNotFoundError: [Errno 2] No such file or directory: '/Users/fred/Dropbox/1_Mon_Switch/Statistiques/Python/RenameFileBids/Raw/sub-00/eeg/' This code is running fine when I remove the second subfolder /eeg/ the sub-00 directory is created. Could you tell me where I'm wrong? Thank you for your help Use os.makedirs() to create multiple elements at once. os.mkdir requires the parent directory to already exist. Thank you for the tips. Why do you recommend to remove the trailing / ? Code doing a split('/') or equivalent may or may not assume a trailing slash (thus, an empty group at the end) to be valid -- basically, it's more work you're assuming anything you call through will be doing right. Might not cause a problem, but it's generally better to just avoid making work for other components (and thus depending on them being written correctly). Same for //s in names -- supposed to just be ignored except at the first position (where it's legal for the filesystem to treat it specially), but sometimes code is buggy and doesn't ignore it.
common-pile/stackexchange_filtered
Cells do not get cleared after TTL is set in HBase I have an HBase table with the following description: { NAME => 'cf', DATA_BLOCK_ENCODING => 'NONE', BLOOMFILTER => 'ROW', REPLICATION_SCOPE => '0', VERSIONS => '1', COMPRESSION => 'NONE', MIN_VERSIONS => '0', TTL => 'FOREVER', KEEP_DELETED_CELLS => 'FALSE', BLOCKSIZE => '65536', IN_MEMORY => 'false', BLOCKCACHE => 'true' } I put some values in it and then set TTL (30s) on those values with another put operation. First thing I notice is that the timestamps of the cells get updated after the 2nd put. And 30 seconds later, when I do a scan on the table, I still see those cells in the table, however this time with their timestamps updated to the original timestamps. I understand that these cells won't necessarily be deleted until a compaction, but why do they still come up in my scan even though the TTL that I set on them has expired?
common-pile/stackexchange_filtered
Why public Electrum servers serving on websocket (WS) are so rare? Couldn't find a single one. Only TCP or TLS. Am I looking in the wrong place? ( https://1209k.com/bitcoin-eye/ele.php?chain=btc ) They are rare because Electrum and all the other wallets using the protocol do not support it client-side, so nobody setting up an ElectrumX server has any incentive to enable this. ElectrumX requires you to enable individual protocols explicitly. Furthermore, as you can see in the changelog they have only been supported since May 2019.
common-pile/stackexchange_filtered
Change view height on click I have a TextView, which is currently 0dp high and I want it to get 20dp higher with every click of a button <TextView android:layout_alignParentBottom="true" android:layout_width="match_parent" android:layout_height="0dp" android:background="@color/colorPrimary"/> <Button android:layout_centerHorizontal="true" android:layout_width="wrap_content" android:layout_height="wrap_content" /> If it is 0dp high, how is it supposed to be clicked ? The button (which is not 0dp high) is supposed to be clicked, the TextView (which is 0dp high) is not supposed to be clicked You should modify your question then. it says that the view is 0dp high and should get 20dp higher with every click of a button You can change height of textview programmatically as- LayoutParams params = (LayoutParams) textView.getLayoutParams(); params.height = 20; textView.setLayoutParams(params); Now, you can get the previous height and add 20 to it every time button is clicked. I don't know why LayoutParams worded to update the UI . . on the other hand is used to set direct layout hight wont work. my code working fine with static data but when i use room db to get data from db it wont work to update the UI here is code in kotlin V11.layoutParams.height = dpToPx(pointsValue[0]) But as soon as i used LayoutParam on one view all worked . I dont know the reson You can change the height or size of your through sharedpreferences in java simply declare the sharedpreference in the onClick method of your button in android as i have done below, your textView size will be changed on button Click: MainActivity_java Button small = (Button) findViewById(R.id.small); small.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { TextView tv = (TextView) findViewById(R.id.teext); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this.getBaseContext()); tv.setTextSize(sharedPreferences.getFloat("FONT_SIZE", 30/*DEFAULT VALUE*/)); } }); Main_XML <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Say Yes if the size of textView changes" /> <TextView android:id="@+id/teext" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="The Size of text View will change on button click !"/> <Button android:id="@+id/small" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="button"/> </LinearLayout>
common-pile/stackexchange_filtered
I need help installing Linux Mint 18 on a computer with Windows 10 Here's what happened. I shut down my computer. I turned off Secure Boot I put in my (authentic) Linux Mint installation disk into my disk drive I checked the integrity of the media. No errors found. I started Linux Mint. Linux took a long time to start, and then froze on me before it even finished. I went into compatibility mode to check on what was wrong. The computer told me that the metadata of my hard drive was in Windows cache. I shrunk the main partition of my hard drive. I shut down the computer again. (I didn't simply turn it off.) I booted into the disk again. Attempted to start Linux in Compatibility Mode. Told me the NTFS partition I opened up by shrinking the system's main partition was in an unsafe state because I needed to resume Windows and fully shut it down. I tried many things again and again with little success. What's wrong? You need to turn off an option called Fast Startup. Open Control Panel. Go to Power options. Click on the option "Choose what the power buttons do" in the top left corner. Click on "Change settings that are not currently available option". Uncheck "Turn on Fast startup". What is Fast startup? Starting with Windows 8, a fast startup mode is available to start a computer in less time than is typically required for a traditional, cold startup. A fast startup is a hybrid combination of a cold startup and a wake-from-hibernation startup. The fast startup enables to start windows faster by using a hibernation like technology. But this means that Windows is not properly shutdown. It is more or like hibernation. Hence the error message "Resume Windows and fully shut it down". Disable fast startup and you will be fine. When Windows has Hibernate enabled, it writes a file to HDD, hiberfil.sys, that contains the state of the system on shutdown, and it may mark the disk as currently in use. As a safety to prevent loss of data, Linux is refusing to boot. To get rid of hiberfil.sys safely, restart Windows 10 and completely turn off hibernation with the following command in a CMD prompt started with administrative privilege: powercfg -h off You might put that, and the converse, powercfg -h on into two batch scripts, and create shortcuts to them to be run as Administrator, to make turning Hibernate on and off more convenient in a ual boot system. After Hibernate mode is disabled, you can then continue the Linux distro installation.
common-pile/stackexchange_filtered
How to use a different path name in ProxyPass than the Tomcat context name I am using Tomcat 5.5.9 and Apache 2.x We are trying to use a path name in ProxyPass that is different than the Tomcat context name. ProxyPass /path http://localhost:8080/contextname However, this does not work. When these two are the same then everything works fine. Most examples I see on the net also have the path equal to the Tomcat context name. I am using "context.xml" within the Tomcat context and do NOT have "server.xml" entries. Also, I am using plain httd.conf and NOT using any VirtualHost entries. Hint for debugging: Use mod_dumpio to dump the data going back and forth over the connections. I believe you need both ProxyPass /path/ http://localhost:8080/contextname/ ProxyPassReverse /path/ http://localhost:8080/contextname/ Any reason not to use mod_jk? Hello David, I did have both the ProxyPass and ProxyPassReverse commands even though I did not mention it in my message. As for why not use mod_jk I simply need to hide tomcat port from user access URL and nothing else so mod-proxy seems the simplest Fixed the solution - you probably must have the slashes at the end of the URI. This is copied from my conf files. Add a slash to both values: ProxyPass /path/ http://localhost:8080/contextname/ Could you explain how this differs from no-trainlish-slash version? Your problem are probably self-referential URLs that the application produces. There isn't much you can do about it except for changing the app or rewrite everything that it spits out. Option 2 can be very fragile. See the tomcat docs for more info.
common-pile/stackexchange_filtered
Possible to delete rows based on the primary keys with realm and swift? So I basically have two arrays of primary ID's which I am comparing. Simplified version: let A: Set = [1, 3, 5, 7, 9] let B: Set = [2, 3, 5, 7] A.exclusiveOr(B).sort() // [1, 2, 9] I want to delete the primary keys that the result returns (so in this case, I want to delete the primary keys 1,2 and 9 from my database). I checked the documents from Realm.io, and at first glance there doesn't seem to be a way to delete these primary keys. Is there a way that I can delete only the rows where the primary keys from my default.realm database are the ones that are returned from the A.exclusiveOr(B).sort() array?? Thanks in advance! You can delete objects with a given primary key by querying for the objects, then passing the returned Results to Realm.delete(_:). For example, if your primary key is named id: try! realm.write { realm.delete(realm.filter("id IN %@", A.exclusiveOr(B))) }
common-pile/stackexchange_filtered
How to manually setup Grub2-efi to triple boot Linux To install/due-boot Linux on an EFI-capable computer with an pre-existing operating system, like Windows 8, the UEFI - Community Help Wiki at https://help.ubuntu.com/community/UEFI have covered it. Everything happens auto-magically. But I'd like to know what's going on under the hood. E.g., What should I do if I want to manually setup a second Linux system on this machine (on which both pre-existing Windows 8 and newly installed Linux are both booting fine)? The Grub2-efi should have already installed to the EFI boot partition. Do I still need to install it again? Or should I just add an Grub2 boot menu entry instead? Do I still need to install Grub2-efi to my second Linux system's partition? What are the minimum steps to manually setup Grub2-efi for booting this second Linux system on this machine? UPDATE, further reading reveals that when using grub2-install to install grub2-efi, it will call efibootmgr to add an entry to EFI boot. My new new ASUS laptop EFI BIOS doesn't offer a BIOS menu to choose boot media. Each time I need to boot something different, I have to promote it up in BIOS, then save the BIOS, each time!. This would make it cumbersome for triple boot or multiple boot. Is there any easier solution? As a general rule, every Linux distribution will try to install its own boot loader (usually GRUB, but sometimes something else). Also as a general rule, every distribution tries to discover every available distribution, so when it installs its version of GRUB, that latest version will boot both its matched distribution and whatever had been installed before. Unfortunately, things don't always work out perfectly, so you may need to tweak the GRUB configuration manually, reconfigure the system so that another GRUB is the default boot loader, or use a boot manager other than GRUB as the default. In fact, there are so many possibilities that it's impossible to answer your question definitively. You can try it, hope for the best, and post here to to some other forum if you run into problems. You may also want to read up on EFI installations generally. There are three sites that I generally recommend for this: My own page on Linux UEFI installations The Ubuntu community wiki on UEFI Adam Williamson's page on how UEFI works If your firmware's built-in boot manager is unsatisfactory, you may want to install another one. Rod Smith also created rEFInd. It looks like a good choice to me. Once you've installed it it's supposed to scan for EFI-bootable OS's automatically. So you don't have to configure them all manually. Also, you may want to think about how to re-install your boot manager in case it is lost. In a BIOS computer, the problem was that installing a new OS would overwrite the existing boot program. In EFI, the problem is that if you happen to reset the firmware settings (or, in some cases, upgrade the firmware), it will forget where the boot program is. Boot discs are Good To Have, especially linux live discs with working network drivers :). An alternative possibility is the traditional (ab)use of the boot loader of one of your OS's, to provide a menu for all of the others. I.e. add custom entries into its GRUB menu, to chain-load the other loaders. I think it's relatively simple to add the entries, but it's extra complexity and potentially fragile. My Fedora laptop has never been able to boot Windows from GRUB for some reason, and I read other reports of the same. On Ubuntu I find it hard to even get into the GRUB menu (I think it's supposed to be hidden unless it detects another OS?). I recommend avoiding the automatic os-prober from upstream GRUB, at least for booting multiple Linuxes. It requires that you notice kernel upgrades on the other installs, and run update-grub manually.
common-pile/stackexchange_filtered
Compass and ruler construction Given the three line segments below, of lengths a, b and 1, respectively: construct the following length using a compass and ruler: $$\frac{1}{\sqrt{b+\sqrt{a}}} \ \ \text{and} \ \ \ \sqrt[4]{a} $$ Make sure to draw the appropriate diagram(s) and describe your process in words. We are also to use the following axioms and state where they are used: Any two points can be connected by a line segment, Any line segment can be extended to a line, Any point and a line segment define a circle, Points are born as intersection of lines, circles and lines and circles Addition is easy enough. Two more difficult items you need are square root and reciprocal. These require a length defined to be $1.$ Similar triangles and right triangles are used over and over. And semicircles. Main theorem is that a triangle with one edge the diameter of a circle and another vertex on the circle is a right triangle. Are you okay with contracting right angles and replicating angles? If so you can create a right triangle with hypotenuse a and a leg of 1. So... triangle witbone side has a similar triangle with a coresponding leg of 1 and... I don't want to answer for you but I'll give you hints. Forget constructions for a moment. How would we represent $\frac 1k$ and $\sqrt{k}$ geometrically? As $k$ won't necessarily correspond to any integer or rational value, the only way I see off the top of my head to do ratios is via similar triangles. Can you construct two similar triangles $ABC$ and $XYZ$ ($A$ corresponds to $X$, $B$ to $Y$ and $C$ to $Y$) so that $ABC$ has sides of length $BC =a$ and $XYZ$ has a side of length $XY = 1$ any $YZ = AB$? That is $AB$ ~ $XY= 1$ and $BC = a$ ~$YZ=AB$ and $AC$ ~ $XZ$. If so that would mean $\frac {AB}{BC=a} = \frac {XY = 1}{YZ=AB}$ so $AB^2 = a$. So $AB = \sqrt{a}$. So how can we construct such similar triangles? Well, maybe $YZ$ should be $AB$. Thus two triangles $ABC$ ~ $XBA$ where $BC = a$ and $XB = 1$ So construct a line $CBX$ so that $CB=a$ and $BX = 1$. Can you construct a point $A$ so that $ABC$ ~ $XBA$? What if the line $\overline{BA}\perp\overline {CB}$ and $\overline{CA}\perp \overline {AX}$? Finding a line $\perp$ to $\overline {CX}$ and $B$ is straightforward because we have the points. But finding an unknown point $A$ so that $\overline{CA}\perp \overline {AX}$ may not be obvious. But Hint: given a semi-circle any angle from diameter endpoint, to point in the semi-circle, to the other endpoint will be a right angle. So that $\sqrt{a}$. To find $\frac 1a$ is easier. Find similar triangles $ABC$ and $XBA$ as above where $BC = a$, $AB= 1$ and Then $\frac {AB=1}{BC=a} = \frac {XB}{BA = 1}$ so $XB =\frac 1a$. To construct those triangle just create $ABC$ be making a $\perp$ to a line 1 at point $B$. Mark off $C$ one line so $BC = a$ and $A$ on the other. At $A$ construct a $\perp$ to $BC$. Where this perpendicular line intersects the extended $\overline {BC}$, mark as $X$. Can you provide a picture or drawing of the first two similar triangles for reference? Some parts of your answer are quite vague.. Can I provide a picture. No. I can not. But Will Jagy did. His illustrations were exactly what I was trying to describe and he add a way to get ab which you didn't ask for. flea, I bought an inexpensive scanner, the first diagrams I posted were for http://math.stackexchange.com/questions/173016/inscribing-a-rhombus-within-a-convex-quadrilateral Worthwhile investment, uses no ink. I got the simple type, just a single page per scan. Helps with keeping various types of records, I keep copies as jpegs. those drawings I made are at answer http://math.stackexchange.com/questions/173016/inscribing-a-rhombus-within-a-convex-quadrilateral/177351#177351 .........................................
common-pile/stackexchange_filtered
Only redirect the requests for "https://localhost:8000/stripe_checkout/..." I develop a web product in react in my Mac. I need to run sudo PORT=8000 HTTPS=true SSL_CRT_FILE=ssl/localhost-mac/cert.pem SSL_KEY_FILE=ssl/localhost-mac/key.pem ./node_modules/.bin/react-scripts start to launch the frontend. As a result, e.g., https://localhost:8000/#/home launch the home page. I also develop the backend in My mac. In another folder, I need to run yarn start. Then, https://localhost:3000 serves requests from the frontend. At the moment, the frontend and the backend work well together. The current /usr/local/etc/nginx/nginx.conf is as follows. Note that there a server block for 443; there is no server block for 8000. worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; log_format my_log '{ "time": "$time_iso8601", ' '"remote_addr": "$remote_addr", ' '"status": "$status", ' '"request": "$request", ' '"request_method": "$request_method", ' '"http_referrer": "$http_referer", ' '"http_x_forwarded_for": "$http_x_forwarded_for", ' '"host": "$host", ' '"server_name": "$server_name", ' '"upstream_address": "$upstream_addr", ' '"upstream_status": "$upstream_status" }'; access_log /usr/local/var/log/nginx/access.log; upstream videohint { # server <IP_ADDRESS>:443; server localhost:3000; } server { listen 443 ssl; server_name localhost; ssl_certificate /etc/ssl/localhost/localhost.crt; ssl_certificate_key /etc/ssl/localhost/localhost.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_session_timeout 1d; ssl_stapling off; ssl_stapling_verify off; add_header Strict-Transport-Security max-age=15768000; add_header X-Frame-Options ""; proxy_ssl_name "www.videohint.com"; proxy_ssl_server_name on; location ~ /socialLoginSuccess { return 301 https://$host:8000/#/socialLoginSuccess; } location ~ /auth/(.*) { proxy_pass https://videohint/key/auth/$1?$query_string; proxy_set_header Host localhost; } location / { proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Accept-Encoding ""; proxy_set_header Proxy ""; proxy_pass https://localhost:8000/; # proxy_pass https://www.bing.com/ # These three lines added as per https://github.com/socketio/socket.io/issues/1942 to remove socketio error proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } } include servers/*; } Now, I have some special needs. I would like everything to work as before excepts requests for https://localhost:8000/stripe_checkout/...; I want to redirect the requests to https://localhost:8000/stripe_checkout/... to https://checkout.stripe.com/.... Does anyone know how to do it? Try adding this code above to the location / {.....} location /stripe_checkout { proxy_pass https://checkout.stripe.com/; } the current server block is for 443, are you sure your modification will work for localhost:8000? the above code will redirect all /stripe_checkout routes to https://checkout.stripe.com/; but it's still inside server { listen 443 ssl; ...... }, no? Yes. Inside the server { listen 443 ssl; ...... } and just above the location / {.....}
common-pile/stackexchange_filtered
%s format specifier in printf #include <stdio.h> int main() { char str[11] = "HelloWorld"; printf("%s\n",str); printf("%s\n",str+3); /* This Line here is the devil */ printf("%s\n",str[2]); // %s needs an addr not a value. return 0; } Why does that line give a segmentation fault. Is it because %s in printf needs an address and not a value. What is the actual reason ?? You gave it a letter instead of an address. So it tries to access the address "0x6c" (hex of "l") which is almost certainly an invalid address. so accessing that memory location might turn out to be illegal and hence the segmentation fault.. OK.. @Bhargav: Mis-match in format specifier and actual type passed to printf results in an Undefined Behavior, and that is what your example does. If there was a suspected reason, you could have tried removing it and see for yourself. +1 to the answer for good explanation though. str[2] returns a char, not a pointer to a char. So, printf will try to start reading at address 0x6c. Right there, there is a good chance that 0x6c is an invalid address that will cause a segfault. However, if it isn't invalid then printf will keep reading until it reaches a 0x00 character, which very well could enter into an invalid address range. If you want to know precisely why it segfaults, you would need to follow along in a debugger, which might be interesting and educational. If you wanted to fix the crashing line, you could change it to: printf("%s\n", &str[2]); which I would consider to be better style than str+2. That last suggestion I've already known.. I knew this is wrong but just couldn't figure out the precise reason for the segphault :) The second sentence describes one possible behavior of one possible implementation, but there's no fundamental reason it's true. The correct answer is simply that OP broke the interface contract (%s requires a pointer to char in the corresponding argument position) and thus the behavior is undefined.
common-pile/stackexchange_filtered
Do I understand this MSIL code correctly? I have the following code in C# // test.Program private static void Main() { int x = 5; int y = 100; Console.WriteLine(y + ", " + x); } And I'm reading the IL code, I've never programmed assembly before so I'm asking if what I each line does is correct. .method private hidebysig static void Main () cil managed { // Method begins at RVA 0x2058 // Code size 33 (0x21) .maxstack 3 // maximum stack in this method is 3 .entrypoint // method is initial entry point .locals init ( // reserves memory for x and y variables [0] int32 x, // x variable is reserved on position 0 of the stack [1] int32 y // y variable is reserved on position 1 of the stack ) IL_0000: ldc.i4.5 // integer of 4 bytes in size and the value of 5 is loaded onto the evaluation stack position 0 IL_0001: stloc.0 // put evaluation stack position 0 into the stack position 0, the evaluation stack is emptied IL_0002: ldc.i4.s 100 // integer of 4 bytes in size and the value of 100 is loaded onto the evaluation stack position 0 IL_0004: stloc.1 // put evaluation stack position 0 onto the stack position 1, the evaluation stack is emptied IL_0005: ldloc.1 // load stack position 1 into the evaluation stack position 0 IL_0006: box [mscorlib]System.Int32 // box last valuetype placed on evaluation stack, replace valuetype with reference on evaluation stack position 0, do not empty stack IL_000b: ldstr ", " // put reference to string on evaluation stack position 1 IL_0010: ldloc.0 // load stack position 0 into the evaluation stack position 2 IL_0011: box [mscorlib]System.Int32 // box last valuetype placed on evaluation stack, replace valuetype with reference on evaluation stack position 0, do not empty stack IL_0016: call string [mscorlib]System.String::Concat(object, object, object) // call Concat, pass values on evaluation stack, empty evaluation stack, put result of concat on evaluationstack IL_001b: call void [mscorlib]System.Console::WriteLine(string) // pass first value in evaluation stack IL_0020: ret // return } // end of method Program::Main Do I understand this program correctly? Pretty much; only thing I'd clarify is that the box (IL_0006 and IL_0011) is type specific, so it is explicitly constructing a box of type int (it isn't just the "last valuetype"). Also, "empty evaluation stack" is misleading; that isn't quite right - for example, call consumes a given number of positions - it doesn't "empty" it. There is never an "empty evaluation stack" semantic - it is always "consume a number of values, put back a number of values" (either of which may be zero). When n number of positions are consumed by something (call for example), only top positions are consumed right? And then puts a number of values back on the evaluation stack? I guess this is true, because it's a 'stack' after all, but I'm just asking to be sure. Yes. A hypothetical operation that would read A,B,C,D and produce Y,Z would pop 4 entries from the stack*, calculate the result*, and then would push 2 new entries onto it. (*) not necesarily in that order, but pushes are always the last. Yes, your understanding is almost entirely correct. One thing: IL_0010 does not load from the stack, it loads from the locals. (Locals end up on the runtime stack but at the IL level those are called locals). The OP is describing the "evaluation stack" separately to the locals on the stack, but I agree it would be better to just call them locals. It is correct, although I'd argue a bit with some unclear wording, for example: put evaluation stack position 0 into the stack position 0, the evaluation stack is emptied I'd say put 0th entry from the top of the stack into stack-variable 0th, then pop just because I think a 'less-formal' wording is in most of the times simply clearer to read, but othwerwise, it seems OK. edit: hm.. in an afterthought, I'd say that there are no two things like "the stack" and "the evaluation stack". There's only "the stack". The marked part of the start of visible part of stack, that one with local variables may be called "slots". I'd suppose that with IL, you could just say "local variable Nth" and everything usually would be clear, but I think that several different variables may be mapped to the same slot, so it may cause some confusion. Also, there is no operation like "emptying" when you work with the stack. Only push/pop with a explicitely specified number of entries to be copied.
common-pile/stackexchange_filtered
Fetching columns from three tables in mysql I want to fetch three different columns from three tables(table1,table2 and table3) and the user_id is a reference. Help me for the query in mysql php use joins while trying to fetch http://dev.mysql.com/doc/refman/5.7/en/join.html try reading this add some sample query and output details Use JOIN...You can use multiple tables in your single SQL query. The act of joining in MySQL refers to smashing two or more tables into a single table. SELECT * FROM table1 INNER JOIN table2 ON table1.user_id = table2.user_id INNER JOIN table3 ON table2.user_id = table3.user_id You can use JOINS in SELECT, UPDATE and DELETE statements to join MySQL tables. We will see an example of LEFT JOIN also which is different from simple MySQL JOIN. Read more You can use JOIN query for this. SELECT * FROM table1 as ti1,table2 as ti2,table3 as ti3 WHERE ti1.user_id = ti2.user_id AND ti1.user_id=ti3.user_id
common-pile/stackexchange_filtered
Referencing same hdfs table in my 50 union all statements in impala which is resulting in memory issues Referencing same hdfs table joins in my 50 union all statements in impala which is resulting in memory issues Select a,case statement From a inner join b On a=b Union all Select a,case statement From a inner join b On a=b Union all Select a,case statement From a inner join b On a=b Union all Select a,case statement From a inner join b On a=b Please mention exact error (error stack) you are seeing. does this actually reflect your current query or is just an example? I am wondering why use union all on top of same table
common-pile/stackexchange_filtered
JavaFX exe bundling for x86 windows systems usually I deploy my Java apps as a bundle which contains the JVM, so there's no need to install a JVM on the system. Btw: This is no jnlp applet, this is a normal Swing Application. I did this using ant's fx:deploy. This already works for 64bit systems. My problem is, that I want to deploy this application to a 32bit system and don't get it to work. Here's what I did: I've set up a clean Windows 7 (32bit) instance and installed a 32bit JVM. Now i ran my ant script to build a bundled Java app and it built a App.exe. But when I tried to start this exe by double clicking, I get the following message box If I click OK, I get another message box After this the app is terminated. I did not find anything searching the web relating to bundling for 32/64 bit systems. So I would be very glad if someone can point me in the right direction. Many thanks in advance! Greetings, -chris- Looks like a known bug fixed for an upcoming JavaFX version (currently known as 2.2.40): RT-25715 The Windows launcher generated by the packager fails to load msvcr100.dll on 32-bit OS RT-22610 .exe created by fx:deploy can't be executed due to missing msvcr100.dll On the bug case, the user mentions a work-around: If I give a try to the workaround documented in RT-22610, which is to copy runtime\jre\bin\msvcr100.dll side to my application's launcher binary, it fixes it. I think the bug is fixed in JDK 8, so another possible work-around is to download a JDK 8 early access release and use the packaging tools from there to package a Java 7 application (though I have never tried that and am not sure if it would work). Thanks for your reply, but this is still not working for me. The exe built by jdk8 just does nothing if started. Not even a error message. The wourkaround works here, on 32 bit Win XP in a VirtualBox with a native bundle including java 7 jvm (upadate 45, I think). The remaining question is: How can we get the installer to automatically put the dll in the right place? Did anyone make progress on this? I believe there's a way to specify a custom InnoSetup script to run after app installation is complete, that could copy this file to the right place. If you modify fxbuild to specify "Verbose" mode, you'll see instructions about how to customise the installation this way. got fixed in jdk8u40 and jdk7u55 Just a small modification to @jewelsea's Fix: copying msvcr100.dll into the app/ folder instead putting it right next to the exe also works, and at least it is somewhat hidden away then. If you're generating an MSI you can hack the WXS file used by WIX to automatically copy msvcr100.dll into the app folder. Making FX Deploy verbose will tell you where it's putting the temporary WXS file you can copy and modify and use to override the WXS like you would the program icon for example.
common-pile/stackexchange_filtered
TextMate Edit Latex Bundle Snippet, regex to replace non ascii-characters I'm trying to modify the code from a TextMate snippet in the LaTeX Bundle. This is the code: \section{${1:section name}} % (fold) \label{sec:${2:${1/\\\\\w+\{(.*?)\}|\\\\(.)|(\w+)|([^\w\\\\]+)/(?4:_:\L$1$2$3)/g}}} ${0:$TM_SELECTED_TEXT} % section $2 (end) I want it to also change unicode accented characters into their non accented counterparts, like: a into a é into e í into i ó into o ú into u ñ into n This is what it does: \section{Configuración de diseño} % (fold) \label{sec:configuración_de_diseño} % section configuración_de_diseño (end) This is what I want it to do since latex labels don't support these characters: \section{Configuración de diseño} % (fold) \label{sec:configuracion_de_diseno} % section configuracion_de_diseno (end) changing the code of the labels to this works \label{ssub:${2:${1/(\w+)(\W+$)?|\W+/${1:?${1:/asciify/downcase}:_}/g}}} This is the link Issue #87
common-pile/stackexchange_filtered
How to fix Android compatibility warnings I have an app that is targeting Android 9 and I noticed in the Google Play prelaunch report a new section called Android compatibility. This new section lists warnings or errors related to the usage of unsupported APIs. The following is one of the problems and is listed as a greylisted API. Can someone explain which is the unsupported API in this case? The usage seems to be coming from the Android support library and not my code. StrictMode policy violation: android.os.strictmode.NonSdkApiUsedViolation: Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V at android.os.StrictMode.lambda$static$1(StrictMode.java:428) at android.os.-$$Lambda$StrictMode$lu9ekkHJ2HMz0jd3F8K8MnhenxQ.accept(Unknown Source:2) at java.lang.Class.getDeclaredMethodInternal(Native Method) at java.lang.Class.getPublicMethodRecursive(Class.java:2075) at java.lang.Class.getMethod(Class.java:2063) at java.lang.Class.getMethod(Class.java:1690) at android.support.v7.widget.ViewUtils.makeOptionalFitsSystemWindows(ViewUtils.java:84) at android.support.v7.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:685) at android.support.v7.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:518) at android.support.v7.app.AppCompatDelegateImpl.onPostCreate(AppCompatDelegateImpl.java:299) at android.support.v7.app.AppCompatActivity.onPostCreate(AppCompatActivity.java:98) at android.app.Instrumentation.callActivityOnPostCreate(Instrumentation.java:1342) at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3002) at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180) at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165) at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1816) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6718) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) possibly duplicate, check out here https://stackoverflow.com/questions/9780934/finding-what-violated-strictmode-policy I do not think it is the same problem. The warning I have (note that it is a warning - I do not have any app crashes) is for a NonSdkApiUsedViolation- this is not the same as a StrictModeDiskReadViolation due to disk performing disk operations on the main thread. The warning comes up on the Google Play vitals section. I have faced the same problem any solution you found till now...?? I suppose there nothing we can do right now, just to wait that they fixed these issues in AndroidX (as Support Library won't be updated anymore). As mentioned here the methods use reflection, so why the warning.
common-pile/stackexchange_filtered
Trigger a event when the moving marker reaches a certain latlng I am Using this plugin for moving a marker around a polyline. Here is how the moving marker is initiated. var locations = [ ["LOCATION_1",25.700769, 82.300140], ["LOCATION_2",26.600969, 83.400260], ["LOCATION_3",27.600969, 84.400260], ["LOCATION_4",28.600969, 85.400260], ["LOCATION_5",29.600969, 86.400260], ["LOCATION_6",24.600969, 87.400260], ["LOCATION_7",23.500969, 88.200260], ["LOCATION_8",22.400969, 89.300260], ["LOCATION_9",25.700569, 90.400000] ]; var latlng = array(); for (var i = 0; i < locations.length; i++) { latlngs.push([locations[i][1],locations[i][2]]); } var myMovingMarker = L.Marker.movingMarker(latlngs, [2500,4000,2000,5000,4000,5000,3000,2000,4000], { autostart: true }); I want to popup a message every time the marker reaches the coordinates in locations array. Is there any way to trigger a event whenever the marker reaches a certain latlng coordiantes ? Or is there any other way to bind a popup when the marker reacches a certain point. You'll need to trigger the event handler every time you change latlng and put logic that checks what is the latlng before executing what you want. First register an event that catches start state myMovingMarker.on('start',function(event) { // console log your event console.log(event) }); I am not entirely sure but there should be a property called latlng inside your event.target once you have your latlng myMovingMarker.on('move',function(event) { // ... you already have your lat and lng here // check if your latlng is in your array here if (condition) { myMovingMarker .bindPopup('<b>My popup content !</b>', {closeOnClick: false}) .openPopup() } else { myMovingMarker.closePopup() myMovingMarker.unbindPopup() } });
common-pile/stackexchange_filtered
Setting TTL for expire data from collection Is there a correct way to configure data self-deletion by key using the official mongo driver? The only method that I found in the Mongo-driver module is ExpireAfterSeconds, but I'm not sure how to use it correctly. Here's the repository with what is ready at the moment. You need to create an ttl index on the field which needs to be removed after n seconds. In the below code snippet, have created an expirationTime field on which ttl can be set. After 60 seconds from the expirationTime set in the record, the record will be removed. Following is the code to create a TTL index: var ttl *int32 *ttl = 60 keys := bsonx.Doc{{Key: "expirationTime", Value: bsonx.Int32(int32(1))}} idx := mongo.IndexModel{Keys: keys, Options: &options.IndexOptions{ExpireAfterSeconds: ttl}} _, err := collection.Indexes().CreateOne(context.Background(), idx) if err != nil { fmt.Println("Error occurred while creating index", err) } else { fmt.Println("Index creation success") } Yes, you can use it. The create index part should be done once in the Init() or main method. If the requirement is to delete the record after the ExpirationDate, you can set the value of ttl as 0 and when inserting the record, set the expiration date accordingly. Once the clock time reaches the expirationDate value, the record will be removed.
common-pile/stackexchange_filtered
Wireless headset standard for Dodge Van I just got a 2016 Dodge Caravan that has the DVD entertainment system in it. It comes with 2 headsets to start with but I'm wanting to get a few more. It uses a IR interface. What is the standard that this works on? I'm not looking for a product req (but feel free to comment some), just trying to get a feel for what I need to look for, what options there are out there, and compatibility issues I'll come across. Please post pictures of the headsets. Specifically with any label they may have. They are usually bluetooth, though. I updated the question with the interface type. Really the only thing you need to know is what you've figured out already - the headsets work with IR emmiters built into the entertainment system of the van. There appears to only be one "standard" and searching for "Dodge Caravan IR headset" will give you tons of choices. The only thing I would look at is to make sure the headsets are "dual channel" capable. My van has a dual DVD player so the second row can watch a different movie than the third row. The headsets must be able to handle and separate the two signals for this setup to work. Maybe all the IR headsets are capable of this and some vendors advertise it heavily while others don't. The aftermarket headphones I bought have a simple 1/2 switch to pick a channel. Note that the same headphones will also work in a VW Routan since it's just a re-badged Dodge Caravan, complete with the same DVD entertainment system.
common-pile/stackexchange_filtered
Prove that $E=\{x=(x_n)\in \ell^\infty(\Bbb N): (x_n)_n~~\text{is periodic}\}$ is not complete. Let $E=\{x=(x_n)\in \ell^\infty(\Bbb N): (x_n)~~\text{is periodic}\}$ Defintion: $x=(x_n)$ is periodic means there exists $p\in \Bbb N$ such that, $x_{n+p} =x_n ~~~\forall ~~n\in\Bbb N.$ we define on $E$ the distance $$d(x,y) =\|x-y\|_\infty$$ Prove that $(E,d)$ is not complete. I don't how to prove this. thanks for help By contradiction we assume that E is complete Consider the map $T:E\to E$ such that for $x= (x_n)_n$ we have $$Tx= \left(0,\frac{x_0 +1}{2},0,\frac{x_1 +1}{2},0,\frac{x_2 +1}{2}, \cdots\right) $$ That is $(Tx)_{2n} =0$ and $(Tx)_{2n +1} =\frac{x_n +1}{2}$. Clearly, for $x,y\in E$ we have, $$\|T(x-y)\|_\infty \le\frac{1}{2}\|x-y\|_\infty$$ That is T is contraction since E is complete then any contraction on $E$ should have a fix point. Let $u\in E$ such that $$u =Tu = \left(0,\frac{u_0 +1}{2},0,\frac{u_1 +1}{2},0,\frac{u_2 +1}{2}, \cdots\right) $$ Therefore, $$\begin{cases}u_{2n} = 0\\ u_{2n+1} =\frac{u_n+1}{2}\end{cases}$$ the relation $u_{2n+1} =\frac{u_n+1}{2}$ with $u_1 =\frac{u_0+1}{2}=\frac{1}{2}$ clearly shows that $(u_n)_n$ is not periodic. In fact, $$ u_3 =\frac{u_2+1}{2} =\frac{1}{2}, u_7=\frac{u_3+1}{2} =\frac{\frac12+1}{2} = \frac34,$$$$u_{15}=\frac{u_7+1}{2} =\frac{\frac34+1}{2} = \frac78, u_{31}=\frac{u_{15}+1}{2} =\frac{\frac78+1}{2} = \frac{15}{16}\cdots$$ With further investigation one glimpses that if we set $a_n =u_{4n-1}$ then $$a_{n+1} =\frac{a_n +1}{2}~~~\text{which is not periodic}$$ Then, $u\not\in E$. Conclusion T has no fix point in $E$, therefore, E is not complete. Let us define a sequence $x^i=(x_n^i)_{i,n\in\omega}$ which is Cauchy but not convergent (sorry for the cumbersome notation). We set $x^0$ as the sequence identically $0$, so $x_n^0=0$ for all $n$. Then, let $x^1$ be the sequence such that $x_{2n}^1=0$ and $x_{2n+1}^1=1$(so that we obtain the sequence $(0,1,0,1,\dots)$). As $x^2$, we set the sequence such that $x^2_{2n+1}=1$, $x^2_{4n}=1/2$ and has $0$ in the remaining positions (this is the sequence $(0,1,1/2,1,0,1,\dots))$. We continue this way: the sequence $x^{j+1}$ coincides with $x^j$ in every position except the ones that are divisible by $2^{j+1}$, which are assigned value $1/2^{j}$. This sequence is Cauchy, since $d(x^j,x^k)$, for $j<k$, is $2^{-k}$. But the limit of the sequence is not periodic, since it has $0$ only in its first position. My edit was for a typo in the 2nd-last sentence :$;2^k$ changed to $2^{-k}$. Good example.
common-pile/stackexchange_filtered
How to show progressive curve in matplotlib I have this code right now: import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np fig = plt.figure() ax = fig.gca(projection='3d') x = np.arange(1,6) y = np.arange(5,11) z = np.arange(3,9) for i in range(4): ax.plot([x[i], x[i+1]], [y[i],y[i+1]],[z[i],z[i+1]]) plt.show() I want to show how the curve is progressing(moving). But this doesn't work. It shows the first line and there is no way to move to the next plot, and when I close the window, the program just ends, without showing me the next 3 lines. I also tried adding plt.waitforbuttonpress() in the end, but it didn't help. I am new to python so I might be missing something simple. Thanks for the help! Sounds like you need a 3D animation. Hopefully this is what you want: import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as p3 import matplotlib.animation as animation def move_curve(i, line, x, y, z): line.set_data([[x[i], x[i+1]], [y[i],y[i+1]]]) line.set_3d_properties([z[i],z[i+1]]) fig = plt.figure() ax = fig.gca(projection='3d') x = np.arange(1,6) y = np.arange(5,11) z = np.arange(3,9) i = 0 line = ax.plot([x[i], x[i+1]], [y[i],y[i+1]], [z[i],z[i+1]])[0] ax.set_xlim3d([1, 5]) ax.set_ylim3d([5, 10]) ax.set_zlim3d([3, 8]) line_ani = animation.FuncAnimation(fig, move_curve, 4, fargs=(line, x, y, z)) Edit: to show line growing rather than line moving. The basic idea is to add a point to the line for each frame loop rather than changing the start and end points of the line: import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as p3 import matplotlib.animation as animation def move_curve(i, line, x, y, z): # Add points rather than changing start and end points. line.set_data(x[:i+1], y[:i+1]) line.set_3d_properties(z[:i+1]) fig = plt.figure() ax = fig.gca(projection='3d') x = np.arange(1,6) y = np.arange(5,11) z = np.arange(3,9) i = 0 line = ax.plot([x[i], x[i+1]], [y[i],y[i+1]], [z[i],z[i+1]])[0] ax.set_xlim3d([1, 5]) ax.set_ylim3d([5, 10]) ax.set_zlim3d([3, 8]) line_ani = animation.FuncAnimation(fig, move_curve, 5, fargs=(line, x, y, z)) Edit 2: Update axis limit; draw lines with different color; skip even lines. The basic idea is to: Pass ax as one of fargs so that you can update axis limit with ax. Set up your lines as 4 empty lines and show (or skip) corresponding lines in each frame. By default, different lines will have different color. Here is some codes to start with. Just to be clear, the following code is not the best in design and may or may not fit your needs. But I think it's a good starting point. import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as p3 import matplotlib.animation as animation def move_curve(num, ax, lines, x, y, z): for i in range(num+1): if i % 2 == 1: continue lines[i].set_data([[x[i], x[i+1]], [y[i],y[i+1]]]) lines[i].set_3d_properties([z[i],z[i+1]]) ax.set_xlim3d([1, x[i+1]]) ax.set_ylim3d([5, y[i+1]]) ax.set_zlim3d([3, z[i+1]]) return lines fig = plt.figure() ax = fig.gca(projection='3d') x = np.arange(1,6) y = np.arange(5,11) z = np.arange(3,9) lines = [ax.plot([], [], [])[0] for i in range(4)] line_ani = animation.FuncAnimation(fig, move_curve, 4, fargs=(ax, lines, x, y, z), repeat=False) No, not really. I want to show the first line when the loop runs for the first time, and first & second line when the loop runs for the second time and so on... Is it possible to show plt in the loop itself? Because actually, I am getting the next point when the loop runs, so I want to connect it with the earlier point. @Ank Could you please check out my edit and see if that's what you want? The line will grow rather than moving. You don't have to show plt in the loop because the "plot" will be shown for each frame for interval milliseconds. Is it possible to update the axis also as the line grows? Is it possible to use different colours for different lines? @Ank To update axis, pass ax as an argument and use codes like ax.set_xlim3d([1, x[i+1]]) to update axis limit. To use different colors for different lines, you are essentially plotting multiple lines rather than one line. I would suggest you check the official example and use lines instead of line. If you have a specific MCVE, I suggest you open a new question with all your details. How to pass ax as argument? animation.FuncAnimation(fig, move_curve, 5, ax, fargs=(line, x, y, z)) gives me some error As you suggested, I have opened a new question here: https://stackoverflow.com/questions/49705425/matplotlib-animation-draw-lines-in-different-colours Is it possible to skip one line alternatively? Like join point 1 & 2, and 3 & 4, but skip 2 & 3 and so on? @Ank Your new question seems to be only a copy and paste of your comments here. Again, it will be very helpful if you can provide more descriptions on exact effects you are looking for. That way those real experts will come and help you. Matplotlib animation has a lot of useful options and I highly recommend you looking into them yourself. My skills are limited and I hope the new code can be a good starting point for you.
common-pile/stackexchange_filtered
How do I make Apache finish running Perl scripts after the web browser is closed? I have a Perl script that is activated by an end user clicking on a shortcut in a web browser. The script iterates over a list of hash values. It outputs to the browser some HTML when it inserts a row into the database for each iteration. The environment was Perl, Windows Server 2003 Standard Edition, IIS. I recently migrated to Apache. Traditionally the number of iterations has been small, and most users closed the browser after the page finished loading. Now, we have a case where there are up to 5000 iterations. Now it takes a long time (1 min~) to execute those 5000 iterations. That is not the problem. The problem is that when the user closes the web browser Apache kills the Perl script and we do not finish inserting the rows into the database because the browser doesn't acknowledge the most recently sent html. I have tested this under IIS and after the user closes the web browser, the Perl script continues to run and all the rows are inserted. Is there a setting in the Apache config file that will force Apache to finish running the Perl script even after browser is closed and the socket is dropped? This is what we are doing: foreach my $Destination (sort keys %{$self->{_Destinations}}) { print qq! <td $self->{_bgcolor}>$Destination Queued</td> !; if ($self->{_Data}->Execute(@params)) {&error} } I know we should do all the database inserts and THEN do our print, but this is legacy code and if I could just get Apache to behave like IIS in this regard then I will have time to do a more thorough re-write of this script. You need to put any work that must happen even if the browser is closed / the connection is terminated in a background job. Use a work queue (I like resque, but practically anything will work) and a job processor to retrieve the jobs and do the necessary insertion. Questions about writing that code are best asked on stackoverflow. This is the direction we are heading now. I know this is the correct way to do it; I was just hoping there might be a trick in Apache to hold us over until we can do the re-write. On a Unix server, in your perl scripts you can try ignoring signals, e.g., $SIG{'TERM'}='IGNORE'; $SIG{'HUP'}='IGNORE'; $SIG{'PIPE'}='IGNORE'; This probably isn't helpful if you are running Windows servers. On unices, this could raise other issues.
common-pile/stackexchange_filtered
python multiprocess read data from disk it confused me long time. my program has two process, both read data from disk, disk max read speed 10M/s 1. if two process both read 10M data, is two process spend time same with one process read twice? 2. if two process both read 5M data, two process read data spend 1s, one process read twice spend 1s, i know multi process can save time from IO, but the spend same time in IO, multi process how to save time? It's not possible to increase disk read speed by adding more threads. With 2 threads reading you will get at best 1/2 the speed per thread (in practice even less), with 3 threads - 1/3 the speed, etc. With disk I/O it is the difference between sequential and random access speed that is really important. For example, sequential read speed can be 10 MB/s, and random read just 10 KB/s. This is the case even with the latest SSD drives (although the ratio may be less pronounced). For that reason you should prefer to read from disk sequentially from only one thread at a time. Reading the file in 2 threads in parallel will not only reduce the speed of each read by half, but will further reduce because of non-sequential (interleaved) disk access. Note however, that 10 MB is really not much; modern OSes will prefetch the entire file into the cache, and any subsequent reads will appear instantaneous. reduce the speed? it means multi thread is slower?sorry for my english That's correct, a single-threaded read from disk will be fastest.
common-pile/stackexchange_filtered
is there any way to make this at seaborn scatter plots (gridplots)? python Hi am doing a data analisys and i need to make some scatterplots but i have to do this in a grid of 3x3 plots .for example am reading a csv file and store it as data frame.From this data frame i chose some columns to make those scatter plote. lets supose that the name of the columns are : 1)x 2)y 3)z 4)a 5)b 6)c the scatterplots that i need to make are: 1-4 2-4 3-4 1-5 2-5 3-5 1-6 2-6 3-6 and it must be seen like i used this function sns.pairplots it words fine but i have to do this with a for loop ,is there any way to do this please let me know here is my code : df=pd.read_csv("owid-covid-data.csv") //it has a lot of columns there but i want only 6. states=['total_cases_per_million','total_deaths_per_million','mortality','gdp_per_capita','hospital_beds_per_thousand','population_density'] fig,ax=plt.subplots(3,3,figsize=(5,5)) for i ,state in enumerate(states[0:5]): x_var=state y_var=state sns.scatterplot(data=new_df,x=x_var,y=y_var,ax=ax[i],hue='continent') Yes, there is. Here is an example that shows the structure that you should follow for the grids. Here 4 times 4 and barplots but it works the same way for scatter plots and more plots: The data I used was Spotify data of 160K song. So, the first thing is to define the size of the image AND the grid by gs = gridspec.GridSpec(100,100). The second step is to divide the grip for your plots. In my case: ax1 = fig1.add_subplot(gs[0:45,0:40]) ax2 = fig1.add_subplot(gs[0:45,60:100]) ax3 = fig1.add_subplot(gs[55:100,0:40]) ax4 = fig1.add_subplot(gs[55:100,60:100]) After that, it's all the plots. fig1 = plt.figure(figsize=[30,30]) gs = gridspec.GridSpec(100,100) ax1 = fig1.add_subplot(gs[0:45,0:40]) ax2 = fig1.add_subplot(gs[0:45,60:100]) ax3 = fig1.add_subplot(gs[55:100,0:40]) ax4 = fig1.add_subplot(gs[55:100,60:100]) lead_artists1 = Spotify.groupby('artists')['popularity'].sum().sort_values(ascending=False).head(30) ax1 = sns.barplot(x=lead_artists1.values, y=lead_artists1.index, palette="Blues", orient="h", edgecolor='white', ax=ax1) ax1.set_xlabel('Popularity All time (Count of presence in the dataset Spotify)', c='w', fontsize=16) ax1.set_ylabel('Artist', c='w', fontsize=16) ax1.set_title('30 Most Popular Artists past 100 years', c='w', fontsize=20, weight = 'bold') ###More plots fig1.savefig('...../Graphs/Popularity.png') plt.show() This gave first of all thank you for your answer.But it doesnt helped me alote,am new to this and i said if there is any way to made this with for loop .I have covid data and i need scatter plots , i used sns.pairplot(data,x_var=[],y_var=[],hue=..) where x_vars has the column names that i needed to add in grid at x axes and y_vars respectively but i have an issue it doesnt show me the diagonal plots in the 3x3 grid
common-pile/stackexchange_filtered
How can i implement a background "Timer" in PHP of my page that checks something every X time I want to implement something that do every X time some actions. I want that this thread worker are always executing in my server (PHP). For example: I have a blog and i want that someone process deletes comments with keyword "XXXX". I want that this process can sleep every X minutes and when it wakes up, gain, it will going to delete the comments. I dont want the solution, i only want how can implement this type of process in PHP server (Apache). build a script that does what you want, and trigger it with a cron job at your desired interval. if you have access to your server's terminal, cron is better suited for this, php is not designed to be a daemon You can use a cron job to run a PHP script every x minutes etc All you need to do is make a PHP file to do what you need, and then point the cron to the PHP file and it will run for whatever time you specify If you use something like Plesk or cPanel cronjobs are built in and very easy to use. http://en.wikipedia.org/wiki/Cron Thank you man, have your points. Also i have discovered that Wordpress implements cron job in its framework, is very easy to implement.
common-pile/stackexchange_filtered
How to color just the `\vec` symbol? How do I color only the vector symbol in \vec f? I'm using beamer, so xcolor is already loaded. Extra "points" to an answer that also explains how to fish..and not only gives me the fish. Thanks! How about $\color{red}{\vec{\color{black}{f}}}$ and if you want it a bit more automated \newcommand{\colorvec}[1]{{\color{red}\vec{\color{black}{#1}}}} which is to be used as $\colorvec{g}$ What about $\colorvec{a}+\colorvec{b}$? At least correct it. @egreg done, by adding extra grouping {} You can use \textcolor that works also in math mode: \documentclass{article} \usepackage{xcolor} \newcommand{\rvec}[2][black]{% \textcolor{red}{\vec{\textcolor{#1}{#2}}} } \begin{document} $\vec{x}$ $\rvec{x}$ $\rvec[green]{x}$ \end{document} In this way you're sure that the color change will be limited to this object. I've added an optional argument to change also the color of the variable. Great idea! love it! I'm surprised it didn't come up in other questions of this type. @YossiFarjoun Probably because it's a bad idea to color the arrow. ;-) I meant, for example here. I think that for a presentation, color is great when used sparingly...in this case, I want to have the arrow overlaid...so I want it in a different color to bring the attention to it... The question How to color only a tilde accent was closed as "Duplicate" improper. There is very interesting problem which isn't solved in mentioned post nor here. When you return back to the black color in the nucleus of mathaccent atom, then this color manipulation needs \special or \pdfliteral and the skewchar correction of accent placement is lost. See the following example: $\widetilde{E}\ \widetilde{\special{}E}\ \coloredaccent{red}\widetilde{E}$ which gives the result: Note that the second accent is positioned wrong because here is \special in the nucleus and the skewchar TeX positioning is lost. We need to return to the black color here which expands to such \special or \pdfliteral. How the third accent is created? This surprise follows: \documentclass{article} \usepackage{xcolor} \newmuskip\tmpmudim \newdimen\tmpdim \def\coloredaccent#1#2#3{% #1=color, #2=accent, #3=nucleus {\ifnum\skewchar\textfont1<0 \tmpmudim=0mu \else \calculatemukern{#3}{\char\skewchar\textfont1 } \fi \colorlet{outcolor}{.} \color{#1}\mkern2\tmpmudim #2{\color{outcolor}\mkern-2\tmpmudim#3} } } \def\calculatemukern #1#2{% \setbox0=\hbox{\the\textfont1 #1#2}\setbox1=\hbox{\the\textfont1 #1\null#2}% \tmpdim=\wd0 \advance\tmpdim by-\wd1 \tmpmudim=\expandafter\ignorept\the\tmpdim mu \tmpmudim=288\tmpmudim \tmpdim=16em \divide\tmpmudim by\expandafter\ignorefracpart\the\tmpdim\relax } \def\ignorefracpart#1.#2\relax{#1} {\lccode`\?=`\p \lccode`\!=`\t \lowercase{\gdef\ignorept#1?!{#1}}} \begin{document} $\widetilde{E}\ \widetilde{\special{}E}\ \coloredaccent{red}\widetilde{E}$ \end{document} We need to emulate the skewchar kerning (implemented in TeX) by macros. First, we do measurement of kern between nulcelus and skewchar. The result is in pt. Second, we convert this result to the mu units in order to the result is applicable in \scriptstyle and \scriptscripstyle too. Finally, the \mkern2\tmpmudim and \mkern-2\tmpmudim is used to the correction of the accent placement.
common-pile/stackexchange_filtered
Web page scraping gems/tools available in Ruby I'm trying to scrape web pages in a Ruby script that I'm working on. The purpose of the project is to show which ETFs and stock mutual funds are most compatible with the value investing philosophy. Some examples of pages I'd like to scrape are: http://finance.yahoo.com/q/pr?s=SPY+Profile http://finance.yahoo.com/q/hl?s=SPY+Holdings http://www.marketwatch.com/tools/mutual-fund/list/V What web scraping tools do you recommend for Ruby, and why? Keep in mind that there are thousands of stock funds out there, so any tool I use has to be reasonably quick. I am new to Ruby, but I have experience using lxml to scrape web pages in Python (https://github.com/jhsu802701/dopplervalueinvesting/blob/master/screen.py). Once the pages on 5000+ stocks are downloaded, lxml can scrape them all in just a few minutes. (I remember trying BeautifulSoup but rejecting it because it was too slow.) Yahoo finance actually has many APIs available, you should be using one of those. There are so many scraping gems available in Ruby like Hpricot, Nokogiri and so many. I recommend Nokogiri to scrape static web pages. If you are scraping dynamic web pages (means which involves button click, submit form etc..). I recommend Mechanize which internally uses Nokogiri. Hpricot is no longer has a maintainer. I would recommend using Nokogiri :) I see a list of HTML parsing solutions at https://www.ruby-toolbox.com/categories/html_parsing.html . I'm going with Nokogiri because it's the only one that's still active.
common-pile/stackexchange_filtered
.NET MVC 2 Client-Side Validation and Ajax-Loaded Form I am loading a form onto a page via jquery ajax. Once loaded I was hoping that <%Html.EnableClientValidation(); %> would work as it normally does. It is not, and I am guessing that this is because the form has been added to the DOM after it was initially set, and the client-side validation scripts are not wired to hanlde "live" content. Is this assumption correct? Is there a work-around? I am using the following main scripts to handle client-side validation.... <script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script> <script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script> <script src="/Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script> Note that I am not using... <script src="../../Scripts/jquery.validate.js" type="text/javascript"></script> Although the inclusion of this script seems to make no difference. Also note that I am placing the <%Html.EnableClientValidation(); %> above my form, and so that directive is loaded along with the form via the ajax call. One thing that has helped is that I changed the form that was loading to use the <% using (Html.BeginForm(...)}%> as opposed to just manually typing the tag. I found this hint on this site http://blogs.teamb.com/craigstuntz/2010/09/09/38636/. This has made it so that the elements of the form have the proper classes inserted. But, the script that is supposed to be inserted below the 'close form tag' is still missing. Is this assumption correct? Yes, this assumption is correct. Is there a work-around? Yes, there is. You may take a look at the following blog post which illustrates the how you could proceed to force client side validation for dynamically loaded contents. I read through the blog post, and unless I am missing something, the crux of the solution is to check for validation errors on the submit action of the form with this line of code...if (!Sys.Mvc.FormContext.getValidationForForm(this).validate('submit').length) {...} This does prevent the form from being submitted with errors, but it does not highlight errors as the users moves between fields, and it does not indicate to the user where the error in the form lies. Did I miss something? Also, see my comment above...why does the script for the validation not load below the form?
common-pile/stackexchange_filtered
In Cocos2d, how to release texture from OpenGL memory(GPU)? CCSprite *sprite; sprite.texture = [[CCTextureCache sharedTextureCache] addImage: @"mySpriteImage.png"]; sprite.position = ccp(width/2.0f, height/2.0f); [self addChild:sprite z:2 tag:kTagMySprite]; ... [sprite removeFromParentAndCleanup:YES]; Is there a memory leak in the code above? Is the OpenGL texture released, or does it need to be released from the cache? You don't initialize the sprite! Thus your code can crash! Most questions can be answered by using the right tool. In this case, stackoverflow is not the tool. Instruments is. You can also approach this with Vulcan logic. This piece of code is being used by thousands of developers worldwide. The probability of this code causing a memory leak has to be considered infinitesimal for a software library that has existed for over 3 years. Sorry Sir, I don't have device certificate, not able to attach simulator build to instrument. So asked here and confused with your answer. CCSprite *sprite = [CCSprite<EMAIL_ADDRESS>; sprite.texture = [[CCTextureCache sharedTextureCache] addImage: @"mySpriteImage.png"]; sprite.position = ccp(width/2.0f, height/2.0f); [self addChild:sprite z:2 tag:kTagMySprite]; ... [sprite removeFromParentAndCleanup:YES]; In runtime texture cache is changed. So what about previous texture? released or not? You don't need a device certificate to run Instruments. In this case you add a texture to the cache. You don't remove any texture. So it stays in memory until possibly the device receives a memory warning at which point cocos2d by default removes all unused textures. Thank u Sir, [sprite removeFromParentAndCleanup:YES] won't remove opengl texture? then which call help me to release texture in cache? (in above code) I got solution, One of these call removes texture from CCTextureCache and that removes OpenGL texture (glGenTextures id) . [[CCTextureCache sharedTextureCache] removeTexture:sprite3.texture]; OR [[CCTextureCache sharedTextureCache]<EMAIL_ADDRESS> OR [[CCTextureCache sharedTextureCache] removeTexture:[(CCSprite*)[self getChildByTag:kTagBackground] texture] ];
common-pile/stackexchange_filtered
Is there any way to modify the mail headers in an outgoing message sent using Gmail? I'm interested in doing this to add an "Approved:" header to a Mailman announcements-only list (reference). If you are using the Gmail web interface the answer is no, it's not an available option. However, you can bypass this restriction by sending an email using a script or any other tool where you can control the headers and using the Gmail SMTP to deliver the message. Every programming language allows you to write a script to deliver an email. There's also a ton of pre-packaged scripts you can download, install and customize. Make sure to use Gmail SMTP so that the email will be stored in your Gmail account. You can use Thunderbird to edit and send email messages from your Gmail account. Here's an extension called Header Tools Lite that helps you modify the header info in your email message. So is there a Chrome extension that does it? @Pacerier, not that I'm aware of, and based on my understanding, I would suspect it's not possible at that point in the pipeline. Emails cannot be sent from a browser / client. How any email web app works is by passing a HTTP(S) message to their own servers and then based on their own internal APIs / method, sending the email from their domain. Unless they were to expose header info as a parameter, there is no way to get that info to them via an extension. What Thunderbird is doing is driving the email generation from scratch, so you can do anything you'd like before sending. I use Thunderbird on Windows and added custom headers without an extension, like this person: https://webapps.stackexchange.com/a/11810/27487
common-pile/stackexchange_filtered
can you re-initiate a ui-popover? Since I'm injecting a <span ui-popover></span> after the DOM is constructed I need to reinitiate the popovers otherwise it won't show. Is there away to do that? HTML <div ng-repeat="i in comments"> <div id={{i._id}} class="task" commentId={{i._id}}> {{i.text}} </div> </div> I'm using the external rangy library that injects 's around highlighted texts. You can also inject elementAttirbutes to accommodate these span, This is shown in this part of the code: JS function initHighLighter() { var cssApplier = null; highlighter = rangy.createHighlighter(document); cssApplier = rangy.createClassApplier('highlight-a',{elementAttributes: {'uib-popover':"test"}}/*, {elementAttributes: {'data-toggle':"popover", 'data-placement':"bottom", 'title':"A for Awesome", 'data-selector':"true", 'data-content':"And here's some amazing content. It's very engaging. Right?"}}*/); highlighter.addClassApplier(cssApplier); cssApplier = rangy.createClassApplier('highlight-b', {elementAttributes: {'uib-popover':"test"}}/*, {elementAttributes: {'data-toggle':"popover", 'data-placement':"bottom", 'title':"B for Best", 'data-selector':"true", 'data-content':"And here's some amazing content. It's very engaging. Right?"}}*/); highlighter.addClassApplier(cssApplier); } I'm calling on to highlight parts of the texts, only after I upload them from the server (highlighter1 calls on init highlight written above) JS (function(angular) { 'use strict'; angular.module('myApp', ['ui.bootstrap']) .controller('Controller', function($scope, $http, $timeout) { $http.get('/comments') .success(function(response) { $scope.comments = response; var allEl=[]; var i; for (i=0; i<response.length; i++) { allEl.push(response[i]._id); } $http.post('/ranges', {"commentIds":allEl}) .success(function(result){ result.forEach(function(item){ highlighter1(item.dataAction, item.rangyObject, true); }) }) }); }) })(window.angular); So in the end my DOM is being changed AFTER I initiated everything and then the attributes associated with the span don't do anything. The uipopover tag info says: "UIPopover is a common misrepresentation of UIPopoverController, which is used in iOS to manage the presentation of content in a popover.". Is that what you're asking about? If not, choose the appropriate tags, and provide more context. And post your code: that's what StackOverflow is about. I re-tagged. Not sure why it was necessary to down vote. Don't jump to conclusions. I didn't downvote. I guess your actual tiny snippet of code is actually <span uib-popover></span>? How about providing more context, explaining what you're trying to achieve, posting your code? ok, my apologies. your markup should be (notice the prefix) <span uib-tooltip="hello world"></span> or if you want dynamic content $scope.welcomeMessage = "hello world"; // inside controller .. <span uib-tooltip="{{welcomeMessage}}"></span> if you want to reinitialize the tooltip, you can trigger a $destroy event and have it rebuilt, one way if by using ng-if and setting it to true when you need it. <span ng-if="doneUpdating" uib-tooltip="hello world"></span> It's not working. Maybe I communicated my problem wrong. the is added after the initial page was requested from the server. It is added for specific paragraph. Now, it seems like whatever attribute I'm adding this with, I can't really act upon it, not uib-popover and not ng-if. mcve will be hard to create, I expanded on my problem in the initial question, providing the relevant peaces of the code.
common-pile/stackexchange_filtered
Creating a buffer round a polyline At the moment the code I use creates a buffer extending 1000km from each geometry creating square buffer zones over polygons, lines and points. How can I amend the code so that it creates a 'sausage' buffer around the polyline instead of creating a square extent? Should I create another variable for biggerExtent? This is the polyline current code which I need to amend from the others: if (geometry.type === "polygon" || geometry.type === "multipoint" || geometry.type === "polyline") { var searchExtent = geometry.getExtent(); var biggerExtent = new esri.geometry.Extent(searchExtent.xmin - 1000, searchExtent.ymin - 1000, searchExtent.xmax + 1000, searchExtent.ymax + 1000, new esri.SpatialReference({ wkid : 27700 })); graphic1 = new esri.Graphic(biggerExtent, buffersymbol); buffergraphicsLayer.add(graphic1); bufferExtent = getBufferExtent(); graphic2 = new esri.Graphic(bufferExtent, bufferextentsymbol); buffergraphicsLayer.add(graphic2); I don't know anything about javascript, but you are getting what you asked for - an extent object. The min/max extent of the input data.. There must be another tool / method to do an actual "buffer" of the geometry itself. I see what you mean - I need to isolate the polyline and use a different function with it... The easiest way is to use the buffer method of a geometryservice, samples are here: https://developers.arcgis.com/javascript/jssamples/#search/BufferParameters
common-pile/stackexchange_filtered
Moving and returning a mutable pointer I am working through this Rust tutorial, and I'm trying to solve this problem: Implement a function, incrementMut that takes as input a vector of integers and modifies the values of the original list by incrementing each value by one. This seems like a fairly simple problem, yes? I have been trying to get a solution to compile for a while now, and I'm beginning to lose hope. This is what I have so far: fn main() { let mut p = vec![1i, 2i, 3i]; increment_mut(p); for &x in p.iter() { print!("{} ", x); } println!(""); } fn increment_mut(mut x: Vec<int>) { for &mut i in x.iter() { i += 1; } } This is what the compiler says when I try to compile: Compiling tut2 v0.0.1 (file:///home/nate/git/rust/tut2) /home/nate/git/rust/tut2/src/main.rs:5:12: 5:13 error: use of moved value: `p` /home/nate/git/rust/tut2/src/main.rs:5 for &x in p.iter() { ^ /home/nate/git/rust/tut2/src/main.rs:3:16: 3:17 note: `p` moved here because it has type `collections::vec::Vec<int>`, which is non-copyable /home/nate/git/rust/tut2/src/main.rs:3 increment_mut(p); ^ error: aborting due to previous error Could not compile `tut2`. To learn more, run the command again with --verbose. I also tried a version with references: fn main() { let mut p = vec![1i, 2i, 3i]; increment_mut(&p); for &x in p.iter() { print!("{} ", x); } println!(""); } fn increment_mut(x: &mut Vec<int>) { for &mut i in x.iter() { i += 1i; } } And the error: Compiling tut2 v0.0.1 (file:///home/nate/git/rust/tut2) /home/nate/git/rust/tut2/src/main.rs:3:16: 3:18 error: cannot borrow immutable dereference of `&`-pointer as mutable /home/nate/git/rust/tut2/src/main.rs:3 increment_mut(&p); ^~ error: aborting due to previous error Could not compile `tut2`. To learn more, run the command again with --verbose. I feel like I'm missing some core idea about memory ownership in Rust, and it's making solving trivial problems like this very difficult, could someone shed some light on this? Bear in mind that that set of notes is for a version of Rust that’s about a year old, which is very old for Rust. You will doubtless have noticed various of the differences. Is there somewhere that you could recommend for good rust tutorials, other than rust-lang.org? Some of the tutorials on there even seem to be outdated using ~ and @ rather than box That link is for 0.9, as the URL reveals. Start at http://doc.rust-lang.org/ and you'll be fine, getting up-to-date information. There are a few mistakes in your code. increment_mut(&p), given a p that is Vec<int>, would require the function increment_mut(&Vec<int>); &-references and &mut-references are completely distinct things syntactically, and if you want a &mut-reference you must write &mut p, not &p. You need to understand patterns and how they operate; for &mut i in x.iter() will not do what you intend it to: what it will do is take the &int that each iteration of x.iter() produces, dereference it (the &), copying the value (because int satisfies Copy, if you tried it with a non-Copy type like String it would not compile), and place it in the mutable variable i (mut i). That is, it is equivalent to for i in x.iter() { let mut i = *i; … }. The effect of this is that i += 1 is actually just incrementing a local variable and has no effect on the vector. You can fix this by using iter_mut, which produces &mut int rather than &int, and changing the &mut i pattern to just i and the i += 1 to *i += 1, meaning “change the int inside the &mut int. You can also switch from using &mut Vec<int> to using &mut [int] by calling .as_mut_slice() on your vector. This is a better practice; you should practically never need a reference to a vector as that is taking two levels of indirection where only one is needed. Ditto for &String—it’s exceedingly rare, you should in such cases work with &str. So then: fn main() { let mut p = vec![1i, 2i, 3i]; increment_mut(p.as_mut_slice()); for &x in p.iter() { print!("{} ", x); } println!(""); } fn increment_mut(x: &mut [int]) { for i in x.iter_mut() { *i += 1; } }
common-pile/stackexchange_filtered
Bluetooth pairing without pin code I am a newbie working on bluetooth, and I would like to get some advice regarding the pairing process. I have googled this but I did not find much information ... My goal is simple: I want to do a pairing to a headset without entering a pin. I have an android (nexus S running Android 4.1.2) and an iphone (3GS running ios 6.1.3). If I connect to a device like a Jabra BT3030 (bluetooth headset), the pairing is performed without asking me any pin code. Now I want to do the same from an Ubuntu (with BlueZ 4.6), i.e. I fake a bluetooth headset by enable only the correct service and so on. I disabled the authentication. When I pair my iphone to this device, no pin code is required (as expected), but when I connect from my Android device, it still asks me for a pin code, whereas I would expect to have the same behavior than with the Jabra. Would you have any idea of what I am missing here? Thanks in advance, Best regards, Guillaume Hi pingguo, you got any solution? The Standard password for a Jabra BT3030 is 0000. Many other bluetooth devices have a standard password. For the Case a system only accepts devices with passwords, and u cant enter a pasword on a device without keys :D Maybe the solution is implementing the standard passwords for mutliple devices and use them instead f forcing a connection without password.
common-pile/stackexchange_filtered
Many values of HMM matrices, A and B, tend to zero I'm experimenting with an HMM. I have a sequence of observations (10000) and the original matrices A,B and pi that generated those observations. There are 4 types of observations. What I am trying to do is to train a randomly initialized HMM (initial distributions are near uniform) with different numbers of states in order to see its behavior for numbers of states lower or higher than the one that generated them. The original model that generated the observations had 3 states. I observed that for a number 7 or more states a lot of the matrices' values tend to zero. Is there some explanation for the reason why this would happen? I'm not trying to find why it is happening specifically in my case. I'm not trying to solve a problem of mine. I'm in fact curious to find whether this is something that happens in general and there is some explanation behind this. Thank you. I assume you have limited sequential data, and want to try a very complicated HMM. Suppose you have transition matrix $A$ is $7 \times 7$ and emission matrix $B$ is $7 \times 4$ (assume you have 4 different types of observations), that is $7+7\times7+7\times4=84$ parameters, to fit such a model, it is better to have a sequence with thousands of observations. You may experience a over-fitting problem in HMM. HMM is similar to mixture of Gaussian, that if you increase number of hidden states, the fitting will always be better (in terms of the likelihood to be optimized). As a result, the fitting algorithm will stop easily and find a good enough solution for the data given. I suspect this is why you are seeing most zeros in 7 hidden state transition matrix. I have 4 different type of observations and have used up to 10000 observations in the training observation sequence.
common-pile/stackexchange_filtered
R: how to shape two lists of uneven length to a data frame I have two lists in R: a=c(1,3,7) and b=c(0,2,4,6,8,10). How could I reshape them into a data frame as below: Value type 0 b 1 a 2 b 3 a 4 b 6 b 7 a 8 b 10 b One option is to create a name list and then stack into a two column data.frame stack(list(a = a, b = b)) Or use rep to replicate the object names based on the length of the vector and then create the data.frame data.frame(key = rep(c('a', 'b'), c(length(a), length(b))), value = c(a, b))
common-pile/stackexchange_filtered
Difference between key hash produced by x509 ocspid option and public key of the certificate I am using Openssl Version: 1.1.1d I was trying to debug a mismatch between Issuer key hash returned by ocsp responder and the hash calculated on the public key retrieved from the certificate. In order to check if everything was alright with the certificate, I executed the following commands: 1) Retrieving Public key of the issuer certificate Issuer public key command img I used the command x509 -in all_certs/cpo_sub_ca2_cert.pem -pubkey and copied the public key field. I then converted the Base-64 key to Hex using this tool. And then generated a sha1 hash for it.Following is the hash: 7f7d65e42a26021b69110e6a8f5d8638dfa7c565 2) Retrieving hash of Public key of the issuer certificate that would be sent by ocsp responder I used the command x509 -ocspid -in all_certs/cpo_sub_ca2_cert.pem and got the following hash: Hash generated by ocspid option Public key OCSP hash: D698940FD07B4AEB7DD08155B0C068BDB7A6A063 Why is there a mismatch between the two hashes ? I can confirm that the first hash is correct since that is exactly what i get on my client (which issued a certificate status request during TLS 1.2 handshake).Client uses WolfSSL in case you are wondering. Also this is exactly the mismatch that my client reports. Any help will be greatly appreciated. I found out the reason. This happened because OCSP responder (here openssl) produced sha1 hash on uncompressed public key while the client that had received certificates from my server was calculating hash on compressed public key. Hence the hashes were different. The fix for this issue (if it ever happens) would be to first decompress the key and then hash it, or compare hashes for both version of keys and then accept or reject an OCSP response from a given server.
common-pile/stackexchange_filtered
Will the image load for visibility value set as hidden when the page loads? I am new to javascript. I would like to know how the loading works. Suppose in my html page I have an image whose visibility is set as hidden. I have an button which on click sets the visibility property of the image to visbile using javascript. When the page is loaded will the image load or will it load when the button is clicked.Similiarly I would like to know about the display property whose value is set as none.Thanks in advance. In both scenarios the images will be loaded (regardless if you can see or not the image due to visibility or display). The difference between visibility and display is basically on the "space" the element will occupy in the page. With visibility the element will keep that space even if it is hidden. With display the element will not keep the space, other elements will be able to occupy that space. If you DON'T want the image to be loaded and you want to start loading only when the button is getting pressed then a nice trick to do that is to set the IMG src attribute to "data:" or "about:blank" and then change it on the button click. This way you will "trick" the browser and it will not load the image on page load. Hope this helps When page load, image will be loaded and will be hidden. In your button click its style property become show means visible. If you set style to display:none; it will be hidden; The better is to use the display property of the CSS to control the visibility and the space it occupies. document.getElementById( 'elemtId' ).style.display = 'none'; or use jquery to simplify the code. $("#elementId").hide(); $("#elementId").show(); or use $('#elementId').toggle(); Ref:- http://www.w3schools.com/jquery/jquery_hide_show.asp As long as the img tag is in the DOM, it will load the resource; the CSS will determine whether or not it is actually displayed. Whether or not you're using visibility: hidden; or display:none; will not affect this. The main difference is whether or not the image will occupy any space on the page; an element set to display: none; is not rendered at all, whereas an element set to visibility: hidden; will still occupy the space set by its box model. You can see this in action here: http://jsfiddle.net/d8NrK/
common-pile/stackexchange_filtered
df.fillna() throws ValueError: fill value must be in categories I have a DataFrame df without specified Dtypes, which is a conditional frequency table where the headers are organized in the following way: Data Attributes excluding X | freq_v columns for all values v of X I obtain the frequency columns by performing an outer join, which introduces NaN values into the data frame. So df.fillna(0) worked perfectly until I discretized my original Dataset using data.cut(), where data is also a DataFrame. Now I receive the ValueError. What I've tried so far: for header in list(df): if 'freq_' in header: catcol = pd.Series(df[header], dtype='category') catcol.cat.add_categories(0) catcol.fillna(0) cft[header] = catcol This is supposed to take the frequency columns out of the DataFrame, convert them to categorical Seiries's so that I am allowed to introduce the new category, and apply fillna() before I overwrite the original column with the series. However, it still throws the exact same error. How do I do this better? Sample input and output would help understanding of the problem, please provide a [mcve] Does this answer your question? Pandas fillna throws ValueError: fill value must be in categories you do add_categories that is good, but you need to reassign it, otherwise it is "lost", so do catcol = catcol.cat.add_categories(0) and same with fillna Thank you Ben! That did it. @Dave I read it before asking but I did not succeed in solving the problem regardless. As explained by Ben.T, cat.add_categories returns a new Series, so I need to change my code in the following way: for header in list(df): if 'freq_' in header: catcol = pd.Series(df[header], dtype='category') catcol = catcol.cat.add_categories(0) catcol.fillna(0) cft[header] = catcol
common-pile/stackexchange_filtered
Using custom type props in React I have a type that looks like this: type MyType = string; I then want to restrict a prop to only take MyType, not a regular string or anything else. But even when I type it like this: interface MyProps { key: MyType } the component still accepts takes a regular string as a parameter. I guess it's because MyType equals a string. <MyComponent key="regularstring" /> How do I make the component to only accept 'MyType' type of strings? Need to provide explicit string for the type. for eg type MyType = 'myType'; this will only accept the value of myType for multi values type MyType = 'myType' | 'regular'; // will support both values
common-pile/stackexchange_filtered
ImageView frame doesn't fit the real size I've created an imageView in the storyBoard and created some constraints on it. Then I use a function to add a border in that imageView: CALayer *borderLayer = [CALayer layer]; CGRect borderFrame = CGRectMake(0, 0, (imageView.frame.size.width), (imageView.frame.size.height)); //Make some changes in the border [borderLayer setFrame:borderFrame]; [imageView.layer addSublayer:borderLayer]; The thing is when I run the app the border is smaller than the image. I suppose it has to be with the scale or something but I can figure it out. Thanks for the help! Can you show the code that is making "some changes in the border"? And, image-caps of what the result looks like, and how you want the result to look? How about manipulating the image view's layer's boarder properties directly? imageView.layer.borderWidth = 7.0; Fixed the problem, I was complicating it. Thanks!
common-pile/stackexchange_filtered
Load a XML into Database using SSIS 2012 I have a XML-File which is stored on a server. It can be reached over a URL. I need to Load the XML-Data into my Database, using SSIS 2012/Visual Studio 2010. I've done this before in SSIS 2008 and it worked like a charm. Now I moved to 2012 and I am getting the following Error: "[XML-Source [46]] Error: The file "http://www.xxxx.xml" was not found. Please verify the file path and try again." Anyone knows? That URL looks bad. Do you mean a local network server like http://servername/xxxx.xml, or an internet address like http://www.somewhere.com/xxxx.xml. (You should also explain that "XML-Quelle" just means "XML-Source", for anyone who doesn't know how to read that.) The url is correct. It's not the problem Iam facing. Here is the fix for VS 2010 and VS 2012. FIX: SSIS 2012 XML Source task cannot load data from a URI http://support.microsoft.com/kb/2991526 Enjoy! :) Make sure you close the xml file before loading. you have to generate an XSD file make sure the schema defination is correct in the XSD file. Schema is correct, since it worked before. I can't close it, because it isn't stored on my pc.
common-pile/stackexchange_filtered
Hyperbolic PDEs - Proof that the restriction of a locally $H^s$ solution to a spacelike hypersurface is locally in $H^s$ I have found the following claim made very clearly at least once in the published literature (see below): Let $P$ be a linear partial differential operator defined on an open set $\Omega \subset \mathbb{R}^{n+1}$, strictly hyperbolic with respect to the level surfaces of the first coordinate, which I will denote by $t$. Let $u$ be a distribution in $H^s_\mathrm{loc}(\Omega)$ for some $s \in \mathbb{R}$, such that $Pu=0$. Then the restriction (i.e. pullback) of $u$ to each of the level sets $\Sigma_{\tau} := \Omega \cap \{ t = \tau \}$ is itself in $H^s_\mathrm{loc}(\Sigma_\tau)$. In fact, a more general statement may be found in Section 2 of: Bao, Gang; Symes, William W., A trace theorem for solutions of linear partial differential equations, Math. Methods Appl. Sci. 14, No.8, 553-562 (1991). ZBL0754.35023. There, the authors say that the statement boxed above follows from standard energy estimates, and refer to e.g. Taylor's book on pseudo-differential operators for the arguments. However, I meet the following difficulties when attempting to fill in all details: Ostensibly, the "standard energy estimates" discussed in Taylor's book (and elsewhere, e.g. in Hörmander's) pertain distributional solutions which (in the case $\Omega = \mathbb{R}^{n+1}$) are in spaces $\bigcap_{j=0}^{m-1} C^j([\tau_1,\tau_2]; H^{s-j}(\mathbb{R}^n))$, where $m$ is the order of $P$. I, on the other hand, am interested in distributions (locally) in $H^s$ in both time and space. In any case, as far as I am aware, the usual energy estimate controls the evolution in time of the sum of (appropriate) "spatial" Sobolev norms of (appropriate) $t$-derivatives of $u$ restricted to the level sets of $t$. Specifically, in the case $Pu=0$ the energy estimate says that the supremum of this quantity over a compact interval $[\tau_0,\tau_1]$ is bounded by a constant times its value at $\tau_0$. To prove that the restriction of $u$ to the $t=\tau_0$ surface is (locally) in $H^s$, presumably we would like to control the $H^s$ norm of this restriction and place an upper bound on it, but this does not seem to be the scenario in the energy inequality. By the way, I am not doubting that $u$ can be pulled back to a spacelike hypersurface, as a distribution. I know that this is the case because $WF(u)$ is disjoint from the normal bundle of the hypersurface whenever $Pu$ is smooth. Update I might have the beginning of an argument, but this leads to a further question about Bochner–Sobolev spaces whose answer seems clear in the case of positive Sobolev order $s$, but not so much otherwise. I will explain schematically and in particular assuming for simplicity and definiteness that $P$ is of second order and that $\Omega = \mathbb{R}^{n+1}$ (so that also $\Sigma_\tau \cong \mathbb{R}^n$). Namely, let $u \in H^s_\mathrm{loc}(\mathbb{R}^{n+1})$ be in the kernel of $P$, and let $\phi \in C_\mathrm{c}^\infty(\mathbb{R}^{n+1})$. Let $\psi \in C_\mathrm{c}^\infty(\mathbb{R}^{n+1})$ be such that $\psi = 1$ on a neighbourhood of $\mathrm{supp}{\phi}$. Then $P(\phi u) = [P,\phi] u = [P,\phi] (\psi u)$, and the commutator is a first-order differential operator. Hence, $\phi u$ solves the PDE with non-zero right-hand side but vanishing Cauchy data on $\Sigma_{T_0}$ for any sufficiently small $T_0$. Now, if $u$ were smooth then the standard energy estimates would say that for any $T_1 > T_0$ there exists a constant $C>0$ such that $$ (*) \quad \mathcal{E}_s(\tau; \phi u) \leq C \int_{T_0}^{T_1}\| [P,\phi] (\psi u) (t,\cdot) \|^2_{H^{s-1}(\mathbb{R}^n)} \, \mathrm{d}t $$ where the energy of order $s \in \mathbb{R}$ and at time $\tau$ is defined as $$\mathcal{E}_s(\tau; \phi u) = \| (\phi u)|_{\Sigma_\tau} \|^2_{H^s(\mathbb{R}^n)} + \| \partial_t (\phi u)|_{\Sigma_\tau} \|^2_{H^{s-1}(\mathbb{R}^n)}.$$ If we could provide a lower bound for the right-hand side of $(*)$, in terms of the norm of $\psi u$ in $H^s(\mathbb{R}^{n+1})$, then presumably we would be close to being done (by a suitable density argument from $C^\infty$). Now I would like to say something along these lines: $$ (**) \quad \int_{T_0}^{T_1}\| [P,\phi] (\psi u) (t,\cdot) \|^2_{H^{s-1}(\mathbb{R}^n)} \, \mathrm{d}t \leq C_1 \| [P,\phi] (\psi u) \|^2_{H^{s-1}(\mathbb{R}^{n+1})} \leq C_2 \| \psi u \|^2_{H^{s}(\mathbb{R}^{n+1})}$$ where the second inequality would be due to $[P,\phi]$ being differential of order $1$. But how can I justify the first inequality? It seems almost obvious in the case of integer $s \geq 1$ – we are simply ignoring those multi-indices with a non-zero entry corresponding to $t$, which would otherwise contribute to the $H^{s-1}(\mathbb{R}^{n+1})$ norm. For general $s \in \mathbb{R}$, I'm not sure. Notice that the left-hand side of $(**)$ is the square of the norm in the Bochner–Sobolev space $L^2([T_0,T_1]; H^{s-1}(\mathbb{R}^{n}))$. Update 2 Perhaps proving the first inequality in $(**)$ is not so difficult when the Sobolev order $s$ is real and $s \geq 1$. For then it seems we can use the Fourier transform, as follows. Set $\ell := s-1$ and $g := [P,\phi](\psi u) \in C^\infty_\mathrm{c}(\mathbb{R}^{n+1})$, and denote partial Fourier transforms with respect to $t$ and the $x$-variables in $\mathbb{R}^n$ by $\mathcal{F}_t$ and $\mathcal{F}_x$ respectively, while the full Fourier transform of $g$ will be $\hat{g}$. Then, using that $\mathcal{F}_t \mathcal{F}_x g = \hat{g}$, and the Plancherel theorem: \begin{align*} \int_{T_0}^{T_1} \| g(t,\cdot) \|^2_{H^{\ell}(\mathbb{R}^n)} \, \mathrm{d}t &\leq \int_{\mathbb{R}} \| g(t,\cdot) \|^2_{H^{\ell}(\mathbb{R}^n)} \, \mathrm{d}t \\ &= \int_{\mathbb{R}} \left( \int_{\mathbb{R}^n} (1 + |k|^2)^\ell |[\mathcal{F}_x g](t,k)|^2 \, \mathrm{d}^n k\right) \mathrm{d}t \\ &= \int_{\mathbb{R}} \left( \int_{\mathbb{R}^n} (1 + |k|^2)^\ell |[\mathcal{F}_t^{-1} \hat{g}](t,k)|^2 \, \mathrm{d}^n k\right) \mathrm{d}t \\ &= \int_{\mathbb{R}^n} (1 + |k|^2)^\ell \left( \int_{\mathbb{R}} |[\mathcal{F}_t^{-1} \hat{g}](t,k)|^2 \, \mathrm{d}t \right) \mathrm{d}^n k \\ &= \int_{\mathbb{R}^n} (1 + |k|^2)^\ell \left( \int_{\mathbb{R}} |\hat{g}(\tau,k)|^2 \, \mathrm{d}\tau \right) \mathrm{d}^n k \\ &\leq \int_{\mathbb{R}^{n+1}} (1 + |\tau|^2 + |k|^2)^\ell|\hat{g}(\tau,k)|^2 \, \mathrm{d}\tau \, \mathrm{d}^n k \\ &= \| g \|^2_{H^{\ell}(\mathbb{R}^{n+1})}. \end{align*} Of course, I used the fact that $\ell \geq 0$ (i.e. $s \geq 1$) in the final inequality above. Old, mildly related question: https://math.stackexchange.com/questions/1904939/bochner-sobolev-space-vs-sobolev-space-on-product-via-fubini-tonelli
common-pile/stackexchange_filtered
Magento: I need Discount Coupon Code Field on Product Detail Page I have seen examples and workaround here and there but they doesn't seems to be working in my case. I was thinking if there is any extension or chunk of code that might make it work. I need discount coupon field to apply discount on any particular product. I'm voting to close this question as Stack Overflow is a programming-related Q&A site. Asking for an extension or code is off-topic. Perhaps you should post it on http://magento.stackexchange.com instead? If I understand the problem you are having correctly, you are wanting to apply a shopping cart price rule on the product detail page. If that's the case, there are several factors that come into play. The easiest answer to this is, they have to be applied in the shopping cart. Customer group, region, product type, quantity can all have an effect on if the rule is allowed or not. I do not know of any extensions that allow what you want to do, it could be done with custom development. One way might be using the URL to contain the coupon code, displaying the product with the coupon code affecting the product and then forcing the customer to login when adding to cart and then applying the code. It would be a significant chunk of work to implement though. I hope this helps
common-pile/stackexchange_filtered
Django: Limit user's session by time I'm working on the app where I need to limit the ability to log in and be authenticated for a specified time of the day. Let's say from 8am to 5pm. To limit the ability to log in I created a custom auth backend where authenticate() method returns user object only if current time is within allowed period of time. Now I want to terminate user's auth session after specified time. Setting session expiry_date date and cookie's Expiry seems to be the best way to achieve this, but after reading Django docs and digging in the source code for some time I did not found a good solution to it. How do I do this? Any help is appreciated. Changing the auth backend is probably not the solution you are looking for (at least I wouldn't recommend it), since you are changing security-critical parts of your application. I would suggest a custom middleware: If registered users trying to access your site between 8am and 5pm, they'll see a warning that this site cannot be used. from django.utils import timezone from django.core.exceptions import PermissionDenied class AccessRestrictionMiddleware: def process_request(self, request): current_hour = timezone.now().hour is_time_restricted = current_hour >= 8 and current_hour < 17 if request.user.is_authenticated() and is_time_restricted: raise PermissionDenied I'm not changing it completely, I just extend the default backend, and in the authenticate() method I call super() first and then do my job with the authenticated user (if super returns a user, means authenticated successfully). Default backend is 100% in action. You still need to logout / show the warning if a logged in user using the website outside of the specified time. The AuthBackend however is not used if your user is requesting with a valid session, and you still need to check with a function decorator or middleware.
common-pile/stackexchange_filtered
Is it possible to return more than one value from a method in Java? I am using a simulator to play craps and I am trying to return two values from the same method (or rather I would like to). When I wrote my return statement I simply tried putting "&" which compiled and runs properly; but I have no way of accessing the second returned value. public static int crapsGame(){ int myPoint; int gameStatus = rollagain; int d1,d2; int rolls=1; d1 = rollDice(); d2 = rollDice(); switch ( d1+d2 ) { case 7: case 11: gameStatus = win; break; case 2: case 3: case 12: gameStatus = loss; break; default: myPoint = d1+d2; do { d1=rollDice(); d2=rollDice(); rolls++; if ( d1+d2 == myPoint ) gameStatus = win; else if ( d1+d2 == 7 ) gameStatus = loss; } while (gameStatus == rollagain); } // end of switch return gameStatus & rolls; } When I return the value as: gameStatus=crapsGame(); It appropriately sets the varaible to win or lose but if I try something as simple as following that statement with: rolls=crapsGame(); It is assigned the same value as gamestatus...a 0 or a 1 (win or lose). Any way that I can access the second returned value? Or is there a completely different way to go about it? use array of object or hashmap or model class No it is not. You can return an object though and that object can contain multiple properties You should return an int[]. Checkout http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html @sissonb So I would return an array and assign index 1 as the gameStatus and the second index as number of rolls? And then return it to an existing array? where I could then access it? @OscarWilde yep, but remember index's of arrays start at 0. Also your method will need to change to public static int[] crapsGame. This is a more of a quick and dirty method to return the values. If this is going to turn into a large project then returning an object like @rgettman said would be best, but requires the overhead of creating classes and uses more memory. you are using bitwise AND (&). while returning. See Operators in Java It has different meaning. You can declare rolls as an instance variable instead of local variable which will solve your problem where you need not to return two value. Create your own value holder object to hold both values, then return it. return new ValueHolder(gameStatus, rolls); It's possible to return an array with multiple values, but that's cryptic and it does nothing for readability. It's much easier to understand what this means... valueHolder.getGameStatus() than what this means. intArray[0] What would I return a valueholder too? As in the statement: gameStatus=crapsGame(); what would hold the value of a value holder; if that makes any sense? Sorry if this sounds ridiculously idiotic... I'm completely unfamiliar with ValueHolder ValueHolder is a class that you will make -- a custom object. Then you'll write something like ValueHolder valueHolder = crapsGame(); thank you! I went with the array method because it was slightly simpler (seeing as I only need two values) but i appreciate the reply and the merit of this method! Plus, I learned about something extra which is always nice; because I'd never heard of "ValueHolder"! returning gameStatus & rolls means "return the bitwise and of gameStatus and rolls" which probably is not what you want you have some options here: return an array create a class that represents the response with a property for each value and return an instance use one of the many java collections to return the values (probably lists or maps) I did end up going with the array method but I was wondering if you could expand a bit on the "return the bitwise and of gameStatus and rolls" What was I actually returning when I had it entered like that? @OscarWilde sure: the bitwise and operator & will apply a logic AND one bit at a time on its two operands (check this out: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html) Is it possible to return more than one value from a method in Java? No it is not. Java allows only one value to be returned. This restriction is hard-wired into the language. However, there are a few approaches to deal with this restriction: Write a light-weight "holder" class with fields for the multiple values you want to return, and create and return an instance of that class. Return a Map containing the values. The problem with this (and the next) approach is that you are straying into an area that requires runtime type checking ... and that can lead to fragility. Return an array containing the values. The array has to have a base type that will accommodate the types of all of the values. If this is a method on an object, then add some fields on the same object and methods that allow the caller to pick up "auxiliary results" from the last call. (For example, the JDBC ResultSet class does this to allow a client to determine if the value just retrieved was a NULL.) The problem is that this makes the class non-reentrant at the instance level. (You could even return extra results in statics, but it is a really bad idea. It makes the class non-reentrant across all instances, not to mention all of the other badnesses associated with misused statics.) Of these, the first option is the cleanest. If you are worried about the overhead of creating holder instances, etc, you could consider reusing the instances; e.g. have the caller pass an existing "holder" to the called method into which the results should be placed. You can return an array of values or a Collection of values. The best practice for an OOP approach is to return an Object. An object that contains all the values you want. Example: class Main { public static void main(String[] args) { MyResponse response = requestResponse(); System.out.println( response.toString() ); } private static MyResponse requestResponse() { return new MyResponse( "this is first arg", "this is second arg" ); } } class MyResponse { private String x, y; public MyResponse( String x, String y ) { this.x = x; this.y = y; } @Override public String toString() { return "x: " + x + "\t y: " + y; } } If you want an even more scalable approach then you have to use JSON responses. (let me know if you want an example with JSON too) This question is from 3 years ago... why did I suddenly get two new answers tonight? Just displayed to "newest" section man. Don't know. You can following ways to do this: Use a Container class, for example public class GameStatusAndRolls { String gameStatus; String rolls; ... // constructor and getter/setter } public static GameStatusAndRolls crapsGame(String gameStatus, String rolls) { return new GameStatusAndRolls(gameStatus, rolls); } public static void main(String[] args) { ... GameStatusAndRolls gameStatusAndRolls = crapsGame(gameStatus, rolls); gameStatusAndRolls.getGameStatus(); Use List or an array, for example public static List<Integer> crapsGame(String gameStatus, String rolls) { return Arrays.asList(gameStatus, rolls); } private static final int GAME_STATUS = 0; private static final int ROOLS = 0; public static void main(String[] args) { ... List<Integer> list = crapsGame(gameStatus, rolls); ... list.get(0)...list.get(GAME_STATUS); ... list.get(1)...list.get(ROOLS); or public static String[] crapsGame(String gameStatus, String rolls) { return new String[] {gameStatus, rolls}; } private static final int GAME_STATUS = 0; private static final int ROOLS = 0; public static void main(String[] args) { ... String[] array = crapsGame(gameStatus, rolls); ... array[0]...array[GAME_STATUS]; ... array[1]...array[ROOLS]; Use Map, for example public static Map<String, String> crapsGame(String gameStatus, String rolls) { Map<String, String> result = new HashMap<>(2); result.put("gameStatus", gameStatus); result.put("rolls", rolls); return result; } public static void main(String[] args) { ... Map map = crapsGame(gameStatus, rolls); ... map.get("gameStatus")...map.get("rolls");
common-pile/stackexchange_filtered
Flutter - ListView.Builder() horizontal + reverse pull to refresh does not work class MyWidget extends StatefulWidget { const MyWidget({Key? key}) : super(key: key); @override State<MyWidget> createState() => _MyWidgetState(); } class _MyWidgetState extends State<MyWidget> { List<String> cities = ['New York', 'Paris', 'Tokyo', 'London']; Future<void> _refresh() async { // your refresh logic here await Future.delayed(const Duration(seconds: 2)); setState(() {}); print('huh??'); } @override Widget build(BuildContext context) { return Container( height: 400, child: RefreshIndicator( onRefresh: _refresh, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: cities.length, itemBuilder: (BuildContext context, int index) { return Padding( padding: const EdgeInsets.all(8.0), child: Container( width: 100, height: 100, color: Colors.blue, child: Center( child: Text(cities[index]), ), ), ); }, ), ), ); } } I have this widget. I am trying to execute _refresh() function when I pull the side on the right. However, it does not work and I dunno what I have to add to make it work now. I also tried to pull the left side but does not work as well. have you try this? https://stackoverflow.com/q/67262806/12838877 Here in this post's comment. It is said that Refersh Indicator doesn't work on Horizontal Scrolling. and another comment shows the workaround to tackle this. I made it easier for you: import 'package:flutter/material.dart'; class MyPage extends StatefulWidget { const MyPage ({Key? key}) : super(key: key); @override State<MyPage > createState() => _MyPage State(); } class _MyPageState extends State<MyPage> { late ScrollController _controller; List<String> cities = ['New York', 'Paris', 'Tokyo', 'London']; Future<void> _refresh() async { // your refresh logic here await Future.delayed(const Duration(seconds: 2)); setState(() {}); print('huh??'); _controller.animateTo( _controller.position.minScrollExtent, curve: Curves.easeOut, duration: const Duration(milliseconds: 500), ); } _scrollListener() { //for right end if (_controller.offset >= _controller.position.maxScrollExtent && !_controller.position.outOfRange) { _refresh(); } //for left start if (_controller.offset <= _controller.position.minScrollExtent && !_controller.position.outOfRange) { _refresh(); } } @override void initState() { _controller = ScrollController(); _controller.addListener(_scrollListener); super.initState(); } @override void dispose() { super.dispose(); _controller.removeListener(_scrollListener); _controller.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: SizedBox( height: 200, child: ListView.builder( controller: _controller, scrollDirection: Axis.horizontal, itemCount: cities.length, itemBuilder: (BuildContext context, int index) { return Padding( padding: const EdgeInsets.all(8.0), child: Container( width: 200, height: 100, color: Colors.blue, child: Center( child: Text(cities[index]), ), ), ); }, ), ), ); } } This works good. However, how can I give a pull effect? Like RefreshIndicator? This refreshes when i just scroll to the end. I want it to run the function when user pull the widget to certain distance. actually, I got it! I can play around with controller offset value! Hey! sorry to bother ya but I want to scroll all the away to the starting position after _refresh() has been called. so I added _controller.animateTo( _controller.position.minScrollExtent, duration: Duration(seconds: 2), curve: Curves.fastOutSlowIn, ); after _refresh(); but I get '_positions.isNotEmpty': ScrollController not attached to any scroll views.. What can I do in this case?
common-pile/stackexchange_filtered
JAGS: posterior predictive distribution I am fitting a simple linear regression model with R & JAGS: model { for (i in 1:length(ri)){ ri[i] ~ dnorm(mu[i],tau) mu[i] <- alpha + b.vr*vr[i] + b.ir*ir[i] } #posterior predictive distribution for (j in 1:length(pvr)){ pmu[j] <- alpha + b.vr*pvr[j] + b.ir*pir[j] pri[j] ~ dnorm(pmu[j],tau) } #priors for regression alpha ~ dnorm(0,0.01) b.vr ~ dunif(-10,0) b.ir ~ dunif(0,10) #prior for precision tau ~ dgamma(0.001,0.001) sigma <- 1/sqrt(tau) } I am trying to calculate the posterior predictive distribution with new data (pvr and pir in the model). But somehow the reported results (pri) do not make sense (the means of pri are smaller than expected). Could someone explain me, is something wrong with the model specification? could you at a minimum provide the input data that you are using? disclaimer I still don't fully understand your model; but without at least a reproducible example, this is the best I can offer. It is not clear exactly what you are doing here. For example, how are pvr and pir calculated? Would it make sense to calculate them inside the same model? Answer I am assuming that your data includes observations for mu[] but not pmu[] and you want to estimate pmu[j] given j values of pvr and pir. Append the pir and pvr to the ir and vr columns, get rid of the second for loop, and then consider the values of mu[] estimated using pir and pvr to be the posterior predictive estimates of mu. Then replace the two for loops with this: for (i in 1:length(ri)+length(pri)){ ri[i] ~ dnorm(mu[i],tau) mu[i] <- alpha + b.vr*vr[i] + b.ir*ir[i] } I have done something similar, but without predicted regressors, similar to the example given by Gelman et al in 'Bayesian Data Analysis' (pp 598-599 starting under posterior predictive simulations). @David pvr and pri are user supplied data: they are the predicted regressors... @teucer are they predicted from user-supplied values of ir and vr? if so, how? and if so, why not calculate pri and pvr yourself inside the JAGS model? @teucer, this is a shot in the dark since I still don't understand your model, and this might be the same as what you already have, but would it make sense to append the pir and pvr to the ir and vr columns, get rid of the second for loop, and then consider the values of mu[] estimated using pir and pvr to be the posterior predictive estimates of mu? @David I want to have some credible interval for the predictions (pri), this is why having mu is not enough. If I append pvr and pir I would get alpha, b.vr and b.ir for the whole ri, right? Or can I have ri with missing values e.g. (1,2,3,NA,NA) and append the regressors? @teucer yes, you can have ri with missing values; this is a neat feature of bugs that simplifies calculation of a predictive interval. @David could please edit your answer accordingly so that I can accept?As I said earlier having only the mean is not enough for my purposes, I would like to have the other statistics... @teucer I have updated my answer, I will be interested to know if it works. @David Thx! Actually the both approaches work as outlined in link (page 39, second paragraph). Your solution is obviously more eficient...
common-pile/stackexchange_filtered
Can a Scala object reference itself in its constructor? I want to construct an object, but in the process I want to pass itself in as one of the parameters during construction. object TradeTable extends AbstractTable ( join = ReportForeignKey.addJoinTo(TradeTable).withAlias(TradeTableJoin.Parent) ) I get an error super constructor cannot be passed a self reference unless parameter is declared by-name I tried using this but that doesn't work either. I think I can convert this to a class and it works then but I only need a single instance of this ever. @senia you are referencing the object in the body, not the constructor of the class being extended. what about doing that after defining the object? Like object TradeTable extends AbstractTable; ReportForeignKey.addJoinTo(TradeTable).withAlias(TradeTableJoin.Parent) I'm a beginner on scala so if this doesn't make sense it's normal :p Just tried this Scala 2.10.3 and it seems to work fine. @RobN would you mind answering the question then?
common-pile/stackexchange_filtered
Information regarding using Core Service to create Components in SDL Web 8 Recently I'm trying to use the Core Service in SDL Web 8 to create Components from XML files. I found that the information on the SDL Documentation Center is not enough for me, and information from browser is a little messy. Could anyone share some links from basic concepts to deep implementation? Any share would be appreciated. Thanks. :) If you search this site for "core service create component", you get more than 100 resuls and some of those are pretty much to what you are looking for. I'm seeing a complete code example of constructing a Component from XML in Trying to create a Component with the Core Service: Data at the root level is invalid, which translates into something like: using (var client = new CoreServiceClient(endPoint)) { var componentData = (ComponentData)client.GetDefaultData(ItemType.Component, folderUri, new ReadOptions()); componentData.Title = "Your Title"; componentData.Schema = new LinkToSchemaData { IdRef = schemaUri } componentData.Content = serializableXmlDocument; client.Create(componentData, new ReadOptions()); } If you look through the documentation you also see a few examples regarding creating items, and specifically dealing with Components and fields. All in all, I think all the information you are looking for is right there for you. If you encounter a specific issue with stringing all this example code together, that is something you could create a new question on. I wrote a program some time ago that imports RSS feed articles into components, you can see the code here. Most of the CoreService logic is in ContentItem.cs and in the main Program.cs. It may be a bit more complex than what you need to get started , but I always see this as a good example of mapping content to a proper class structure, and then using class inheritance/OO logic to deal with the CRUD operations via CoreService. You may also want to look at the Core Service Recipies section of the Tridion Cookbook: https://github.com/TridionPractice/tridion-practice/wiki/CookbookDocumentation#core-service-recipies Although it doesn't have a specific example for creating a Component, it does introduce some Core Service concepts nicely, using examples such as Creating a new Publication and Changing the content and metadata of existing Components. To create/migrate Tridion item using XmL is good option but its tricky when you have component link and media links etc. Define your Schema with simple fields to test. Title Description Create a class in C# like following. public class Book { [XmlElement(ElementName = "Title")] public string Title { get; set; } [XmlElement(ElementName = "Description")] public string Synopsis{ get; set; } } Fill this component with your required data and serialize it to disk as XML file. Similarly you can Create XML for metadata of you component. Importing XML (Code similar to @bart's) var componentData = (ComponentData)tridionClient.CoreServiceClient.GetDefaultData(ItemType.Component, folderId, readOptions); componentData.Title = componentDetails.Title; var schemaId = tridionClient.CoreServiceClient.Read(componentDetails.SchemaWebDavUrl, readOptions).Id; componentData.Schema.IdRef = schemaId; var schemaFields = tridionClient.CoreServiceClient.ReadSchemaFields(schemaId, true, readOptions); componentData.Content = UpdateNamespace(componentDetails.ComponentData, schemaFields.NamespaceUri).OuterXml; ; // this is custom method which add required namespace in the XML. assuming you are generating XML from another source and this namespace is missing if (componentDetails.MetaData != null) { componentData.Metadata = UpdateNamespace(componentDetails.MetaData, schemaFields.NamespaceUri).OuterXml); } tridionClient.CoreServiceClient.Create(componentData, readOptions); for any component link. you have to first create linked component and cache its tcm-id and put that tcm-in the parent component. this is very interesting part. Don't forget to put check of component/folder already exists Category keywords are just set of repeating nodes.
common-pile/stackexchange_filtered
I need to create a few customer specific products in woocommerce which should only be shown to specific users I am developing a ecommerce store using WordPress and WooCommerce. I have a products. I will only allow a specific customer to purchase the product. So I would like to only show this product if the specific customer is logged in. Thanks This is useful to restrict user, // Woocommerce - Redirect unauthorised users from accessing a specified product category when clicked or visited via direct url function woocommerce_hide_non_registered() { if( ( is_product_category('specials') ) && ! ( current_user_can( 'customer' ) || current_user_can( 'administrator' ) ) ) { wp_redirect( site_url( '/' ) ); exit(); } } add_action( 'template_redirect','woocommerce_hide_non_registered' ); // End - Woocommerce - redirect unauthorised users from accessing a specified product category // Woocommerce - Removes category link from woocommerce product category widgets so they are not seen add_filter( 'get_terms', 'get_subcategory_terms', 10, 3 ); function get_subcategory_terms( $terms, $taxonomies, $args ) { $new_terms = array(); // if a product category and on the shop page if ( in_array( 'product_cat', $taxonomies ) && ! ( current_user_can( 'customer' ) || current_user_can( 'administrator' ) ) && is_shop() ) { foreach ( $terms as $key => $term ) { if ( ! in_array( $term->slug, array( 'specials' ) ) ) { $new_terms[] = $term; } } $terms = $new_terms; } return $terms; } // End - Woocommerce - Removes category link from woocommerce product category widgets so they are not seen // Woocommerce - Remove products from being displayed that belong to a category user is not authorised to visit. Products seem to still be accessible via direct url unfortunately. add_action( 'pre_get_posts', 'custom_pre_get_posts' ); function custom_pre_get_posts( $q ) { if ( ! $q->is_main_query() ) return; if ( ! $q->is_post_type_archive() ) return; if ( ! ( current_user_can( 'customer' ) || current_user_can( 'administrator' ) ) && is_shop() ) { $q->set( 'tax_query', array(array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => array( 'specials'), // Don't display products in the private-clients category on the shop page 'operator' => 'NOT IN' ))); } remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' ); } // End - Woocommerce - Remove products from being displayed that belong to a category user is not authorised to visit. Products seem to still be accessible via direct url unfortunately. Thanks for your response. Your answer is good but not to my question. I want it for products not categories. Actually what is your question? you need to create category for that specific customer and then you can restrict that newly created category. This will do the trick for you. add_action( 'pre_get_posts', 'dm_restrict_user_to_show_own_posts_only' ); function dm_restrict_user_to_show_own_posts_only( $dm_wp_query_obj ) { // Front end, do nothing if( !is_admin() ) return; global $current_user, $pagenow; wp_get_current_user(); // http://php.net/manual/en/function.is-a.php if( !is_a( $current_user, 'WP_User') ) return; // Not the correct screen, bail out if( 'edit.php' != $pagenow ) return; // Not the correct post type, bail out if( 'product' != $dm_wp_query_obj->query['post_type'] ) return; // If the user is not administrator, filter the post listing if( !current_user_can( 'delete_plugins' ) ) $dm_wp_query_obj->set('author', $current_user->ID ); }
common-pile/stackexchange_filtered
Test reporting tools I am creating a set of test cases and I am looking for a better solution for what I am doing. I am currently using Microsoft excel to create a spreadsheet for all my tests and reporting. I am looking for an open source test management tool that I can create tests for products and have it generate reports. You may also look into commercial tools which offer free experience for limited number of team members. I believe http://www.kualitee.com/ is a good choice as it offers free access to all features for 20 members team. Isn't that a candidate for community-wiki? There isn't one best answer. If you are doing Automated testing I would suggest TestNG as mentioned previously along with ExtentReport ExtentReport is used to create a report based on the results from your TestNG tests. Example - http://relevantcodes.com/Tools/ExtentReports2/ExtentJava.html You can use it as either a Logger or Listener Logger The logger function is where you add a log to your test step and this will then be logged in the report along with the status of the test eg. Pass/Fail/Skip. Example - http://www.ontestautomation.com/creating-html-reports-for-your-selenium-tests-using-extentreports/ Listener You can also use ExtentReport as a listener. This is where ExtentReport will listen in on the tests being run and then generate a report based on your results. This is useful if you don't want to add in extra code to your test classes. You then specify the listener in your TestNG test XML file. Example - http://www.ontestautomation.com/using-the-extentreports-testng-listener-in-selenium-page-object-tests/ You can also specify the dependency if you are using a Maven style project. Here - http://mvnrepository.com/artifact/com.relevantcodes/extentreports/2.40.2 This is for version 2.40.2. They now have however version 2.41.0 released. Hi Colin, what is ExtentReport and how does using it make it substantially different from TestNG? Thanks! Its just a JAR file that can be used as an add-on to test NG. You can use it as a Logger or a Listener. In terms of the Logger you can use it to log each of your test steps. With a Listener you can just create a Listener class that will listen in on your tests and generate a report based on the results. You just need to specify the Listener class in your TestNG Testing XML. I will update my questions and put in some useful links for you. @corsiKa Thank you. Hopefully it helps somebit, do not hesitate to contact me further about it I'll be more than happy to help. @corsiKa I updated my question with more links as my reputation is now higher. TestLink is one of the major open source test management tools. (I have some experience using it). You should also take a look at the answer to this question, which include links to some detailed lists of testing tools. fitnesse is one option http://fitnesse.org/ From the site: FitNesse is a tool for specifying and verifying application acceptance criteria (requirements). It acts as a bridge between the different stakeholders (disciplines) in a software delivery process. It's wiki server makes it easy to document the software.It's testexecution capabilities allow you to verify the documentation against the software, ensuring the documentation remains up to date and the software is not facing regression. For this to work, the tests should be defined on a business level, in conjunction with business representatives. They are basically business requirements, laid out in a way easy to understand by all stakeholders. When your requirements are unambiguous, they can be automatically verified with your application. testng is another option http://testng.org/doc/documentation-main.html TestNG is a testing framework designed to simplify a broad range of testing needs, from unit testing (testing a class in isolation of the others) to integration testing (testing entire systems made of several classes, several packages and even several external frameworks, such as application servers). Writing a test is typically a three-step process: Write the business logic of your test and insert TestNG annotations in your code. Add the information about your test (e.g. the class name, the groups you wish to run, etc...) in a testng.xml file or in build.xml. Run TestNG. TestLink is the open source test management tool, with good reporting tools. Following is the screenshot of report from TestLink: If wish to try it before you start using it, following is the demo link for TestLink Demo Link for TestLink
common-pile/stackexchange_filtered
How to install .ipa programmatically How do I install an .ipa file programmatically on iOS? is there some framework for that? I'm not jailbreaker, just coding some app for client, and that's what he wants. As far as I know, the only way to install apps on the iPhone is to download them through Appstore. The .ipa files you find on the net are usually cracked apps, and obviously Apple don't want you to install those... yes i know, but he wants it to be on some cydia repo or so, so probably it's gona be designes for jailbroken phones ... so it doesn't matter. Create enterprise ipa and host it in your site and use itms-services to install.
common-pile/stackexchange_filtered
AJAX / PHP form submit issue I trying to upgrade a website to make it easily replicable and more database driven. My forms use PHP / AJAX to submit to response.php within the same directory. E.G domain.com/client1/login.php this would use JS in /js/common.js common.js will take the variables from the form name and use domain.com/client1/response.php?action=login The issue I am having is that despite login.php and response.php both being in client1/, the JS is trying to locate response.php at domain.com/response.php Is there a way of forcing the JS to use the local directory or taking my php url: '$isteURL/response.php', Any help would be gratefully appreciate, racking my head here. $siteURL is defined in the header.php above the JS file function submitForm3() { var data = $("#reset-form").serialize(); $.ajax({ type : 'POST', url : '<?php echo $siteURL; ?>/response.php?action=reset', data : data, beforeSend: function(){ $("#error").fadeOut(); $("#reset_button").html('<span class="glyphicon glyphicon-transfer"></span> &nbsp; sending ...'); }, success : function(response){ if($.trim(response) === "1"){ console.log('dddd'); $("#reset-submit").html('Email sent ...'); setTimeout(' window.location.href = "index.php?resetStatus=1"; ',2000); } else { $("#error").fadeIn(1000, function(){ $("#error").html(response).show(); }); } } }); return false; } "$siteURL is defined in the header.php above the JS file" ... therefore you need to copy/paste header.php in your question as well. Did you check your common.js source? PHP usually isn't being parsed in .js files, unless you tell your webserver to do so common.js source is above. I can post the full page but this is the relevant bit. When I change remove the echo and just place in client1/response... works fine. When I just leave response.php and check the consol it has a 404 error on response .php. in relation to header I can do but. $siteURL works fine on the rest of the site, I just can't bring it into the JS. I would rather no be passing php variables in the JS, my preference is for it to use the documents in the directory it is in "common.js source is above" I meant did you view the file on your server, from the source of the page, like http://localhost/js/common.js? Did <?php echo $siteURL; ?> actually run and place your siteURL in common.js? Or is <?php echo $siteURL; ?> still there? As said, PHP is usually only parsed/run in .php files, not .js NO it doesn't link to file is https://volunteershub.co.uk/vmsmain/js/common.js - the idea being that vmsmain will be replicated to several different sites so I want it be able to $siteURL to make the site easier to set up Php code is only executed in .php files Why don't you use a JavaScript variable for this then? Add <script>const baseURL = '...';</script> before any of the other scripts - and output the value via PHP, dynamically. Then all your other scripts can use that variable, to build the full URL for the specific request.
common-pile/stackexchange_filtered
JSON.Net serializer ignoring JsonProperty? I have the following entity class: public class FacebookComment : BaseEntity { [BsonId(IdGenerator = typeof(ObjectIdGenerator))] [BsonRepresentation(MongoDB.Bson.BsonType.ObjectId)] [JsonProperty("_id")] public ObjectId Id { get; set; } public int? OriginalId { get; set; } public DateTime Date { get; set; } public string Message { get; set; } public string Sentiment { get; set; } public string Author { get; set; } } When this object is serialized to JSON, I want the Id field to be written as "_id":{...}. AFAIK, I should just have to pass the desired propertyname to the JsonProperty attribute; and I should be good to go. However, when I call JsonConvert.SerializeObject; it seems to ignore my attribute and renders this instead: { Author: "Author name", Date: "/Date(1321419600000-0500)/", DateCreated: "/Date(1323294923176-0500)/", Id: { CreationTime: "/Date(0)/", Increment: 0, Machine: 0, Pid: 0, Timestamp: 0 }, Message: "i like stuff", OriginalId: null, Sentiment: "Positive" } As you can see, the Id field is being rendered with the wrong field name. Any ideas? Been working on this issue for an hour; can't figure out why the serializer is seemingly ignoring my JsonProperty. Any constructive input is greatly appreciated. So BaseEntity has and Id property also? No, BaseEntity only has a DateCreated field did u ever figure this out? I'm pretty sure my answer (which took me two hours!) is probably what happened I fixed this issue by marking my Id property with [System.Runtime.Serialization.DataMember(Name="_id")] instead of JsonProperty. Still not entirely clear as to why it didn't work originally though... Short Answer: Make sure all your assemblies are referencing the SAME EXACT JSON.NET DLL. What's probably happening is you are applying [JsonProperty] from one DLL in one assembly, and serializing the object from a different assembly which is looking for a different [JsonProperty] and because the CLR object types are different it is effectively being ignored. Longer Answer: I just had this problem but fortunately because I had one class that was working with JsonProperty and one that wasn't I was able to do some detective work. I stripped the non-working class down to the bare minimum and compared it to the working class and couldn't see ANY differences - except for the fact that the non-working class was in a different assembly. When I moved the class to the other assembly it worked perfectly as it should. I poked around for a bit trying to look into JSON serialization of namespaces, but that didn't seem to apply so I looked at the references and sure enough I was referencing an old JSONNET3.5 DLL in my entities DLL and the NUGET 4.5 version in my main project file. This gives me two instances of [JsonProperty] attribute (which is just a regular class) and just because they're named the same doesn't mean the serializer is going to even recognise the attribute. I'm only using 1 assembly referencing Newtonsoft.Json and I'm still getting this problem, not even the DataMember attribute works for me. Very strange stuff. are you sure you did a clean build and there is no extra dll in your bin? if you have multiple projects do you have the same JSON.NET DLL defined for each? try evaluating typeof(JsonProperty).Assembly.CodeBase at runtime to ensure DLL is loaded and not coming from somewhere unexpected I stripped it down to just 1 project and did the clean just to be sure and the same unfortunately. Maybe it's a bug with this version? Does the expression in my last comment compile ok and run? What project type is this? Website/mvc? it runs fine and it is pointing to my bin where it was copied to by VS. This project is a console app. Perhaps this is the culprit? I'm calling a rest api and then processing the data Console should be fine. But let's go back to when you said 'it doesn't work'. What exactly do you mean? are you serializable or deserializing Yes sorry deserialization, but of course only with the JsonProperty, every other property works. I tried Required= Required.Default and also Required.Always and those don't seem to work either. I'm not sure what you mean 'every other property works'. Shouldn't they all have JsonProperty? Also I always like to put [JsonObject(Mode=MemberSerialization.OptIn)] on my object. Anyway I just remembered once I had a cut and paste error with TWO properties with [JsonProperty(Name="foo")] and that caused this issue I'm only using it on those that I need a different name than that actual property. Example: [JsonProperty("3h")]public string myProperty{get; set;} The other properties deserialize correctly without the JsonProperty attribute. Ok yes this sounds very similar to when I had duplicates. it didn't know what to do. You're SURE you don't have two "3h" defined? in a base class perhaps? If you add a fake property [JsonProperty("testProperty")] does that work ok? or ANY JsonProperty causes it to break? and you're sure you're using JSON.NET to do the deserialization? did you try JsonConvert.DeserializeObject<MyObject>(jsonString) You sir are the man. I was using new JavaScriptSerializer().Deserialize(jsonResponse). I thought that was Json.NET. My mistake. It works perfect now using your change. Thanks so much for taking the time to help me find the problem. Great :) I think everyone makes that mistake sometime :) not a working solution, my property is "$type" and it can no be Deserialize @Mahdi it sounds like your issue has nothing to do with this which is not intended to be an answer to every possible Json.NET issue. With that said does it only fail for properties with a $? You should ask a new question with specifics. This resolved it for me. I had two different 'usings' Thanks for posting!!! I had the same problem (.Net Core 3.1) and the reason was that I was using JsonPropertyName annotation, which is in System.Text.Json.dll but using JsonConvert.Serialize(string), which is obviously in Newtonsoft.Json.dll. It seems the serialization functions only respect their own library annotations. Changing JsonPropertyName annoation to JsonProperty fixed it, as the latter is in Newtonsoft.Json.dll Using JsonPropertyName was the issue. Thanks! In my case I was applying the JsonProperty atrtibute on properties alright, but since I was using asp.net core 3.1, types from System.Text.Json were used, not types from JSON.Net. So if you start using asp.core 3.1, you should make a decision as to which library you would like to use for json. HTH. To expand on this: .NET Core 3.1 uses the "JsonPropertyName" attribute from System.Text.Json.Serialization. If you're just passing in a string, you can switch from [JsonProperty("name")] to [JsonPropertyName("name")], switch out your Newtonsoft import, and you'll be all set. This post helped me. I used serialiser: new JavaScriptSerializer().Serialize(message) But rigtly use this: JsonConvert.SerializeObject(message); In my case, I was using record types, which means you have to use a property: prefix for the fields as mentioned in this question: public record Person ( [property:JsonPropertyName("name")] string Name, ); I also found that my JsonProperty tags were being ignored. I ultimately found that a silent failure loading Newtonsoft Json was to blame. Nancy.Serialization.JsonNet tries to load Newtonsoft Json <IP_ADDRESS> which was an earlier version than I had installed. No error is surfaced and the serializer provided by Nancy.Serialization.JsonNet is unavailable. Adding a library mapping to the application config fixed the issue: <configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /> <bindingRedirect oldVersion="<IP_ADDRESS>-<IP_ADDRESS>" newVersion="<IP_ADDRESS>" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration> This was discovered by trying to load the JsonNetSerializer early within the Main method: Type t=typeof(JsonNetSerializer); This triggered the load error and lead to the config resolution.
common-pile/stackexchange_filtered
Android CPU ARM architectures We have a Android CPU dependent code and I would like to see how many devices used by customers are ARMv6/ARMv7, if there are still ARM v5, how many of ARMv6 have VFP, what is the Tegra or Neon percentage. Any tips where such statistics could be found? BR STeN One thing that should make it easier. There were never any ARMv5 Android phones. The minimum CPU used was a Qualcomm MSM7200 (ARMv6). There may be some inexpensive tablets which used cheaper ARM CPUs, but they would represent a tiny % (if they exist at all). is this a programming question? Hi BitBank, the MXPlayer for ARMv5 has 100-500K downloads on Google Play, so there are some devices... Intel/Marvell XScale is ARMv5TE, and some early Android phones were based on XScale. If you want to collect such data, simply do "cat /proc/cpuinfo" and feed googleanalytics account with this data :) ( i am doing a lot of research this way ). If you are looking for already made statistics i think that any of them is outdated :) Normal smartphone user change his handset every year or two, dependant on his carrier policy, i would forget about armv6/armv7 and neon on your place, armv6 is currently sold only in some chinese crapphones :), and neon is very nice but for example tegra 2 is incompatibile with it, the other side is that tegra2 has about 0.05 percent of market share, vfp is supported in every armv7, and arm v7 is about 95 percent of market or more. I doubt that anybody who use google play or actually is paying for apps use armv6 or antyhing older, most of google play users are using samsung galaxy for example about 20percent of overall downloads of my apps are downloaded on galaxy s2, 10 percent on nexus, and it looks like supporting all/older devices its not a good idea at all, its takes a lot of time, and paying users are usually using highend handsets. In the end I don't think that this kind of data can change the way you write your application, because no matter what report says the situation is: the Play Store application do not check for this kind of features considering the previous statement, the only way to run your application correctly is to check at runtime for the support for that technology, for example you have to check if the device supports NEON, and it's your problem to do that as programmer, the Play Store doesn't check for that. if you are not using a particular instrunctions set you don't have this problem so this question should be erased in 3, 2, 1 ... ! Another consideration is the fact that ARM is an architecture that can have multiple forms and with that i mean the fact that if you pick 2 commercial product like the Tegra 2 and OMAP 4430, they are both ARMv7 devices but the Tegra 2 doesn't support NEON while the entire OMAP 4 family support this kind of registry, so not even the label about the instructions set can really tell you about the real potential of the device itself. In the end all that it's worth to know is that the Play Store tells you nothing about this, knowing about the most used platforms won't really help, and in the end you always have to do the same task and the check for this kind of features is up to you.
common-pile/stackexchange_filtered
object object object has no method slides/autocomplete' My site has been working completely fine for months but now suddenly no longer. Chrome provides me these errors: object object object has no method autocomplete' //When ajax search is enabled object object object has no method slides' //When ajax search is denable I tried reading other people's questions with the same problem. But seems like in most cases, it was caused by several loadings of the jquery lib - which ain't in my case. My code is sorta long, so here is the link: http://tinyurl.com/d2cn6ng Thank you for your time. Actually, jQuery is loaded twice in this case: Line 34: <script type="text/javascript" src="/js/jquery/jquery-1.4.4.min.js"></script> Line 765: <script src="jquery.js"></script><script src="jqueryui.js"></script><script src="dle_js.js"></script> Different versions - the second is jQuery 1.7.2 Ahhh..... you are right. Didn't check in the bottom. Thank you. Now just gotta find out which module add this.
common-pile/stackexchange_filtered