text
stringlengths
64
81.1k
meta
dict
Q: MongoDB Aggregate a sub field of an array (Array is main field) I have a database in MongoDB. There are three main fields: _id, Reviews, HotelInfo. Reviews and HotelInfo are arrays. Reviews has a field called Author. I would like to print out every author name (once) and the amount of times they appear within the dataset. I tried: db.reviews.aggregate( {$group : { _id : '$Reviews.Author', count : {$sum : 1}}} ).pretty() A part of the results were: "_id" : [ "VijGuy", "Stephtastic", "dakota431", "luce_sociator", "ArkansasMomOf3", "ccslilqt6969", "RJeanM", "MissDusty", "sammymd", "A TripAdvisor Member", "A TripAdvisor Member" ], "count" : 1 How it should be: { "_id" : "VijGuy", "count" : 1 }, { "_id" : "Stephtastic", "count" : 1 } I posted the JSON format below. Any idea on how to do this would be appreciated JSON Format A: Lets assume that this is our collection. [{ _id: 1, Reviews: [{Author: 'elad' , txt: 'good'}, {Author: 'chen', txt: 'bad'}] }, { _id: 2, Reviews: [{Author: 'elad', txt : 'nice'}] }] to get the data as you want we need to first use the unwind stage and then the group stage. [{ $unwind: '$Reviews' }, {$group : { _id : '$Reviews.Author', count : {$sum : 1}}}] You need to first unwind the collection by the Reviews field. after the unwind stage our data in the pipeline will look like this. {_id:1, Reviews: {Author: 'elad' , txt: 'good'}}, {_id:1, Reviews: {Author: 'chen' , txt: 'bad'}}, {_id:2, Revies: {Author: 'elad', txt : 'nice'} The unwind created a document for each element in Reviews array with the element itself and his host document. Now its easy to group in useful ways as you want. Now we can use the same group that you wrote and we will get the results. after the group our data will look like this: [{_id: 'elad',sum:2},{_id: 'chen', sum: 1}] Unwind is a very important pipeline stage in the aggregation framework. Its help us transform complex and nested documents into flat and simple, and that help us to query the data in different ways. What's the $unwind operator in MongoDB?
{ "pile_set_name": "StackExchange" }
Q: How to get Line-s from Canvas Children in WPF I'm trying to delete some lines I have drawn on my canvas, and my idea was to use the coordinates of the Line controls from Canvas.Children. My initial code looked like this: var ax = Mouse.GetPosition(Canvas).X; int mx1 = (int)ax - (eraserSize / 2); int mx2 = (int)ax + (eraserSize / 2); var ay = Mouse.GetPosition(Canvas).Y; int my1 = (int)ay - (eraserSize / 2); int my2 = (int)ay + (eraserSize / 2); foreach(Line l in Canvas.Children) { if((l.X1 < mx1 && lX2 > mx2) && (l.Y1 < my1 && lY2 > my2)) { Canvas.Children.Remove(l); } } But of course it doesn't work since there are other controls that it cannot cast to Line. I tried using if(l.Name == "LineName") to put these in a Line[] or Control[] but nothing works, and I'm not sure what else to try, other then just painting over it... A: foreach(var child in Canvas.Children) { var l = child as Line; if(l != null && (l.X1 < mx1 && lX2 > mx2) && (l.Y1 < my1 && lY2 > my2)) { // You can't remove item from collection you enumerate thru // Canvas.Children.Remove(l); LinesToDelete.Add(l); } } Than you can simple remove all lines that got to LinesToDelete
{ "pile_set_name": "StackExchange" }
Q: Can I overload functions with type-traits? Let's say, I have six types, and they each belong in a conceptual category. Here is a diagram that shows this: Or Perhaps a more specific example for you: I want to write two functions that will handle all 6 types. Types in "Category 1" get handled a certain way, and types in "Category 2" get handled a different way. Let's get into the code. First, I'll create the six types. //Category 1 Types class Type_A{}; class Type_B{}; class Type_C{}; //Category 2 Types class Type_D{}; class Type_E{}; class Type_F{}; Next, I'll create two type traits so that the category of the type can be discovered at compile time. /* Build The Category 1 Type Trait */ //Type_A Type Trait template <typename T> struct Is_Type_A { static const bool value = false; }; template <> struct Is_Type_A<Type_A> { static const bool value = true; }; //Type_B Type Trait template <typename T> struct Is_Type_B { static const bool value = false; }; template <> struct Is_Type_B<Type_B> { static const bool value = true; }; //Type_C Type Trait template <typename T> struct Is_Type_C { static const bool value = false; }; template <> struct Is_Type_C<Type_C> { static const bool value = true; }; //Category 1 Type Trait template <typename T> struct Is_Type_From_Category_1 { static const bool value = Is_Type_A<T>::value || Is_Type_B<T>::value || Is_Type_C<T>::value; }; /* Build The Category 2 Type Trait */ //Type_D Type Trait template <typename T> struct Is_Type_D { static const bool value = false; }; template <> struct Is_Type_D<Type_D> { static const bool value = true; }; //Type_E Type Trait template <typename T> struct Is_Type_E { static const bool value = false; }; template <> struct Is_Type_E<Type_E> { static const bool value = true; }; //Type_F Type Trait template <typename T> struct Is_Type_F { static const bool value = false; }; template <> struct Is_Type_F<Type_F> { static const bool value = true; }; //Category 1 Type Trait template <typename T> struct Is_Type_From_Category_2 { static const bool value = Is_Type_D<T>::value || Is_Type_E<T>::value || Is_Type_F<T>::value; }; Now that I have two type traits to distinguish what category each of the six types fall into, I want to write two functions. One function will accept everything from Category 1, and the other function will accept everything from Category 2. Is there a way to do this without creating some kind of dispatching function? Can I find a way to have only two functions; one for each category? EDIT: I have tried to use enable_if like this, but such an attempt will result in a compiler error. //Handle all types from Category 1 template<class T ,class = typename std::enable_if<Is_Type_From_Category_1<T>::value>::type > void function(T t){ //do category 1 stuff to the type return; } //Handle all types from Category 2 template<class T ,class = typename std::enable_if<Is_Type_From_Category_2<T>::value>::type > void function(T t){ //do category 2 stuff to the type return; } Edit 2: I've tried the code provided in the link, but this isn't a yes or no decision on whether or not to call the function. It's which function do I call, given two type traits. This would be a redefinition error. //Handle all types from Category 2 template<class T, class dummy = typename std::enable_if< Is_Type_From_Category_1<T>::value, void>::type> void function(T t){ //do category 1 stuff to the type return; } //Handle all types from Category 2 template<class T, class dummy = typename std::enable_if< Is_Type_From_Category_2<T>::value, void>::type> void function(T t){ //do category 2 stuff to the type return; } A: I think using tag despatch would be easier than SFINAE. template<class T> struct Category; template<> struct Category<Type_A> : std::integral_constant<int, 1> {}; template<> struct Category<Type_B> : std::integral_constant<int, 1> {}; template<> struct Category<Type_C> : std::integral_constant<int, 1> {}; template<> struct Category<Type_D> : std::integral_constant<int, 2> {}; template<> struct Category<Type_E> : std::integral_constant<int, 2> {}; template<> struct Category<Type_F> : std::integral_constant<int, 2> {}; template<class T> void foo(std::integral_constant<int, 1>, T x) { // Category 1 types. } template<class T> void foo(std::integral_constant<int, 2>, T x) { // Category 2 types. } template<class T> void foo(T x) { foo(Category<T>(), x); } A: Two functions signatures are not allowed to differ only by the default value of a template parameter. What would happen if you explicitly called function< int, void >? Usual usage of enable_if is as the function return type. //Handle all types from Category 1 template<class T > typename std::enable_if<Is_Type_From_Category_1<T>::value>::type function(T t){ //do category 1 stuff to the type return; } //Handle all types from Category 2 template<class T > typename std::enable_if<Is_Type_From_Category_2<T>::value>::type function(T t){ //do category 2 stuff to the type return; } A: As an alternative to category selection via "traits", you can also consider CRTP (where the type carries the category as a base): template<class Derived> class category1 {}; template<class Derived> class category2 {}; class A1: public category1<A1> { ..... }; class A2: public category2<A2> { ..... }; class B1: public category1<B1> { ..... }; class B2: public category2<B2> { ..... }; template<class T>void funcion_on1(category1<T>& st) { T& t = static_cast<T&>(st); ..... } template<class T>void funcion_on1(category2<T>& st) { T& t = static_cast<T&>(st); ..... } The advantage is to have a less polluted namespace.
{ "pile_set_name": "StackExchange" }
Q: AS3 Class inheritance problem Please help Stackoverflow! I have a MapInterface class in AS3 that inherits from Interface class. public class Interface extends Sprite { public function Interface(){ // do stuff } } and then import com.georgecrabtree.Interface; public class MapInterface extends Interface { public function MapInterface(){ addMapButtons(); } public function addMapButtons():void { trace("init"); } } this all works fine, and when I create a new MapInterface class from the document class it traces out init. But when I try to call this: var mapInterface:MapInterface = new MapInterface(); mapInterface.addMapButtons(); from the main timeline I get this error: 1061: Call to a possibly undefined method addMapButtons through a reference with static type com.georgecrabtree:Interface. Thanks in advance for any help, George A: If I understand the problem correctly, I think your second code sample has a typo. I imagine it is actually: var mapInterface:Interface = new MapInterface(); mapInterface.addMapButtons(); The problem is that your variable is of type Interface, which does not define an addMapButtons() method. You can fix the problem either by changing the variable type to MapInterface, or by adding an addMapButtons() method to Interface and overriding the method in MapInterface.
{ "pile_set_name": "StackExchange" }
Q: MonoTouch iPhone orientations are not matched pairs I'm just starting out with MonoTouch and have just written the usual Hello World type app that does very little. I'm trying to get a completely clean build with no errors or warnings. I am getting the warning: Info.plist: Warning: Supported iPhone orientations are not matched pairs I know why - it's because Portrait upside down is not selected. But that's the recommendation from Apple (and in fact the MonoTouch default!) so why give a warning. How do I get rid of this warning? (without adding upside down, obviously) A: IIRC Apple recommend this behaviour for the iPhone but not for the iPad. It's likely that the addin does not make the distinction and warn for every case. How do I get rid of this warning? I do not think you can (presently). However it's a warning (not an error) so it will not cause any issue with your build. If it really bother you I suggest you to fill an enhancement bug report with Xamarin (under MonoDevelop, iPhone addin).
{ "pile_set_name": "StackExchange" }
Q: Remove markers from google maps iOS I am building an iOS app using storyboards and Google Maps. Using iOS6 My application features the split view navigation as seen in the facebook app On my left view I am selecting an item in a list which has lat/long cords and showing it on my map on the following method - (void)viewWillAppear:(BOOL)animated I would like to remove all markers in this method before I add another one (so only one marker is on the map), is there a way to do this? Below is my code to add a marker to the mapView Thanks in advance - Jon - (void)loadView { GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:poi.lat longitude:poi.lon zoom:15]; mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera]; mapView.myLocationEnabled = YES; self.view = mapView; mapView.mapType = kGMSTypeHybrid; //Allows you to tap a marker and have camera pan to it mapView.delegate = self; } -(void)viewWillAppear:(BOOL)animated { GMSMarkerOptions *options = [[GMSMarkerOptions alloc] init]; options.position = CLLocationCoordinate2DMake(poi.lat, poi.lon); options.title = poi.title; options.snippet = poi.description; options.icon = [UIImage imageNamed:@"flag-red.png"]; [mapView addMarkerWithOptions:options]; [mapView animateToLocation:options.position]; [mapView animateToBearing:0]; [mapView animateToViewingAngle:0]; } A: To remove all markers mapView.clear() To remove a specific marker myMarker.map = nil A: To remove all markers simple do: [self.mapView clear]; A: Please refer to the Google Map documentation: Google Maps SDK for iOS Please refer to the section title "Remove a marker". Always check documentation for such methods.
{ "pile_set_name": "StackExchange" }
Q: LINQ subquery question Can anybody tell me how I would get the records in the first statement that are not in the second statement (see below)? from or in TblOrganisations where or.OrgType == 2 select or.PkOrgID Second query: from o in TblOrganisations join m in LuMetricSites on o.PkOrgID equals m.FkSiteID orderby m.SiteOrder select o.PkOrgID A: Do you need the whole records, or just the IDs? The IDs are easy... var ids = firstQuery.Except(secondQuery); EDIT: Okay, if you can't do that, you'll need something like: var secondQuery = ...; // As you've already got it var query = from or in TblOrganisations where or.OrgType == 2 where !secondQuery.Contains(or.PkOrgID) select ...; Check the SQL it produces, but I think it should do the right thing. Note that there's no point in performing any ordering in the second query - or even the join against TblOrganisations. In other words, you could use: var query = from or in TblOrganisations where or.OrgType == 2 where !LuMetricSites.Select(m => m.FkSiteID).Contains(or.PkOrgID) select ...;
{ "pile_set_name": "StackExchange" }
Q: Best Approach for Localisation variables I read more articles related to localization best practices. From them we can identigy that always UTCtime is best for handling date time. Like that we have some guidence like concetenation of string, ui etc. But i also found one article saying we need to handle string / integer conversion. I din't get it properly. The following is the explanation "Be sure to always pass CultureInfo when calling ToString() unless it is not supported. That way you are commenting your intents. For example: if you are using some number internally and for some reason need to convert it to string use: int i = 42; var s = i.ToString(CultureInfo.InvariantCulture); For numbers that are going to be displayed to user use: var s = i.ToString(CultureInfo.CurrentCulture); // formatting culture used The same applies to Parse(), TryParse() and even ParseExact() - some nasty bugs could be introduced without proper use of CultureInfo. That is because some poor soul in Microsoft, full of good intentions decided that it is a good idea to treat CultureInfo.CurrentCulture as default one (it would be used if you don't pass anything) - after all when somebody is using ToString() he/she want to display it to user, right? Turn out it is not always the case - for example try to store your application version number in database and then convert it to instance of Version class. Good luck. " But why this is needed. So in all datatatypes we need to convert / do like this? what is the advatages for this as i got same result as with out adding culture info. A: If you do like this double i = 42.42; var s = i.ToString(); and run it on your on English PC (US or UK locale), then s will be 42.42 Now run it on German or Russian PC and suddenly s become 42,42 This different decimal point could lead to countless bugs in many places (when you save/load data, when you show values and reading user inputs, etc). One possible ultimate solution, if your software will run on different locales, is to use ColtureInfo.InvariantCulture always when you operate with data and only when require user interruction CultureInfo.CurrentCulture. With int values problem could be with thousands separator (it could be missing, space, comma, point, etc). I myself create extension methods, something like: public static string F(this string @this, params object[] args) { return string.Format(CultureInfo.InvariantCulture, @this, args); } so that i just write "{0} {1:0.#}".F(Msg.Localization.User.Prompt, i); where Msg is a localized messages class.
{ "pile_set_name": "StackExchange" }
Q: Get a list of enumeration values in Kotlin for an Any variable How can I retrieve the list of enum values in Kotlin for a variable of Any type? There are plenty of questions on how to print the list of enum values, but these all start from a known enum class. How can I get the list of enum values for a variable that is an enum? import kotlin.reflect.full.isSubclassOf enum class Direction { NORTH, SOUTH, WEST, EAST } enum class Days { MON, TUE, WED, THU, FRI, SAY, SUN } fun main(){ val x1: Any = Direction.NORTH val x2: Any = Days.TUE val x3: Any = 100.0 printEnumValues(x1)// should print NORTH, SOUTH, WEST, EAST printEnumValues(x2)// should print MON, TUE, WED, THU, FRI, SAY, SUN printEnumValues(x3)// should print nothing. } fun printEnumValues(arg : Any) { if (arg::class.isSubclassOf(Enum::class)){ // How to get and print the list of possible enum values here? } } A: I don't know if it can be done with Kotlin reflection, but you can borrow Java reflection to do it like this: fun printEnumValues(arg: Any) { if (arg is Enum<*>) { println(arg::class.java.enumConstants.joinToString()) } }
{ "pile_set_name": "StackExchange" }
Q: Add New columns in Html Table using JQuery I have created one HTML table using a forEach loop. I need to add one column in the only header portion. I have two titles which are display in two tables simultaneously, Open Projects and Closed Projects, and I need to add columns under both of them. <table align="center" cellpadding="0" cellspacing="0" width="100%;" border="1"> <tr> <td> <table style="width:100%;"> @foreach ($boardgroups as $boardgroupsitem) <tr> <td> <h2>{{$boardgroupsitem["grouptitle"]}}</h2> </td> </tr> <tr> <td colspan="3"> <table cellpadding="0" cellspacing="0" id="tbl_table"> <tbody> <tr id="tr_Col"> <td style="width:220px;font-weight:bold;"></td> @php $i=0; foreach($group as $subgroup) { @endphp <td style="width:180px;text-align:center;"> {{$subgroup[$i]->title}} </td> @php $i++; } @endphp </tr> </tbody> <tr id="tr_row"> <td></td> @php $i=0; $mainid=$boardgroupsitem["id"]; $i=0; foreach($grouprows[$mainid] as $grouprw) { $i++; @endphp <td id="div_row" style="text-align:center;">{{$grouprw["title"]}}</td> @php if($i%2==0) { @endphp </tr> <td></td> @php } } @endphp </table> </td> </tr> @endforeach </table> </td> </tr> </table> A: I believe you want to add new column to the table with the id tbl_table. If so, maybe this will work in jQuery: $(function(){ $("#btnAddColumn").on('click', function(){ $("#tbl_table tr").append("<td></td>"); }); }); What we are doing is, we are adding empty <td> elements to each row of the table with the id tbl_table when a button with the id btnAddColumn is clicked. Also, I would like to point out some things. You can enclose all the <tr> elements inside the <tbody>. A table can have a <thead> and a <tbody>. Secondly, when you use id= attribute for any elements, make sure that you are not repeating the same id. I mean, the id attribute should be unique in a HTML dom. That is, no two elements can have the same id name! In your code, I believe you are repeating the ids tr_row, div_row, tr_Col, tbl_table, etc. as these are inside a loop! In such cases, a class attribute is the best. Because class names are not expected to be unique, whereas id names are! Hope it helps. If not, please EDIT your question and include more details so that we maybe able to throw some more ideas. EDIT Based on your comments, am providing the solution. Try changing this line: <tr id="tr_Col"> to <tr class="tr_Col"> Then, try this code: $(function(){ $("#btnAddColumn").on('click', function(){ $(".tr_Col").append("<td></td>"); }); });
{ "pile_set_name": "StackExchange" }
Q: Get all Images from a Folder and add it to Slider I have a folder named first - res/drawable/pics/first.The folder can contain upto 5 images(5 or less than 5).I need to loop through all these images and add to this slider https://github.com/daimajia/AndroidImageSlider Is something like this possible? x=5; sliderShow1 = (SliderLayout)findViewById(R.id.ad1); TextSliderView[] textSliderViewarray=new TextSliderView[x]; for (int y=0;y<x;y++) { textSliderViewarray[y]=new TextSliderView(this); } for (int y=0;y<x;y++) { textSliderViewarray[y].description(" ").image("@drawable/pics/first/"+Integer.toString(y+1)+".png"); sliderShow1.addSlider(textSliderViewarray[y]); } This code creates 5 sliders with blank content. A: Try this: The root folder of the images should be drawable. Don't keep in nested folders. Use the following code: for (int y=0;y<x;y++) { // Assuming image names as 1.png, 2.png, 3.png ... String resourceName = Integer.toString(y); // Extension is not needed. int resourceId = getResources().getIdentifier(resourceName, "drawable", getPackageName()); textSliderViewarray[y].description(" ").image(resourceId); sliderShow1.addSlider(textSliderViewarray[y]); }
{ "pile_set_name": "StackExchange" }
Q: I want to remove occurrences of a given letter I have attempted to remove the occurrences of a user inputted letter after they've chosen a word however, the final output prints out a random string of letters and numbers instead of what I expected. For example, if the user enters the text "Coffee" then proceeds to enter the letter "f", the program should return "Coee" as the final print. However, this is not the case. Could anyone check to see where I've gone wrong? Much obliged. #include <iostream> #include <string> using namespace std; void removeAllOccurrence(char text[], char letter) { int off; int i; i = off = 0; if (text[i] == letter) { off++; } text[i] = text[i + off]; } int main() { string text; char letter; string newText; cout << "Type your text: " << endl; cin >> text; cout << "Choose the letters to remove: " << endl; cin >> letter; cout << "your new text is: " << removeAllOccurrence << endl; system("pause"); return 0; } A: This should do the job #include <algorithm> #include <string> #include <iostream> void remove_char(std::string s, char r) { s.erase( std::remove( s.begin(), s.end(), r), s.end()) ; std::cout << s << std::endl; } int main() { std::string test = "coffee"; char r = 'f'; remove_char(test, r); return 0; }
{ "pile_set_name": "StackExchange" }
Q: ICA Protocol with Streamed App's - XenApp I'm studying XenApp and I know that the ICA protocol is used when hosting an application to the XenApp server. But does the ICA protocol is also used when streaming an application from xenapp to the client ? Thanks A: Citrix app streaming is an application virtualization technology similar to Microsoft's App-V. A streamed (aka virtualized) application is packaged in a so-called profile which is transferred to the client for local execution. The transfer can happen over the following protocols: SMB (aka CIFS) HTTP HTTPS Further reading: Application Streaming Delivery and Profiling Best Practices
{ "pile_set_name": "StackExchange" }
Q: Questions about Drombler FX for NetBeans Platform RCP application I am looking for a JavaFX application framework to use in a NetBeans Platform based application. Would it be possible to use Drombler FX in it? I looked at other alternatives (mFx and eFX, but seem abandoned) and I would like to avoid the mixed look of Swing with JavaFX. I tried to run the sample application to get a better idea of its functionality, but I got an error when I follow the get started instructions to generate it: Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:2.4:generate (default-cli) on project standalone-pom: The desired archetype does not exist (org.drombler.fx:drombler-fx-maven-archetype-application:0.8-SNAPSHOT) Lastly, is Drombler FX under active development? A: I'm the main developer of Drombler FX. Lastly, is Drombler FX under active development? Yes, Drombler FX is under active development. The desired archetype does not exist (org.drombler.fx:drombler-fx-maven-archetype-application:0.8-SNAPSHOT) Please note, that at the time of writing, the latest released version is 0.7. All artifacts of v0.7 have been deployed to Maven Central and should be available. You can find the Getting Started page of the v0.7 tutorial here. If you really want to use the SNAPSHOT versions of the current development, please add a proxy to the following repo to your Maven Repository Manager (such as Nexus): https://oss.sonatype.org/content/repositories/snapshots/ I am looking for a JavaFX application framework to use in a NetBeans Platform based application. Would it be possible to use Drombler-FX in it? I looked at other alternatives (mFx and eFX, but seem abandoned) and I would like to avoid the mixed look of Swing with JavaFX. Drombler FX has not been designed for integration in a NetBeans Platform Application and it does not support NetBeans Platform Modules out-of-the-box. As the NetBeans Platform supports OSGi (at least to some degree?), I guess you would have to find replacements at least for the bootstraping code, which you can find here: https://github.com/Drombler/drombler-acp/tree/develop/drombler-acp-startup-main https://github.com/Drombler/drombler-fx/tree/develop/drombler-fx-startup-main But even if you would manage it, wouldn't you still have the mix of Swing and JavaFX you would like to avoid?
{ "pile_set_name": "StackExchange" }
Q: How to redirect all 404s to the same path on a different server I want to redirect all 404 errors on my site to the same path on a different server. For example: http://drupal.example.com/url/not/in/drupal should be redirected to http://othersite.example.com/url/not/in/drupal The sites are not on the same server and the other site is not running Drupal. I know I can use the redirect module to redirect specific URLs but I don't have a complete list of the URLs on the other site so building the list is not practical. Suggestions for modules or pointers to the appropriate hooks if I want to write my own module would be appreciated. A: Here is small trick: Enable module PHP Filter, add PHP filter to administrator Create a node can use php filter, add code: (We are using header here, not use drupal_goto because handle 404 workfollow of Drupal will redirect to the node first. <?php $url = drupal_get_destination(); header('Location: http://other.example.com/' . $url['destination']); drupal_exit(); ?> Config Drupal using 404 page is the node you was create.
{ "pile_set_name": "StackExchange" }
Q: Difference between tangent space and tangent plane I’ve avoided doing any manifold (regretting it somewhat) courses, however do have some understanding. Let $p$ be a point on a surface $S:U\to \Bbb{R}^3$, we define: The tangent space to $S$ at $p$, $T_p(S)=\{k\in\Bbb{R}^3\mid\exists\textrm{ a curve }\gamma:(-ε,ε)\to S\textrm{ with }\gamma(0)=p,\gamma'(0)=k\}$. The tangent plane to $S$ at $p$ as the plane $p+T_p(S)\subseteq\Bbb{R}^3$. My current understanding is, in the diagram below the tangent plane is the plane shown, whilst the tangent space would be p minus each element of the plane, hence the corresponding plane passing through the origin. Is this correct or is it incorrect? I’m doing a course called geometry of curves and surfaces and being unsure about this is making understanding later topics difficult. Edit - can't post images, here's a link instead! http://standards.sedris.org/18026/text/ISOIEC_18026E_SRF/image022.jpg Thanks! A: While the definitions you've given are acceptable, I would use different definitions for tangent space and tangent plane that reveal some more mathematical structure. The tangent plane is a geometric object. You can define the tangent plane to a point $p$ on a surface $S$ in $\mathbb{R}^3$ as a plane in $\mathbb{R}^3$ which intersects $p$ and whose normal vector is parallel to the gradient of $f$, if $S$ is represented as the level surface $f(x,y,z) = 0$. But all that formality is simply used to the describe the geometric object that everybody can visualize intuitively. The tangent space is a vector space of linear functionals. Each vector $v \in T_p S$ acts on a function $g \in C^1(S)$ in a way such that $v(g)$ gives you a directional derivative of $g$ in a particular direction (which can be identified with $v$ itself). Thus the tangent space $T_p S$ can be naturally identified with the tangent plane, because the only directions that make sense to take the directional derivative on are the directions that lie on the tangent plane. A: Exactly. The tangent space is simply a translation of the tangent plane by taking $p$ to $0$. One nice property that the tangent space always has (but which a tangent plane almost never does) is that it is closed under addition and scalar multiplication--that is, for any $\alpha\in\Bbb R$ and any $x,y$ in the tangent space, we have $x+y$ and $\alpha x$ in the tangent space.
{ "pile_set_name": "StackExchange" }
Q: Python error when executing shell script I'm executing a line of shell script using python. It isn't working with which to test of the existence of homebrew #!/usr/bin/python import sys, subprocess subprocess.call(["which python"]) throws the long error Traceback (most recent call last): File "installations.py", line 5, in <module> subprocess.call(["which python"]) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 522, in call return Popen(*popenargs, **kwargs).wait() File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 709, in __init__ errread, errwrite) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1326, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory But I know that the shell execution is working correctly on some level #!/usr/bin/python import sys, subprocess subprocess.call(["whoami]) prints my username just fine. Am I doing something wrong, or is which for some reason not supported. Is there some better supported way of detecting the existence of an installation? A: The failing call is trying to find an executable named 'which python' not running which with an argument of python as you likely intended. The list that you pass to call (unless shell=True is set) is the list of the command and all the arguments. Doing subprocess.call(['which', 'python']) will probably give you what you are looking for. A: When calling this way you need to separate each word on your command line as a different element of an iterable: subprocess.call(["which", "python"]) I highly recommend reading the docs several times through in order to truly understand all the possible ways of launching subprocesses and how they differ from each other.
{ "pile_set_name": "StackExchange" }
Q: How to use JS property like "offsetWidth" in angular 4 I am trying to get the width of an element using JS in my Angular app. document.getElementsByClassName("element")[0].offsetWidth; When I do this i am getting the below compilation error Property 'of fsetWidth' does not exist on type 'Element'. Could someone tell me how to use it in Angular 4. Thanks A: If give identification of your DOM element using # Template: <div class="for-example" #titleText>For Example</div> Component: Declare @ViewChild('titleText') titleTextElement; and get offsetWidth like following: this.titleTextElement.nativeElement.offsetWidth
{ "pile_set_name": "StackExchange" }
Q: Passing the address from an element of an array of pointers to set another pointer address I've tried searching through responses, but examples unfortunately seem too complex for me to understand. Most fundamentally I want to know how I can pass and change the addresses of an array of pointers. Example: class Foo { M** arryM; ... arryM = new M*[10]; ... void Foo::replace(int ind, M &newm) { // Q1: which one correct to change the address of an element to a new object's address? arryM[ind] = newm; // this correct to pass and reset a new address for pointer? arryM[ind] = &newm; // or is this correct, or does this just set the object pointed by array element instead of the array element's address? *arryM[ind] = newm; // or do I need to dereference the pointer rep by array element first? &arryM[ind] = &newm; // or is this correct?? } ... // Q2: is it easier to return a pointer or address for this function? M & Foo::getM(int ind) { M *out; // Q3: which one of following correct to get correct address value to return? out = arryM[ind]; // get address to M obj pointed by pointer array elem out = *arryM[ind]; // is "arryM[ind]" == "*ptr"?? if so how to get to "ptr"? out = &arryM[ind]; // is this way to get to "ptr" so addresses passed? return out; } } void main() { M *op1; M *op2; M *sol; Foo mstorage; // and assume already got valid M objects pointed to by arryM[] elements ... // Q4: which one correct? op1 = mstorage.getM(x); // x being the correct and valid int index pos op1 = *mstorage.getM(x); // so address and not object pointed to is passed? *op1 = mstorage.getM(x); op2 = mstorage.getM(y); ... // perform some operations using op1 and op2 M functions int size = op1->getDim() + op2->getDim(); sol = new M(size, name); // no default constructor--M objects need a size parameter ...// perform/set values of sol based upon op1, op2 values // Q5: this is correct to pass the address for sol object created, right? if (<sol already exists>) mstorage.replace(indx, *sol); else mstorage.add(*sol); } So my 5 main questions extracted from the code sample are below, and Q1, Q3, Q4 are most important/confusing to me: Q1 (important): if an array[i] returns a pointer *n, then how can we dereference "array[i]" to look like "n" so we can get "n=p" where "*p" has an address of an externally created object. Also, where "*p" is passed through a function call with type& parameter. Q2 : in the given context, is it better to return a pointer or an address in the function? Or would it be easier to change the context to work with one function return type over the other? Q3 (important): if we are returning an address, what is the correct way to get "array[i]" (based on same assumption as in Q1) to be the address contained in "n" and not object represented by "*n"? Q4 (important): if a function is returning an address &, then is a locally created pointer *p able to receive an address by "p = obj.funcretaddress()"? I saw some example code with doubles though that made me confused: "double hours = funcreturningaddress()". Q5 : just double checking that if a function parameter takes "obj &x" and we locally create a "obj *y" that in the function call we would pass "function(*y)" and then within the function scope "obj *n = &x" so that a pointer represented by array[i] could take correct address of the locally created obj. Many thanks, as I have been compiling and tweaking for several days now, getting confused trying to take examples with int and double data types from the web and apply them to created class objects. My apologies and please let me know if anything unclear! edit: Many thanks, and just wanted to clarify the Q4: int a = 2; int *b; b = &a; *b = 3; int c = 4; b = func(c); // *b now points to c, and value is 5? *b = func(c); // *b value is updated to 5, and a therefore also now 5?? ... int & func(int &d) { d++; return &d; // correct, or wrong as &&d is returned? return d; // and the & is applied to the var d? } A: Q1. Following two are correct. arrayM[ind] will return pointer. So think that you are storing into the pointer. Be careful, about the lifetime of object you are adding (i.e. newM) arryM[ind] = &newm; // or is this correct, or does this just set the object pointed by array element instead of the array element's address? *arryM[ind] = newm; Q2. Following is correct. out = arryM[ind]; Additionally, you can not return pointer when it is expecting reference. So either you can modify function to sender pointer or send value instead of pointer. Q3. If you are returning address as follows return array[ind] then that would return a pointer. (i.e. M* myArray). You can access elements as follows 1. myArray[index] 2. *(myArray+1) Q4.If you returning reference (i.e M&) then you must collect them in either reference or normal object otherwise you can also store the value into pointer as follows. Function: M& foo() Call: M m = foo() OR M& m = foo() OR M* m; *m = foo(); Q5. I could not get your question here. I shall update it later. Let me know if you need detailed explanation.
{ "pile_set_name": "StackExchange" }
Q: Navbar div off centre by border I have a navbar: HTML: <div id="navbar"> </div> CSS: #navbar{ width: 100%; height: 50px; background-color: #F0F0F0; border-color: #B2B2B2; border-style: solid; -webkit-border-radius: 16px; -moz-border-radius: 16px; border-radius: 16px; } For some reason, the border makes it offcenter, there is always some space to the left of the div but not on the right. How do I fix this problem??? A: Remove width: 100% from your CSS. The div is block-level, so will take up all available horizontal space. Adding an explicit 100% just introduces problems when you then give it padding or, in this case, border
{ "pile_set_name": "StackExchange" }
Q: Find for which values of $\alpha\in\mathbb R, f_n(x)$ converge uniformally The question is "Find for which values of $\alpha\in\mathbb R$ such that $ f_n(x)$ converge uniformally in $[0,\infty)$ where $f_n(x)=n^\alpha x \dot e^{-nx} $". For $\alpha<0$, the sequence converges uniformally to $0$ (since $\forall x\in[0,\infty):e^{nx}>x $ hence the denominator is bigger then the counter and tend to infinity). My problem is I don't know how to procedd further... The book claims the sequence converges $\forall \alpha<1$. Why is this answer correct? A: We know that the $f_n$ are continuous and non-negative, that $f_n(0) = 0$ and $\lim_{x\to\infty} f_n(x) = 0$, since the exponential function grows much faster than $x$. So let's try to find $\max \{ f_n(x) \colon x \in [0,\,\infty)\}$. That must be a critical point of $f_n$, so let's try to find the zeros of $f_n'$. $$f_n'(x) = n^\alpha e^{-nx} + n^\alpha x \cdot(-n)e^{-nx} = n^\alpha e^{-nx} (1-nx).$$ The only zero of $f_n'$ is therefore $x = \frac1n$, and thus that must be the point where $f_n$ attains its maximum. $$f_n(\frac1n) = n^\alpha \frac1n e^{-n\frac1n} = n^{\alpha-1}/e,$$ and $n^{\alpha-1} \to 0 \iff \alpha < 1$.
{ "pile_set_name": "StackExchange" }
Q: can someone explain to me !lockButton in this jquery This is partial code from a simple calculator exercise: From my understanding the ! reverses the boolean value, so since lockButtons was set to false, is it now true in the first if statement? But later below in the if check =, we set lockButtons to true so it stops any numbers from being inputted, it's probably simple but i can't wrap my head around it. var firstNumber = ""; var secondNumber = ""; var operator = ""; var result = 0; var hasNumber = false; var firstNumberComplete = false; var lockButtons = false; // Check if any button is clicked... $(document).on("click", "button", function() { // Checks if it's a number and that its not the end of the calculation ("!lockButtons") if ($(this).hasClass("number") && !lockButtons) { // We'll then set our "hasNumber" variable to true to indicate that we can proceed in selecting an operator. hasNumber = true; // If we haven't received an operator yet... if (firstNumberComplete === false) { // Then grab the number of the value clicked and build a string with it firstNumber += $(this).attr("value"); // Print the number to the firstPage console.log(firstNumber); // Print it to the div $("#first-number").html(firstNumber); } // If we have received an operator already... else { // Grab the number of the value clicked and build a string with it secondNumber += $(this).attr("value"); // Print the number to the firstPage console.log(secondNumber); // Print it to the div $("#second-number").html(secondNumber); } } // Checks if its an operator (but not "=") if ($(this).hasClass("operator") && hasNumber && !lockButtons) { firstNumberComplete = true; // Set the visual to show the operator's symbol $("#operator").html("<h1>" + $(this).text() + "</h1>"); operator = $(this).attr("value"); } // Checks if the equal button has been pressed. If so... if ($(this).hasClass("equal")) { // Lock the keyboard from being clicked lockButtons = true; A: var lockButtons = false; This statement creates a boolean variable which which can have a value of true or false. So you can use it directly in if if(lockbutton) Since lockbutton is set to false the statements inside if will not be executed. if ($(this).hasClass("number") && !lockButtons) This statement should be clear to you. if both the conditions are true then only the statements inside if will be executed. Also I think it's pretty clear why a statement has been put at a particular place by the comments above almost all of them.
{ "pile_set_name": "StackExchange" }
Q: display webpage inside other webpage without frames i'm looking for a way to display a web page inside a div of other web page. i can fetch the the webpage with CURL, but since it has an external stylesheet when i try to display it, it appears without all his style properties. i remember facebook used this technique with shared links (you used to see the page that was linked with a facebook header) did some unsuccessful jquery tests but I'm pretty much clueless about how to continue.. i know this can be done with frames but i always here that it's good practice to avoid frames so i'm a bit confused any ideas how to work this out? A: If you want to display the other website's contents exactly as they are rendered in that site then frames are, in this case, the best (easiest) way to go. Facebook and Google both use this technique to display pages while maintaining their branding / navigation bar above the other site.
{ "pile_set_name": "StackExchange" }
Q: Use jQuery.queue instead of setTimeout I want to append an element to the DOM and then add a class with transition to apply a sliding effect. Currently I'm using setInterval() with delay of 0, otherwise transition won't happen (demo): var $block = $('<div/>', {class: 'block'}); $('body').append($block); setTimeout(function () { $block.addClass('shifted'); }, 0); I want to utilise jQuery.queue instead, but with my current approach it doesn't work: appending the element and adding the class happen at once, so no transition is shown. $('body') .append($block) .queue(function () { $block.addClass('shifted'); }); A: If a timeout is required to make the animation happen, then you should add a delay: $('body') .append($block) .delay(0) .queue(function (next) { $block.addClass('shifted'); next(); //don't forget to dequeue so that the rest of the queue can run }); .delay() is really just a convenience method for: .queue(function (n) { setTimeout(n, duration); }); If you don't call delay (or queue a timeout), the fx queue will execute immediately, which defeats the purpose of queuing $block.addClass('shifted').
{ "pile_set_name": "StackExchange" }
Q: What is the deal with LinkName? I am new to AMQP trying to understand the concept so my question might be very naive. I am sending message to ActiveMQ Broker and while sending the message, I have to mention LinkName but that doesn't matter what I am putting at consumer side and producer side I am receiving the data anyway. I am confused what is the deal with LinkName? A: I can't really state it any better than section 2.6.1 of the AMQP 1.0 specification: 2.6.1 Naming A Link Links are named so that they can be recovered when communication is interrupted. Link names MUST uniquely identify the link amongst all links of the same direction between the two participating containers. Link names are only used when attaching a link, so they can be arbitrarily long without a significant penalty. A link’s name uniquely identifies the link from the container of the source to the container of the target node, i.e., if the container of the source node is A, and the container of the target node is B, the link can be globally identified by the (ordered) tuple (A,B,<name>). Consequently, a link can only be active in one connection at a time. If an attempt is made to attach the link subsequently when it is not suspended, then the link can be ’stolen’, i.e., the second attach succeeds and the first attach MUST then be closed with a link error of stolen. This behavior ensures that in the event of a connection failure occurring and being noticed by one party, that re-establishment has the desired effect.
{ "pile_set_name": "StackExchange" }
Q: Clang/g++ options for template instantiation I'm looking for a compiler option on g++/clang++ to control the instantiation of methods in explicit instantiations. Suppose I have a classtemplate Foo<T> with some explicit instantiation template Foo<int>; I want to enable the instantiation of all public methods. This doesn't seem to be the default, as I'm having to add manual instantiations for all the members in order to avoid link errors; template void Foo<int>:DoStuff(int); template int Foo<int>:GetSomeStuff(); A: You can either instantiate each method individually or you would instantiate all of them for the class. It seems you want to do the latter but the notation you tried is wrong. The correct one is this: template class Foo<int>; (assuming Foo is declared as a class; if it is declared as a struct you'd use the struct keyword instead).
{ "pile_set_name": "StackExchange" }
Q: tensorly.kruskal_to_tensor() method explanation I'm trying to understand tl.kruskal_to_tensor () method in tensorly package. In the webpage I understand that it takes as input a list of matrices and produces the tensor whose cp-decomposiiton are the matrices? It takes as input a list of matrices. But I saw the following code: import tensorly as tl rank =5 dim1= 9 dim2=8 dim3=7 A= tl.tensor(np.random.normal(0,1,[dim1,rank])) B= tl.tensor(np.random.normal(0,1,[dim2,rank])) C= tl.tensor(np.random.normal(0,1,[dim3,rank])) T_approx_old = tl.kruskal_to_tensor((np.ones(rank),[A,B,C])) I don't understand the np.ones(rank) argument in the method. What does it do? A: This version of kruskal_to_tensor is documented in the dev version of the API. The np.ones corresponds to the weight of the Kruskal tensor: a Kruskal tensor expresses a tensor as a weighted sum of rank one tensors (outer product of vectors, collected as the columns of the factor matrices). In your case, the weights of the sum are all ones and accumulated in this vector of ones. Note that you could normalize the factors of your Kruskal tensor and absorb their magnitude in theses weights.
{ "pile_set_name": "StackExchange" }
Q: Search and sort through dictionary in Python I need to sort and search through a dictionary. I know that dictionary cannot be sorted. But all I need to do search through it in a sorted format. The dictionary itself is not needed to be sorted. There are 2 values. A string, which is a key and associated with the key is an integer value. I need to get a sorted representation based on the integer. I can get that with OrderedDict. But instead of the whole dictionary I need to print just the top 50 values. And I need to extract some of the keys using RegEx. Say all the keys starting with 'a' and of 5 length. On a side note can someone tell me how to print in a good format in python? Like: {'secondly': 2, 'pardon': 6, 'saves': 1, 'knelt': 1} insdead of a single line. Thank you for your time. A: If you want to sort the dictionary based on the integer value you can do the following. d = {'secondly': 2, 'pardon': 6, 'saves': 1, 'knelt': 1} a = sorted(d.iteritems(), key=lambda x:x[1], reverse=True) The a will contain a list of tuples: [('pardon', 6), ('secondly', 2), ('saves', 1), ('knelt', 1)] Which you can limit to a top 50 by using a[:50] and then search through the keys, with youre search pattern.
{ "pile_set_name": "StackExchange" }
Q: PySpark: Replace values in ArrayType(String) I currently have the following code: def _join_intent_types(df): mappings = { 'PastNews': 'ContextualInformation', 'ContinuingNews': 'News', 'KnownAlready': 'OriginalEvent', 'SignificantEventChange': 'NewSubEvent', } return df.withColumn('Categories', posexplode('Categories').alias('i', 'val'))\ .when(col('val').isin(mappings), mappings[col('i')])\ .otherwise(col('val')) But I'm not sure my syntax is right. What I'm trying to do is operate on a column of lists such as: ['EmergingThreats', 'Factoid', 'KnownAlready'] and replace strings within that Array with the mappings present in the dictionary provided, ie. ['EmergingThreats', 'Factoid', 'OriginalEvent'] I've tried a number of approaches but can't seem to apply the transformation, any help would be appreciated. I understand this is possible with a UDF but I was worried how this would impact performance and scalability. UPDATE: I've provided a sample of the original table structure below, +------------------+-----------------------------------------------------------+ |postID |Categories | +------------------+-----------------------------------------------------------+ |266269932671606786|[EmergingThreats, Factoid, KnownAlready] | |266804609954234369|[Donations, ServiceAvailable, ContinuingNews] | |266250638852243457|[EmergingThreats, Factoid, ContinuingNews] | |266381928989589505|[EmergingThreats, MultimediaShare, Factoid, ContinuingNews]| |266223346520297472|[EmergingThreats, Factoid, KnownAlready] | +------------------+-----------------------------------------------------------+ And I'd like the code to replace strings in those arrays with their new mappings, provided they exist in the dictionary. If not, leave them as they are: +------------------+-------------------------------------------------+ |postID |Categories | +------------------+-------------------------------------------------+ |266269932671606786|[EmergingThreats, Factoid, OriginalEvent] | |266804609954234369|[Donations, ServiceAvailable, News] | |266250638852243457|[EmergingThreats, Factoid, News] | |266381928989589505|[EmergingThreats, MultimediaShare, Factoid, News]| |266223346520297472|[EmergingThreats, Factoid, OriginalEvent] | +------------------+-------------------------------------------------+ A: Using explode + collect_list is expensive. This is untested, but should work for Spark 2.4+: from pyspark.sql.functions import expr for k, v in mappings.items() df = df.withColumn( 'Categories', expr('transform(sequence(0,size(Categories)-1), x -> replace(Categories[x], {k}, {v}))'.format(k=k, v=v)) ) You can also convert the mappings into CASE/WHEN statement and then apply it to the SparkSQL transform function: sql_epxr = "transform(Categories, x -> CASE x {} ELSE x END)".format(" ".join("WHEN '{}' THEN '{}'".format(k,v) for k,v in mappings.items())) # this yields the following SQL expression: # transform(Categories, x -> # CASE x # WHEN 'PastNews' THEN 'ContextualInformation' # WHEN 'ContinuingNews' THEN 'News' # WHEN 'KnownAlready' THEN 'OriginalEvent' # WHEN 'SignificantEventChange' THEN 'NewSubEvent' # ELSE x # END # ) df.withColumn('Categories', expr(sql_epxr)).show(truncate=False) For older versions of spark, a udf may be preferred.
{ "pile_set_name": "StackExchange" }
Q: JAX-WS servlet filter exceptions I have a client/server application that communicates via SOAP. The server-side application is a Java EE app that exposes web services using JAX-WS. I have a servlet filter setup to perform certain checks before a service is invoked. This is all working pretty well, except for exception handling. If I throw an exception from the filter, it gets returned to the client as a generic server exception. I need to find a way to propagate a custom exception containing a specific message, so the client can display the message to the user. Any insight? A: A servlet filter isn't really the right tool if you want to send the exception in a SOAP response and I would consider using a JAX-WS handler for the verification of incoming messages instead (JAX-WS handlers are somehow to JAX-WS services what Filters are to Servlets). Frmo Working with Headers in JAX-WS SOAPHandlers: JAX-WS Handlers In addition to support for web services development, the JAX-WS framework (the latest Java programming language API for creating SOAP-based web services and web service consumers) also provides a handler framework. Handlers provide a means to inspect and manipulate incoming or outgoing SOAP messages (on both the client as well as server side). They act as powerful message interceptors that can perform an array of functions such as message transformation, content filtering, tracking, etc. In fact, handlers are often used in runtime environments to implement web service and SOAP specifications such as WS-Security, WS-ReliableMessaging, etc. JAX-WS handlers are similar to EJB interceptors or servlet filters. Handlers, like interceptors and filters, encourage developers to follow the chain of responsibility pattern. Resources Writing a Handler in JAX-WS (start here) Handler example using JAXWS 2.0 References Java API for XML-Based Web Services (JAX-WS) 2.0 specification APIs javax.xml.ws.handler.Handler javax.xml.ws.handler.LogicalHandler javax.xml.ws.handler.soap.SOAPHandler
{ "pile_set_name": "StackExchange" }
Q: Use char-codes in strings I'm working on a terminal program under Linux. I consider adding colorized output. The task is not really hard, so I succeeded with the following: [3]> (format t "~a[1;31mred text~a[0m" #\escape #\escape) red text ; this text is really red and bold in terminal ;-) NIL But the code is ugly: I don't know how to put char #\escape (decimal value 27) into a string in 'inline' fashion. For example C++ code from this thread: cout << "\033[1;31mbold red text\033[0m\n"; Here is #\Escape as \033 (octal). Is there something similar in Common Lisp? My effort naïf doesn't work as intended: [4]> (format t "#\escape1;31mred test#\escape[0m") #escape1;31mred test#escape[0m NIL A: You can type the characters manually… You don't have to do anything special to have the control characters (or other "unusual" characters) in your strings. You just need to be able to type them into the editor. How easy it will be will depend on your editor. In Emacs, and in at least some terminal emulators, you can press Ctrl-Q followed by another character to insert that character literally. Thus, you can press Ctrl-Q followed by Escape to insert a literal #\escape character. How it appears will depend on the terminal emulator or editor. In my terminal, the literal Escape character is displayed as ^[. Thus, I end up with: (format t "^[[1;31mhello^[[0!") ; ** ** ; result of C-Q Esc This gives me some red text, as in your example: …or use a library to make it easier! If you don't want your source to contain characters that might not be easily readable, you might look into something like Edi Weitz's CL-INTERPOL: CL-INTERPOL is a library for Common Lisp which modifies the reader so that you can have interpolation within strings similar to Perl or Unix Shell scripts. It also provides various ways to insert arbitrary characters into literal strings even if your editor/IDE doesn't support them. Here's an example: * (let ((a 42)) #?"foo: \xC4\N{Latin capital letter U with diaeresis}\nbar: ${a}") "foo: ÄÜ bar: 42" Using CL-INTERPOL, this becomes easy: * (interpol:enable-interpol-syntax) * (format t #?"\e[1;31mhello\e[0m!") hello! ; there's color here, honest! NIL
{ "pile_set_name": "StackExchange" }
Q: Disable "list" leaving only "add new" and "delete" I have a project that is using SonataMediaBundle, and I am working on the GalleryAdmin page. My goal is to only allow uploads of images, rather than allowing images and videos. I have set up sonata_media.yml so that inline uploads of new media only allow images. However, if there are existing Media records that contain video -- YouTube records, for instance -- the gallery allows selection of those video items alongside images. This is not the desired behavior. How do I change my GalleryAdmin (or other files) so that selection of existing Media records is not possible, and only fresh uploads are allowed? This would fix the problem. ==== Edit: To clarify, I basically want to remove the "List" button from my Media list view, leaving only "Add new" and "Delete." A: Check The available options are section here, you can disable any button. Edit: Just extends this and overwrite the formFields and there you need to hide list option for media field.
{ "pile_set_name": "StackExchange" }
Q: How to define and use resources in xaml so they can be used in C# Theoretically, I think that I can define Brushes and Colors etc. in an xaml file and assign that to a button.background in c#. But how do I do that? Where do I put my lineargradientbrush definition like this: <LinearGradientBrush x:Key="BlaBrush"> <GradientStop Offset="0" Color="Red"/> <GradientStop Offset="1" Color="Green"/> </LinearGradientBrush> Just putting it at various places in my window's xaml file results in various error messages :/ I found this question here on stackoverflow: How to use a defined brush resource in XAML, from C# which explains a part of it, but he seems to know where to do the Brush definition. I also tried adding the shinyblue.xaml wpf template to the app and added <ResourceDictionary Source="ShinyBlue.xaml"/> to the application.resources in app.xaml. This makes all my buttons blue instantly, but still, the "things" defined in shinyblue.xaml like NormalBrush is not accessible from C# - at least I don't know how. Marc A: Your xaml would look something like this: MainWindow.xaml <Window x:Class="BrushResource.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <LinearGradientBrush x:Key="BrushOne" StartPoint="0,0.5" EndPoint="1,0.5" Opacity="0.5"> <LinearGradientBrush.GradientStops> <GradientStopCollection> <GradientStop Color="Black" Offset="0" /> <GradientStop Color="Silver" Offset="1" /> </GradientStopCollection> </LinearGradientBrush.GradientStops> </LinearGradientBrush> <LinearGradientBrush x:Key="BrushTwo" StartPoint="0,0.5" EndPoint="1,0.5" Opacity="0.5"> <LinearGradientBrush.GradientStops> <GradientStopCollection> <GradientStop Color="Maroon" Offset="0" /> <GradientStop Color="Silver" Offset="1" /> </GradientStopCollection> </LinearGradientBrush.GradientStops> </LinearGradientBrush> </Window.Resources> <StackPanel> <Button Content="Button" Width="100" Click="myButton_Click"/> </StackPanel> To assign the value, you need to grab the gradient brush from the resources like this: MainWindow.xaml.cs private void myButton_Click(object sender, RoutedEventArgs e) { (sender as Button).Background = this.Resources["BrushOne"] as LinearGradientBrush; } A: Note that the existing answers talk about putting the resources in Window.Resources. If you want the resources to be available application-wide, you might consider putting them in App.xaml or better yet, create stand-alone resource dictionaries that can be included in your views and re-used elsewhere (including other projects) <UserControl.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="DefaultStyles.xaml"/> </ResourceDictionary.MergedDictionaries> <Style x:Key="my_style" /> </ResourceDictionary> </UserControl.Resources> A: Put them in the Resources collection of one of your elements in XAML: <Window ...> <Window.Resources> <LinearGradientBrush x:Key="BlaBrush"> <GradientStop Offset="0" Color="Red"/> <GradientStop Offset="1" Color="Green"/> </LinearGradientBrush> <!-- Other resources --> </Window.Resources> <!-- Contents of window --> </Window> Then get them in code by using FindResource var blaBrush = this.FindResource("BlaBrush") as LinearGradientBrush; See Resources Overview for more information.
{ "pile_set_name": "StackExchange" }
Q: Installing MinionPro in TeX Live 2011 I am having great difficulty to install the font MinionPro in TeX Live 2011. I followed all the steps in the README file on CTAN, but I get the following error when compiling the text: Process started: xelatex -interaction=nonstopmode "Teste8".tex kpathsea: Running mktexpk --mfmode / --bdpi 600 --mag 1+0/600 --dpi 600 MinionPro-ItLCDFJ.pfb mktexpk: don't know how to create bitmap font for MinionPro-ItLCDFJ.pfb. mktexpk: perhaps MinionPro-ItLCDFJ.pfb is missing from the map file. kpathsea: Appending font creation commands to missfont.log. ** WARNING ** Could not locate a virtual/physical font for TFM "MinionPro-It--lcdfj". ** WARNING ** >> This font is mapped to a physical font "MinionPro- ItLCDFJ.pfb". ** WARNING ** >> Please check if kpathsea library can find this font: MinionPro-ItLCDFJ.pfb ** ERROR ** Cannot proceed without .vf or "physical" font for PDF output... Output file removed. Process exited normally .pfb files were generated and copied to the correct directory. Also all related files are already located at TeX Live as MinionPro.map, etc... However, I noticed that files ending in LCDFJ can not be opened because they have 0 kb. It has something to do? Note: The file compiles normally with pdfLaTeX. I can not compile when using LaTeX ... which may be the problem? I need the file to be compiled with LaTeX, because I use a plugin that does not work with XeLaTeX, just with LaTeX. A: The problem is that MinionPro does something screwy with the dotlessj glyph. XeTeX chokes when it sees the weirdness, even though PDFTeX apparently ignored it. This was discussed before here, but there's no complete answer there. The salient points: If you must use the MinionPro package (or fontspec for text and MinionPro for math) then download the entire MinionPro sources and go through the procedure found here: ./scripts/makeall --nodotlessj ./scripts/generate-glyph-list.sh > scripts/glyph-list-2.030 ./scripts/makeall --nodotlessj --pack="`pwd`/scripts/glyph-list.2.030" You may also have to look through MinionPro.map for some entry with a ?, but I never had to do that. For future reference, in case you ever want to use Minion Pro with XeTeX then it's easiest to use fontspec and mathspec to get Minion Pro working. You could load the font like this: \usepackage[MnSymbol]{mathspec} \setmainfont[Numbers={Lining,Proportional}]{Minion Pro} \setmathsfont(Digits,Latin,Greek)[Numbers={Lining,Proportional}]{Minion Pro} If you need to use LuaTeX, you could approximate the same with unicode-math, like my answer here. But both of these solutions mess up spacing for math sequences like $(f)$.
{ "pile_set_name": "StackExchange" }
Q: Why can't I resize NTFS partition? I'm trying to resize my ntfs partition but can't do it in GParted... tried from HD and from LiveUSB... couldn't find a solution on the web, partition isn't mounted; I'm trying to divide it in two to install another Ubuntu version. I used Ubuntu 13.10 in both installed on HD and LiveUSB. ntfs-3g is installed; ntfsprogs can't be installed. A: As @psusi said I couldn't edit the partition because CHDISK was scheduled to run... then I just entered Windows and waited for it to finish, then partition was able to be resized by GParted. Then did reorganization as @oldfred stated. Package ntfs-3g substitutes ntfsprogs (which is an old package) Thank you for the help!! EDIT: I don't have Windows installed anymore and the general recommendation from the open source community is that you should not use Windows or any closed-source software. Thank you.
{ "pile_set_name": "StackExchange" }
Q: Div's hover tilt I have 2 div, i'm trying to hide the first, and display the second using the hover, but I can't see the second div, because the first one go in a cycle of display none and block. That's the snippet http://codepen.io/IvanPalma/pen/qbOLJp?editors=110 .item-inner { background: red; width: 200px; height: 200px; z-index: 99; } .item-inner:hover { display: none; } .item-inner-hover { display:none; } .item-inner.hover:hover { display: block; height: 200px; width: 200px; background-color: blue; } <div class="item-inner"></div> <div class="item-inner-hover"></div> A: You could use opacity instead of display with the divs stacked on top of each other. .item-inner { background: red; width: 200px; height: 200px; z-index: 99; opacity:1; position: absolute; top: 0; left: 0; } .item-inner:hover { opacity: 0; } .item-inner-hover { height: 200px; width: 200px; background-color: blue; position: absolute; top: 0; left: 0; }
{ "pile_set_name": "StackExchange" }
Q: Why is Tom Hanks firing at the tank in Saving Pvt. Ryan? Towards the end of the movie Saving Pvt. Ryan, most of the soldiers led by Capt. Miller (Hanks) are dead and he himself too is fatally injured. It is obvious that they have been overwhelmed by the enemy forces and he is going to die. There is a scene where he is sitting with his back supported by a truck and a Tiger tank is approaching. If my memory serves me right, they have already fired quite a few bazookas at it to no avail. At that moment Hanks takes out his .45 pistol and starts firing at the tank. Had he gone delirious because of his injuries or the war at large? Or was it his resilience in the final moments? Why would a person fire bullets at a tank?!! A: It was definitely the last resort of a desperate man. Broken and dazed, his company in tatters, Miller doggedly pulls out his pistol and fires at the tank in a futile but defiant gesture. His mission was over, Ryan had been found and given the message, Miller's trusted sergeant lay dead at his side, as far as Miller was concerned this was the end of the road. So, in answer to your question, it was a combination of resilience, defiance and resignation that caused Miller to unload his pistol at the approaching tank.
{ "pile_set_name": "StackExchange" }
Q: Rename Array Keys I need to change this array's keys to 0-5, why isn't this working? $arr = array(); while(count($arr) < 6){ $arr[] = rand(1,53); $arr = array_unique($arr); } asort($arr); $i = 0; foreach($arr as $key => $value){ //echo $i; $key = $i; $i++; } print '<pre>'; print_r($arr); Thank you A: Because foreach creates a copy of the array entry key and value in $key and $value. When you do $key = $i; all you're doing is updating the copy, not the original array. Use array_values($arr) instead, or use sort() instead of asort()
{ "pile_set_name": "StackExchange" }
Q: Is there an interpreter for C? I was wondering if there is something like an interpreter for C. That is, in a Linux terminal I can type in "python" and then code in that interpreter. (I'm not sure interpreter the right word). This is really helpful for testing different things out and I'm curious if something similar exists for C. Though I doubt it. The only thing I can think of that would do it would be the C shell... A: There are many - if you narrow down the scope of your question we might be able to suggest some specific to your needs. A notable interpreter is "Ch: A C/C++ Interpreter for Script Computing" detailed in Dr. Dobbs: Ch is a complete C interpreter that supports all language features and standard libraries of the ISO C90 Standard, but extends C with many high-level features such as string type and computational arrays as first-class objects. Ch standard is freeware but not open source. Only Ch professional has the plotting capabilities and other features one might want. I've never looked at this before, but having a c interpreter on hand sounds very useful, and something I will likely add to my toolset. Thanks for the question! Edit: Just found out that one of my favorite compilers, TCC, will execute C scripts: It also handles C script files (just add the shebang line "#!/usr/local/bin/tcc -run" to the first line of your C source code file on Linux to have it executed directly. TCC can read C source code from standard input when '-' is used in place of 'infile'. Example: echo 'main(){puts("hello");}' | tcc -run - A: picoc - A very small C interpreter PicoC is a very small C interpreter for scripting. It was originally written as the script language for a UAV's on-board flight system. It's also very suitable for other robotic, embedded and non-embedded applications. A: the ROOT project provides a very functional C and C++ interpreter called Cint. I'm quite fond of it. It takes a little getting used to interpretively, though. TCC is a very good choice as well, but i'm not able to vouch for its REPL
{ "pile_set_name": "StackExchange" }
Q: BASH; using find and -exec to remove .pyc files Using the command line in Ubuntu 16.04.2 LTS. I'm getting towards the end of Zed Shaw's LPTHW, and on the video to ex46.py he exercises the following bash command to find and remove all .pyc byte code files: find . -name "*.pyc" -exec rm {} On the video this successfully removes all of Zed Shaw's .pyc files. However, upon typing in the exact same command I get the following error: find: missing argument to `-exec' I understand that there are many ways to delete .pyc files, however, since I'm following along with Zed Shaw I'd like to know how to do it using find and -exec. What am I doing wrong? A: you need to terminate the -exec command with \; find . -name "*.pyc" -exec rm {} \; have a look at find -exec in the man page. as mentioned in the comments by Gordon Davisson it may be more efficient to terminate the command with + as rm is then invoked fewer times: find . -name "*.pyc" -exec rm {} + A: You could leverage using -delete over -exec rm as the former does not spawn a new process for each of the file instance to delete. Also you could chip in the -type f option to apply the operation for files only. find . -type f -name "*.pyc" -delete
{ "pile_set_name": "StackExchange" }
Q: How do I add options to a DropDownList using jQuery (ordered)? This question is similar to this one How do I add options to a DropDownList using jQuery? but I would like to add it in an ordered fashion. The example in the other question just adds it to the end of the list. The code is as follows: var myOptions = { 1: "Test" 2: "Another" }; $.each(myOptions, function(val, text) { $('#Projects').append( $('<option></option').val(val).html(text) ); }); Suppose the list already contains 3 items: "Blah", "Foo" and "Zebra". I'd like to be able to add the two new options ("Test" and "Another") to the dropdown so it's ordered ("Another", "Blah", "Foo", "Test" and "Zebra") using jQuery. Any help is much appreciated!!! A: Give this a go: // Sort Function function sortAlpha(a,b) { if(a.name > b.name) { return 1; } else if(a.name < b.name) { return -1; } return 0; } // Options you want to add var myOptions = [ {id:1, name:"Test"}, {id:2, name:"Another" } ]; // Create array from existing options and merge $.merge(myOptions, $.map( $('#Projects').find('option'), function(n){ return { id:n.value, name:n.innerHTML}; }) ); // Sort all options using above sort function myOptions.sort(sortAlpha); // Clear the <select> of existing options $('#Projects').empty(); // Add the options to the <select> $.each(myOptions, function() { $('#Projects').append( $('<option></option').val(this.id).html(this.name) ); });
{ "pile_set_name": "StackExchange" }
Q: How to set wire format on a property without changing type definition? This type is defined in an assembly where I cannot add a reference to protobuf-net: [StructLayout(LayoutKind.Sequential)] [XmlType] // for XML or protobuf-net serialization public struct PointI { public PointI(int x, int y) { X = x; Y = y; } [XmlElement(Order = 1)] public int X; [XmlElement(Order = 2)] public int Y; ... } How can I use ProtoBuf.Meta.RuntimeTypeModel.Default to specify zig-zag storage to optimize output size? A: var metaType = RuntimeTypeModel.Default.Add(typeof(PointI), true); metaType[1].DataFormat = metaType[2].DataFormat = ProtoBuf.DataFormat.ZigZag; That do ? In other news: mutable structs... bleugh...
{ "pile_set_name": "StackExchange" }
Q: Web slices not loading in IE8 I'm trying to add a webslice to a site i admin, but for some reason i cant get any webslices at all to work in ie8. I have tried 2 different machine at home and one at work but i hit the same problem, i just get an 'ie cannot display this page' error. If i hit the diagnose problem button i get a script debug error: Line: 264 Error: Object doesn't support this property or method I get exactly the same error on every different slice, even down to the line number. Anyone any ideas? Edit - By a webslice i am talking about new functionality that came with ie that lets you ad part of a webpage (say the div containing news) to your links bar. The when you click on the slice it expands to show you the content of the slice. More info at http://msdn.microsoft.com/en-us/library/cc304073(VS.85).aspx">http://msdn.microsoft.com/en-us/library/cc304073(VS.85).aspx Cheers Luke A: I have finally managed to find the answer! There seems to be a bug with the full version of ie and google gears. If you disable the gears ie add on they work again! - http://support.microsoft.com/kb/969213
{ "pile_set_name": "StackExchange" }
Q: Oracle hierarchical query question (start with ... connect by ... ) From the Oracle documentation: To find the children of a parent row, Oracle evaluates the PRIOR expression of the CONNECT BY condition for the parent row and the other expression for each row in the table. Rows for which the condition is true are the children of the parent. The CONNECT BY condition can contain other conditions to further filter the rows selected by the query. When Oracle select child node for a parent node, it selects from all rows except the current row right? Can a row appear multi times in the result set (I mean a row is both the child node of row A and row B)? A: There would have to be data indicating that the row is both a child of row A and a child of row B. This can be done, but does not seem like it would be typical. Think of an employee. Most employees only have one direct managers. In a simple design an employee could have two managers, but it would require multiple employee records. For example: --drop table e; create table e (id number, name varchar2(100), manager number); insert into e values (1,'Amos',null); insert into e values (2,'Bob',1); insert into e values (3,'Cindy',1); insert into e values (4,'Dave',2); insert into e values (4,'Dave',3); select substr(name,1,7) name, substr(prior name,1,7) Manager from e start with id=1 connect by prior id=manager order by name;
{ "pile_set_name": "StackExchange" }
Q: MySQL query to search for all records against field with comma separated values I have 2 sql tables Table name: agents contains a records with a coloumn AgentID Table named: vacancies is the one with the data ans is being dislayed. Table named vacancies has vacancies.Agents which contains values simmilar to this VacanyID Company position CTC Candidates Agents ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FBVAC001 | HDFC | Branch Manager | 4.5 | FBCAN001,FBCAN002| Agent3,Agent4 FBVAC003 | TBNH | Branch Manager | 4.5 | FBCAN004,FBCAN005| Agent2,Agent4 FBVAC005 | MMNT | Branch Manager | 4.5 | FBCAN008,FBCAN006| Agent3 FBVAC008 | LCFC | Branch Manager | 4.5 | FBCAN009,FBCAN023| Agent3,Agent4 FBVAC008 | KOTC | Branch Manager | 4.5 | FBCAN009,FBCAN023| Agent5,Agent4 I want to run a query that will return only those records that contain the value that corresponds to agents.AgentID from table name agents. This is the query so far but all it returs are those records that do not have more than one value in vacancies.Agents for example if the value being searched for is Agent3 it should return rows1,3 and 4 instead it only returns row 3. SELECT vacancies.VacancyID, vacancies.Company, vacancies.`Position`, vacancies.CTC, vacancies.Candidates, vacancies.Agents FROM vacancies , agents WHERE (FIND_IN_SET(vacancies.Agents,agents.AgentID) <> 0) How can this be resolved? A: I believe you have your parameters backwards in FIND_IN_SET. The set should come second FIND_IN_SET(agents.AgentID, vacancies.Agents) More Info: http://www.bitbybit.dk/carsten/blog/?p=162 Also, if you are wanting to see only a specific agent, you need to filter for that as well, otherwise you're getting every possible combination of agent and matching vacancies (hence the duplicate rows): AND Agents.AgentID = 'Agent3' Demo: http://www.sqlfiddle.com/#!2/b4dcb/3
{ "pile_set_name": "StackExchange" }
Q: Cannot update filter controls, PivotTables, PivotCharts, or cube functions I have a PivotTable connection to a SSAS tabular model. After I saved it and reopened it, the PivotTable became completely unresponsive. What I mean by unresponsive is that I can't Refresh data, I can't add remove columns or rows or values, I can't even change properties on the data source connection, I can't even change the connection to something new. I never get a message or progress bar or anything. I can also still edit other cells that aren't part of the Pivot Table. If I copy and paste the PivotTable into a new workbook then everything works again. But once I save it, and reopen it the same problem occurs. I have lots of other workbooks with PivotTables that connect to the same model without any problem. Finally I got a clue. I deleted a slicer and received the following message: Cannot update filter controls, PivotTables, PivotCharts, or cube functions. Reasons for this can include: * The connection to the data source failed. * The worksheet is protected * A PivotTable cannot expand because it would overlap existing cell content It's definitely not the third reason, and I didn't place any protections on the worksheet. The fact that I can not edit the connection might mean it's related to the first item since I can't edit the connection at all. More likely this is just a generic message. Has anybody encountered this before? If not, what's a good way to debug this? UPDATE This seems to be happening with every new Workbook with connected PivotTable that I create! But if I edit and save older ones I don't have a problem. A: To fix this problem I needed to go Excel Options > Trust Center > Trust Center Settings > External Content. In External Content I had Security settings for Data Connections and set to Disable all Data Connections. Changing that to Prompt user about Data Connections fixed my problem. I don't remember ever setting that to disable, and I used to get a prompt when I opened Worksheets from the network. So it's weird that was changed. It would be nice to get an error message indicated this was the problem.
{ "pile_set_name": "StackExchange" }
Q: Any idea how to download a small part of the chain for testing purposes? I am experimenting with Python and Rust libraries on my laptop. I don't actually want to get a node going on it and download the full chain; I just need some blocks to play with. I want to keep my question general enough though; what is the easiest way for someone to download just a small portion of the blockchain, given specific beginning and end points in block numbers? Are there any libraries that would do that either in Python, JS, or Rust (or any other languages, so my question applies to all developers)? A: If you know what hashes of the blocks you want, you can use the P2P protocol to connect to a node and request those specific blocks. However, you cannot just do that with block heights as the block's height is not a unique identifier for the block. There are many libraries available that can speak the P2P protocol. The python-bitcoinlib can be used to send the P2P messages necessary for doing this.
{ "pile_set_name": "StackExchange" }
Q: Use Higher api level featurers in the lower api level devices I have developed my application by using sdk version 10.In lower version doesn't have the features which is available in the higher version's.Is there any api is available to use the higher level api features in the lower api level devices. Note: For example we unable to get the camera count in the api level 8, but we can get the details in the api level 9.If we try to use that feature application shows the exception. A: That is not possible you need to implment that, or use some compatibility pack to get the functionallity. But note that not everything is possible to emulate. E.g. the Base64 classes to implement is easy, but it is impossible to add the NFC functionallity to older releases because the needed hardware is missing. You can simply check the actual android version and build a switch so you won't call any functions that are not aviable to that device. That is possible with the constant android.os.Build.VERSION.
{ "pile_set_name": "StackExchange" }
Q: VM error: revert.The called function should be payable if you send value and the value you send should be less than your current balance There is already a similar question, but it doesn't help me. So I ask this question again and expect something useful information. Two contracts named AccessControl.sol and Judge.sol. I've removed all the extraneous code, leaving only the wrong functions and get same error when call it. First I deploy Judge contract and get its contract address. And then I deploy AccessControl contract, passed Judge contract address. Finally I call emitError function in AccessControl.sol and see the revert error transact to AccessControl.emitError errored: VM error: revert. revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information. I have no idea about why it happened. Here is the simplified code。 AccessControl.sol pragma solidity >=0.4.22 <0.6.0; contract AccessControl{ address public owner; Judge public jc; constructor(address _jc) public { owner = msg.sender; jc = Judge(_jc); } function emitError(address subject) public returns (uint penalty) { penalty = jc.misbehaviorJudge(subject, owner, "data", "read", "Too frequent access!", now); } } contract Judge { function misbehaviorJudge(address _subject, address _object, string memory _resource, string memory _action, string memory _misbehavior, uint _time) public returns (uint); } Judge.sol pragma solidity >=0.4.22 <0.6.0; contract Judge { struct Misbehavior{ address subject; //subject who performed the misbehavior address device; string resource; string action; //action (e.g., "read","write","execute") of the misbehavior string misbehavior; uint time; //block timestamp of the Misbehavior ocured uint penalty; //penalty (number of minitues blocked) } mapping (address => Misbehavior[]) public MisbehaviorList; function misbeaviorJudge( address _subject, address _device, string memory _resource, string memory _action, string memory _misbehavior, uint _time) public returns (uint penalty) { penalty = MisbehaviorList[_subject].length; MisbehaviorList[_subject].push(Misbehavior(_subject, _device, _resource, _action, _misbehavior, _time, penalty)); } function getLatestMisbehavior(address _requester) public view returns (address _subject, address _device, string memory _resource, string memory _action, string memory _misbehavior, uint _time) { uint latest = MisbehaviorList[_requester].length - 1; _subject = MisbehaviorList[_requester][latest].subject; _device = MisbehaviorList[_requester][latest].device; _resource = MisbehaviorList[_requester][latest].resource; _action = MisbehaviorList[_requester][latest].action; _misbehavior = MisbehaviorList[_requester][latest].misbehavior; _time = MisbehaviorList[_requester][latest].time; } } A: You've declared function misbehaviorJudge. But you've implemented function misbeaviorJudge. So the way I see it, you are trying to invoke an unimplemented function. A couple of ways for you to avoid a similar issue next time (more precisely, convert it from a hard-to-investigate runtime problem into an easy-to-investigate compilation problem): Option #1 - if you don't need to call function misbehaviorJudge inside contract Judge: File IJudge.sol: interface IJudge { function misbehaviorJudge(...) external returns (uint); File Judge.sol: import "./IJudge.sol"; contract Judge is IJudge { ... } Option #2 - if you do need to call function misbehaviorJudge inside contract Judge: File IJudge.sol: contract IJudge { function misbehaviorJudge(...) public returns (uint); File Judge.sol: import "./IJudge.sol"; contract Judge is IJudge { ... } Then (for both options), in file AccessControl.sol, simply use IJudge instead of Judge: import "./IJudge.sol"; contract AccessControl { IJudge public jc; ... }
{ "pile_set_name": "StackExchange" }
Q: postgresql insert timestamp error with python I use psycopg2 for postgresql. Here is my snippet: a = "INSERT INTO tweets (Time) VALUES (%s);" % (datetime.now(),) cursor.execute(a) this won't work and gives me an error: ProgrammingError: syntax error at or near "20" LINE 1: INSERT INTO tweets (Time) VALUES (2016-10-03 20:14:49.065092... However, if I run this way: cursor.execute("INSERT INTO tweets (Time) VALUES (%s);", (datetime.now(),)) it works. I want to know what is the difference between these two expressions, and what is wrong with the first one. Can I do this function use the first structure? A: If you check the first query, it states INSERT INTO tweets (Time) VALUES (2016-10-03 20:14:49.065092..., that means, it tries to use unquoted value as a time and this won't work. If you really want to use your first approach, you have to quote the value: a = "INSERT INTO tweets (Time) VALUES ('%s');" % (datetime.now(),) cursor.execute(a) I'd suggest you to use the second approach, where client library handles all quotes and usually prevents a lot of possible problems like SQL injection.
{ "pile_set_name": "StackExchange" }
Q: c programming regarding arrays and minimum? Build a program which reads from the user an array with n elements and finds the element with the smallest value.Then the program finds the number of the elements which have an equal value with this minimum.The found element with the smallest value along with the number of the elements which have an equal value with the minimum of the array should be displayed on screen.. I wrote this code : #include <stdio.h> int main() { int n = 1, min = 0, count = 0; int number[n]; printf("Enter the size of array you want"); scanf("%i", &n); int x; for (x = 0; x < n; x++) { int num; printf("\nEnter a Integer"); scanf("%i", &num); number[x] = num; if (number[x] < min) min = number[x]; } int i; for (i = 0; i < n; i++) { if (min = number[i]) count++; } printf("%s%i", "\nThe smallest Integer you entered was ", min); printf("%s%i", "\nNumber of times you entered this Integer: ", count); return 0; } But the problem is that when I run this,and I add the integers,it doesnt find the smallest value and how time its repeated correctly! Where am I wrong? A: Assuming your compiler has support for variable length arrays, you need to re-order the calls int number[n]; scanf("%i", &n); so that you know the value for n before declaring the array scanf("%i", &n); int number[n]; After that, you should initialise min to a larger value to avoid ignoring all positive values int min = INT_MAX; (You'll need to include <limits.h> for the definition of INT_MAX) Finally, if (min = number[i]) assigns number[i] to min. Use == to test for equality. Your compiler should have warned you about "assignment in conditional statement" for this last point. If it didn't, make sure you have enabled warnings (-Wall with gcc, /W4 with MSVC) A: you are checking array element <0 in line: if (number[x] < min/*as u specified min =0 before*/),... so the minimum is set to be zero and there is no replacement actually happening.. The full solution: #include <stdio.h> int main() { int n = 1, min = 0, count = 0; int number[n]; printf("Enter the size of array you want"); scanf("%i", &n); int x,y; for (y = 0; y < n; y++) { printf("\nEnter a Integer"); scanf("%i", &number[y]); } min=number[0]; for (x = 0; x < n; x++) { if (number[x] < min) min = number[x]; } int i; for (i = 0; i < n; i++) { if (min == number[i]) count++; } printf("%s%i", "\nThe smallest Integer you entered was ", min); printf("%s%i", "\nNumber of times you entered this Integer: ", count); return 0; }
{ "pile_set_name": "StackExchange" }
Q: Решение СЛАУ методом Гаусса по прямому и обратному ходам Здравствуйте, у меня такая проблема. Мне нужно написать программу, которая решает СЛАУ методом Гаусса. Программа у меня работает, но не все написано, я не знаю, что там надо дописать. Программа должна работать по прямому ходу (приведение расширенной матрицы до треугольного вида) и по обратному ходу (нахождение неизвестных). Помогите, пожалуйста. Текст программы: #include <stdio.h> #include <conio.h> #include <math.h> #define N 50 void glavelem(int k, double mas[][N + 1], int n, int otv[]); int main(void) { double mas[N][N + 1]; double x[N]; //корни системы int otv[N]; //отвечает за порядок корней int i, j, k, n; //ввод данных //clrscr(); do { printf("введите число уравнений сисемы: "); scanf("%d", &n); if (N < n) printf("слишком большое число уравнений, повторите ввод\n"); } while (N < n); printf("введите систему:n"); for (i = 0; i < n; i++) for (j = 0; j < n + 1; j++) scanf("%lf", &mas[i][j]); //вывод введенной системы //clrscr(); printf("система:n"); for (i = 0; i < n; i++) { for (j = 0; j < n + 1; j++) printf("%7.2f ", mas[i][j]); printf("n"); } //сначало все корни по порядку for (i = 0; i < n + 1; i++) otv[i] = i; //прямой ход метода Гаусса for (k = 0; k < n; k++) { glavelem(k, mas, n, otv); if (fabs(mas[k][k]) < 0.0001) { printf("система не имеет единственного решения"); return (0); } for (j = n; j >= k; j--) mas[k][j] /= mas[k][k]; for (i = k + 1; i < n; i++) for (j = n; j >= k; j--) mas[i][j] -= mas[k][j] * mas[i][k]; } //обратных ход for (i = 0; i < n; i++) x[i] = mas[i][n]; for (i = n - 2; i >= 0; i--) for (j = i + 1; j < n; j++) x[i] -= x[j] * mas[i][j]; //вывод результата printf("Îòâåò:n"); for (i = 0; i < n; i++) for (j = 0; j < n; j++) if (i == otv[j]) { //расставляем корни по порядку printf("%fn", x[j]); break; } return (0); } //---------------------------------------------- // описание функции //---------------------------------------------- void glavelem(int k, double mas[][N + 1], int n, int otv[]) { int i, j, i_max = k, j_max = k; double temp; //ищем максимальный по модулю элемент for (i = k; i < n; i++) for (j = k; j < n; j++) if (fabs(mas[i_max][j_max]) < fabs(mas[i][j])) { i_max = i; j_max = j; } //переставляем строки for (j = k; j < n + 1; j++) { temp = mas[k][j]; mas[k][j] = mas[i_max][j]; mas[i_max][j] = temp; } //переставляем столбцы for (i = 0; i < n; i++) { temp = mas[i][k]; mas[i][k] = mas[i][j_max]; mas[i][j_max] = temp; } //учитываем изменение порядка корней i = otv[k]; otv[k] = otv[j_max]; otv[j_max] = i; getch(); } A: Вполне достаточно искать главную строку с максимальным по модулю диагональным элементом, и где-то я читал, что достаточно найти ее ОДИН РАЗ. Было бы полезно во время прямого хода заодно вычислять детерминант, который равен произведению диагональных элементов на каждой итерации. Размеры матрицы следовало бы назначать динамически: во-первых, для экономии памяти; во-вторых, для красоты слога. Строки следует переставлять не поэлементно, а адресами. Не следует пользоваться глобальными переменными для переменных цикла. Запутаетесь и собьетесь. Здесь, на форуме, были тому примеры и, именно, с методом Гаусса. Как у Вас написан обратный ход? я не понял, по правде говоря: for(int i = line - 1; i >= 0; i--)//Начало обратного хода { double s = 0.0; for(int j = line - 1; j > i; j--) s += r[j] * temp[i][j]; r[i] = temp[i][line] - s; }//Конец обратного хода A: У вас в конце функции glavelem стоит getch(). т.е. при каждой итерации программа ждет нажатия любой клавиши. Это сделано видимо для отладки. Уберите этот вызов из функции. Можете поставить в конец main перед строчкой return(0)
{ "pile_set_name": "StackExchange" }
Q: Search child element in ET I'm trying to search an XML file. I need to check if the 'localteam' name matches my query (e.g 'Team A') If a match is found check the 'awayteam' name matches my second condition (e.g 'Team B'), the elemt of which is below the 'localteam' within the same element If 'awayteam' matches my query get the id of the parent (in 'match') and exit the search. I can get to the localteam element but I'm not sure how to then search for the awayteam and also go 'up' a level to get the id... I've tried using child.iter() and child.find('awayteam'), but neither has worked.. Thus far I have.. for child in root.iter('localteam'): gs_name = child.get('name') if gs_name == 'Team A': print child.tag, child.attrib for step_child in child.iter(): print step_child.tag, step_child.attrib gs_name = child.get('name') XML <scores sport="sports"> <category name="NAME" id="1419" file_group="USA"> <match date="21.07.2013" time="04:00" status="Finished" id="56456456"> <localteam name="Team A" /> <random name="yyy" /> <awayteam name="Team B" /> <random name="xxx" /> </match> A: Search for match elements instead: for match in root.iter("match"): if (match.find("localteam").get("name") == "Team A" and match.find("awayteam").get("name") == "Team B"): print match.get("id") break The above will raise AttributeErrors if the find calls don't find anything, so you may want to add some additional checks or error handling; e.g. for match in root.iter("match"): localteam = match.find("localteam") awayteam = match.find("awayteam") if localteam is not None and awayteam is not None and ...
{ "pile_set_name": "StackExchange" }
Q: Tableless model with ActiveRecord associations in Rails 3.2 My application configuration includes some values which need to be used in AR relationships. I'm aware this is an odd and potentially criminal thing to attempt, but I need to maintain the configuration as a textfile, and I honestly think I have a good case for a tableless model. Unfortunately I'm having trouble convincing AR (Rails 3.2) not to look for the table. My tableless model: class Tableless < ActiveRecord::Base def self.table_name self.name.tableize end def self.columns @columns ||= []; end def self.column(name, sql_type = nil, default = nil, null = true) columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null) end def self.columns_hash @columns_hash ||= Hash[columns.map { |column| [column.name, column] }] end def self.column_names @column_names ||= columns.map { |column| column.name } end def self.column_defaults @column_defaults ||= columns.map { |column| [column.name, nil] }.inject({}) { |m, e| m[e[0]] = e[1]; m } end def self.descends_from_active_record? return true end def persisted? return false end def save( opts = {} ) options = { :validate => true }.merge(opts) options[:validate] ? valid? : true end end This is extended by the actual model: class Stuff < Tableless has_many :stuff_things has_many :things, :through => :stuff_things column :id, :integer column :name, :string column :value, :string def initialize(attributes = {}) attributes.each do |name, value| send("#{name}=", value) end end end This is all based on code found here on SO and elsewhere, but alas, I get SQLException: no such table: stuffs: Any clues any one? A: For Rails >= 3.2 there is the activerecord-tableless gem. Its a gem to create tableless ActiveRecord models, so it has support for validations, associations, types. When you are using the recommended way (using ActiveModel opposed to ActiveRecord) to do it in Rails 3.x there is no support for association nor types.
{ "pile_set_name": "StackExchange" }
Q: QTcpSocket to QTcpSocket in same object I am attempting to fake a transfer between two QTcpSockets that happen to be in the same class (which is a googletest fixture). The focus of this is to see if I can send multiple messages between the two and properly extract them again. However, it seems that the two sockets won't connect. Most of the posts I've seen that relate to this don't come up with a working answer, and being as this is definitely not the intended means of use, I'm not sure that there is a simple one. What I have for setting up the connection: class TTest : public ::testing::Test, public QObject { //Q_OBJECT protected: QTcpServer qserv; QTcpSocket qtcpsock1; //send QTcpSocket *qtcpsock2; //rcv TTest() : qserv(this), qtcpsock1(this) { while (!qserv.isListening()) { qserv.listen(); } qtcpsock1.connectToHost(QHostAddress::LocalHost, qserv.serverPort()); qtcpsock2 = qserv.nextPendingConnection(); qtcpsock1.waitForConnected(); if (!qtcpsock2) std::cout << "socket 2 not initialized\n"; qserv.close(); } } Signals/slots currently not in use. A: The problem with this is that the event polling loop of the application will not run, so no events will be handled and your function calls will simply not work without it. In short, the waitForConnected() call will wait for an event that never happens. The natural solution with Qt is of course to use signals and slots, and let the normal application event loop run. On a slightly related note: If you want internal communication within the same process consider something other than (heavy and complex) TCP sockets. Simple message queues? Anonymous pipes? Plain strings or arrays?
{ "pile_set_name": "StackExchange" }
Q: Accessing Files From Runnable Jar Quick disclaimer: I am very new to java and I know that this question has been answered in other threads, but I can't understand the answers there so I'm really hoping for a very simple/understandable explanation please. Anyway, my problem is that I am using Eclipse to make a program which uses text files and pictures and while it works through Eclipse, if I try to export it into a runnable jar, I cannot access my resources anymore. Currently my directory structure when I run things from Eclipse is: Desktop --> workspace --> QuizProgram --> bin src Questions.txt right.png and I access my image and text files through: BufferedReader br = new BufferedReader(new FileReader("Questions.txt")); BufferedImage right = ImageIO.read(new File("Right.png")); If anyone could please I give me a step-by-step explanation of where to move my files/change my code I would appreciate it very much. I've looked through many other threads and Classpath/ClassLoader are really confusing me. I've tried some this.getClass().getResource("File.txt"); stuff also but nothing seems to work. Please help, I have a finished program and this last thing is really frustrating, thanks! Edit 1: So I tried what user2933977 suggested and changed getResource to getResourceAsStream and everything worked wonderfully! Thanks a lot user2933977 for your help. Side note: Yeah, yeah I get that this is a duplicate but I think that how you phrase a question and interact with responders helps a lot anyway. Take it easy, I got it to work. A: You're not quite showing enough code but to use getResource(), your file would need to live in the same directory as where your .class files live. For example, you may have something that looks like: Desktop --> workspace --> QuizProgram --> bin --> QuizProgram --> YourClass.class src --> QuizProgram --> YourClass.java Questions.txt right.png I'm guessing a bit here but that is the default "Java Project" in Eclipse. So move your Questions.txt to the same directory as your .java file and Eclipse will move it for you to the classes directory: Desktop --> workspace --> QuizProgram --> bin --> QuizProgram --> YourClass.class Questions.txt <--- Eclipse moves this for you src --> QuizProgram --> YourClass.java Questions.txt right.png And you'll be able to use the getResource() method as you have it written. Having said that, you'll eventually get to a build system that will do much of this for you but this should get you started.
{ "pile_set_name": "StackExchange" }
Q: Linear Regression Apache Spark with Scala not even straight line I want to apologize for my really stupid question but I have a problem with my Linear Regression. I`m struggling with that a lot. Could you please help me. This is my main code. I`m currently using some external library to plot the data. import com.fundtrml.config.ConfigSetUp import org.apache.spark.ml.feature.LabeledPoint import org.apache.spark.ml.linalg.Vectors import org.apache.spark.ml.regression.LinearRegression import org.apache.spark.sql.SparkSession object SimpleLinearRegression { def main(args: Array[String]): Unit = { ConfigSetUp.HadoopBinariesConfig(); val ss = SparkSession.builder().appName("DataSet Test") .master("local[*]").getOrCreate() import ss.implicits._ var listOfData = List(40, 41, 45, 43, 42, 60, 61, 59, 50, 49, 47, 39, 41, 37, 36, 34, 33, 37) val data = listOfData //(1 to 21 by 1) // create a collection of Doubles .map(n => (n, n)) // make it pairs .map { case (label, features) => LabeledPoint(label, Vectors.dense(features)) } // create labeled points of dense vectors .toDF // make it a DataFrame var splittedData = data.randomSplit(Array(0.6,0.4)) var trainingData = splittedData(0) var testSetData = splittedData(1) trainingData.show() val lr = new LinearRegression() .setMaxIter(10) .setRegParam(0.3) .setElasticNetParam(0.8) //train val model = lr.fit(trainingData) println(s"model.intercept: ${model.intercept}") println(s"model.coefficients : ${model.coefficients}") // Summarize the model over the training set and print out some metrics val trainingSummary = model.summary println(s"numIterations: ${trainingSummary.totalIterations}") println(s"objectiveHistory: [${trainingSummary.objectiveHistory.mkString(",")}]") trainingSummary.residuals.show() println(s"RMSE: ${trainingSummary.rootMeanSquaredError}") println(s"r2: ${trainingSummary.r2}") val predictions = model.transform(testSetData) predictions.show() //Display the data import com.quantifind.charts.Highcharts._ regression(listOfData) //using this external library with embeded functionality about regression var currentPredictions = predictions.select("prediction").rdd.map(r => r(0)).collect.toList println(currentPredictions) // regression(currentPredictions.map(_.toString.toDouble)) } } My training set is as follows, label column - value, which should be predicted, features- value, which should be used to make a prediction: +-----+--------+ |label|features| +-----+--------+ | 43.0| [43.0]| | 45.0| [45.0]| | 42.0| [42.0]| | 60.0| [60.0]| | 50.0| [50.0]| | 59.0| [59.0]| | 61.0| [61.0]| | 47.0| [47.0]| | 49.0| [49.0]| | 41.0| [41.0]| | 34.0| [34.0]| +-----+--------+ Evaluating the regression model, I`m getting the following data: model.intercept: 1.7363839862169372 model.coefficients : [0.9640297102666925] numIterations: 3 objectiveHistory: [0.5,0.406233822167566,0.031956224821402285] RMSE: 0.29784178261548705 r2: 0.9987061382565019 --> Extremely High Close to 1 At the end I`m getting the following predictions: +-----+--------+------------------+ |label|features| prediction| +-----+--------+------------------+ | 40.0| [40.0]| 40.29757239688463| | 41.0| [41.0]|41.261602107151326| | 39.0| [39.0]|39.333542686617946| | 36.0| [36.0]|36.441453555817866| | 37.0| [37.0]| 37.40548326608456| | 33.0| [33.0]| 33.54936442501779| | 37.0| [37.0]| 37.40548326608456| +-----+--------+------------------+ It is really easy to see that the predictions are not on the same line. It`s impossible to be located on the straight line. This is whole data set, plotted using the Scala Library- WISP Predicted data Expected result, but done with the WISP A: What you've plotted there seem to be the label on the Y axis and the index in the list on the X axis, not the feature value on the X axis. The predictions are indeed on the same line when plotted feature-vs-prediction. Here's what I get when doing so: link
{ "pile_set_name": "StackExchange" }
Q: Can butterflies break off tree branches? The are some fir tree forests in Mexico that are reputed to have butterfly populations so dense that their collective weight is sufficient to occasionally break off tree branches. An example of this claim: Monarchs living east of the Rocky Mountains in North America fly south each fall, gathering in central Mexico's Oyamel fir forest for the winter. Millions of Monarchs gather in the this forest area, covering the trees so densely that branches break from their weight. Scientists aren’t sure how the butterflies navigate to a place they have never been. No other population of Monarchs migrates this far. Has this ever actually happened? If so, has it ever been photographed or captured on video? A: There is a first-person account from 1976, from Dr. Fred A. Urquhart, part of a small team that found the wintering site of the Monarch butterflies after many years searching. While we stared in wonder, a pine branch three inches thick broke under its burden of languid butterflies and crashed to earth, spilling its living cargo. Source: National Geographic In a corresponding article in the Journal of the Ledpidopterists's Society, the authors describe a primitive means used to estimate the weight of the butterflies on a branch - by noting how much a branch bowed by the weight of the butterflies, removing the butterflies and trying to weigh it down equivalently with stones. Their system sounds to me rather inaccurate as it depends on matching the the centre of gravity of the butterflies, but they came up with an estimate of 3.8kg on a 1.5m branch. That makes the idea that a small and weak branch could break under the additional weight of the butterflies seem plausible.
{ "pile_set_name": "StackExchange" }
Q: Parentheses inside Razor code block Trying to put a URL.Action call inside a Razor ASP.Net MVC code block at the top of a View which includes a parameter creation - it won't parse and causes an error on the page. Seen similar questions where they remove the "@" but I've tried that. I am using an Action for the jpg url as it points to a rewriter. Code placed at the top of the page: @{ ViewBag.Title = @Model.event_title + " - Event - HOTSHOE"; ViewBag.MetaDescription = @Model.event_title + " - HOTSHOE"; Layout = "~/Views/Shared/_Hotshoe.cshtml"; ViewBag.MainImage = Url.Action("thumbnail", "Events" , new { id=Model.event_ID }) + "/imagename.jpg"; } The problematic line is ViewBag.MainImage = Url.Action("thumbnail", "Events" , new { id=Model.event_ID }) + "/imagename.jpg"; In the editor it complains Syntax Error, ',' expected Just after Model.event_ID but before the "}". This code works on another part of the page outside of the code block with @ in front of @Url.Action and @Model.event_ID When viewing the page it complains: Compiler Error Message: CS1513: } expected Source Error: Line 7476: } Line 7477: } Line 7478:} Any ideas ? TIA. A: Humm i'm not discovering why it doesn't work but... Solution @{ ViewBag.Title = @Model.event_title + " - Event - HOTSHOE"; ViewBag.MetaDescription = @Model.event_title + " - HOTSHOE"; Layout = "~/Views/Shared/_Hotshoe.cshtml"; } @(ViewBag.MainImage = Url.Action("thumbnail", "Events" , new { id=Model.event_ID }) + "/imagename.jpg";) Edit Ok i found the problem. ViewBag.Title = @Model.event_title + " - Event - HOTSHOE"; ViewBag.MetaDescription = @Model.event_title + " - HOTSHOE"; Remove the @ from @Model.event_title
{ "pile_set_name": "StackExchange" }
Q: jquery hide() not working after page loads I think I'm missing something simple and obvious here - I'm working on a site where I need to filter portfolio categories, and also show the category description on the link click, but not for the "All" list item. The page loads fine and then I can click and filter the categories/descriptions fine, but then if you click back to "All" the category description for whatever was last clicked remains even though it should hide. Here is the dev site (Wordpress) - http://foothilltile.com/dev/products/ Here is the relevant code: <ul class="filter-nav"> <li> <h4><?php _e("Filter:", "elemis"); ?></h4> </li> <li class="selected-1 all"><a href="#" data-value="all"> <h4><?php _e("All", "elemis"); ?></h4> </a></li> <?php $categories= get_categories('taxonomy=kind&orderby=id'); foreach ($categories as $cat) { $input = '<li><a href="#" data-value="'.$cat->category_nicename.'" class="'.$cat->category_nicename.'"><h4>'; $input .= $cat->cat_name; $input .= '</h4></a></li>'; echo $input; } ?> </ul> <div class="clear"></div> <!-- End Portfolio Navigation --> <div id="category-descriptions"> <ul class="descriptions-list"> <li class="all"></li> <?php $categories= get_categories('taxonomy=kind&orderby=id'); foreach ($categories as $cat) { $input = '<li class="cat-desc '.$cat->category_nicename.'">'; $input .= $cat->description; $input .= '</li>'; echo $input; } ?> </ul> </div> <!--/category-descriptions -->` And then the js: jQuery(document).ready(function($) { $('.filter-nav li a').click(function() { // fetch the class of the clicked item var ourClass = $(this).attr('class'); if (ourClass == 'all') { // this should hide the li's on load - but doesn't? $('.descriptions-list').children('li.cat-desc').hide(); } else { // hide all elements that don't share ourClass $('.descriptions-list').children('li:not(.' + ourClass + ')').hide(); // show all elements that do share ourClass $('.descriptions-list').children('li.' + ourClass).show(); } return false; }); }); And the only relevant css is the li.cat-desc is set to display:none. Any suggestions would be appreciated. I'm always confusing the order of code in jQuery (noob, for sure) so thank you in advance for your help. A: The anchor for "All" has no class "all"...thats the problem. The class is set to the li-element... Add the class to the a-element and it should be work
{ "pile_set_name": "StackExchange" }
Q: Remove meaningless words from corpus in R I am using tm and wordcloud for performing some basic text mining in R. The text being processed contains many words which are meaningless like asfdg,aawptkr and i need to filter such words. The closest solution i have found is using library(qdapDictionaries) and building a custom function to check validity of words. library(qdapDictionaries) is.word <- function(x) x %in% GradyAugmented # example > is.word("aapg") [1] FALSE The rest of text mining used is : curDir <- "E:/folder1/" # folder1 contains a.txt, b.txt myCorpus <- VCorpus(DirSource(curDir)) myCorpus <- tm_map(myCorpus, removePunctuation) myCorpus <- tm_map(myCorpus, removeNumbers) myCorpus <- tm_map(myCorpus,foo) # foo clears meaningless words from corpus The issue is is.word() works fine for handling dataframes but how to use it for corpus handling ? Thanks A: If you are willing to try a different text mining package, then this will work: library(readtext) library(quanteda) myCorpus <- corpus(readtext("E:/folder1/*.txt")) # tokenize the corpus myTokens <- tokens(myCorpus, remove_punct = TRUE, remove_numbers = TRUE) # keep only the tokens found in an English dictionary myTokens <- tokens_select(myTokens, names(data_int_syllables)) From there you can form at document-term matrix (called a "dfm" in quanteda) for analysis, and it will only contain the features found as English-language terms as matched in the dictionary (which contains about 130,000 words). A: Not sure if it will be the most resource efficient method (I don't know the package very well) but it should work: tdm <- TermDocumentMatrix(myCorpus ) all_tokens <- findFreqTerms(tdm, 1) tokens_to_remove <- setdiff(all_tokens,GradyAugmented) corpus <- tm_map(corpus, content_transformer(removeWords), tokens_to_remove)
{ "pile_set_name": "StackExchange" }
Q: "true love", compassion and suffering According to Zen Master Thich Nhat Hanh, "true love" has four elements: Loving kindness: this produces a lot of joy and happiness. Compassion: it makes us and the other people suffer less. Joy: "If love does not generate joy, it is not [true] love." Inclusiveness: "In true love there is no frontier between the one who loves and the one who is loved." I'd like to focus on "compassion" here. Don't people who are more compassionate suffer more because they experience the suffering of other people in some sense? So aren't the elements 2 and 3 as mentioned above contrary to each other? I think this question is related but not identical to another question asked before: love and caring is suffering. A: Don't people who are more compassionate suffer more because they experience the suffering of other people? The above appears to be the Western/Christian meaning of compassion, namely, "to suffer with". In Buddhism, the term "karuṇā" (often translated as "compassion") is the wish to ending suffering. It does not mean "to suffer with". karuṇā - “ahita-dukkh-âpanaya-kāmatā,” the desire of removing bane and sorrow (from one’s fellowmen)
{ "pile_set_name": "StackExchange" }
Q: Where can I find mage related questlines? I'm level 17 mage and have completed Winterhold main quest since a while ago. Where can I find other mage or magic related questlines? A: In the Dragonborn DLC, the Tel Mithryn quests are mostly mage-related. Lore-wise, this is because Neloth, which is related to and gives most of the quests, is a wizard lord from House Telvanni, one of the Great Houses of Morrowind. House Telvanni is comprised mainly of mages. Azra's Staffs: Retrieve a staff made by Azra Nightwielder for Master Neloth. Briarheart Necropsy: Examine a Briarheart of the Forsworn for Neloth. Experimental Subject: Help Neloth by being a test subject in his experiment. From the Ashes: Help Talvas Fathryon by killing an ash guardian. Healing a House: Help Elynea Mothren repair the tower of Tel Mithryn. Heart Stones: Find a heart stone for Neloth. Lost Knowledge: Retrieve the Black Book for Neloth. A New Debt: Help Drovas Relvi with his debt to Mogrul. Old Friends: Find the source of attacks on Tel Mithryn. Reluctant Steward: Find a new steward for Neloth in Raven Rock. Telvanni Research: Extract a sample from an ash spawn for Neloth's research. Wind and Sand: Retrieve a copy of Wind and Sand for Neloth. Source: UESP wiki, "Dragonborn quests" article A: I completed the Winterhold College questline but after a while when I came back, speaking to Tolfdir (if I remember correctly) reveals more quests with some magical rifts opening up in the world due to the earlier events with the Eye and so on. I haven't continued on this path myself but go back and talk with the people at the college after some time and you might find more quests after you've become arch mage.
{ "pile_set_name": "StackExchange" }
Q: PHP: Order by DESC won't do it? I have this: $getWallCommentQuery2 = mysql_query("SELECT * FROM users_wallcomments WHERE wallID = '$displayWall[id]' ORDER BY date DESC LIMIT 2"); while($show = mysql_fetch_array($getWallCommentQuery2)){ echo $show["comment"] . " <br> "; } Now, my database: INSERT INTO `users_wallcomments` VALUES (1, 401, 1, 2, '1284056799', 'test kommentar blabla1'); INSERT INTO `users_wallcomments` VALUES (2, 401, 1, 1, '1284540210', 'test test comment2'); INSERT INTO `users_wallcomments` VALUES (3, 401, 1, 1, '1284540225', 'nr3 kommentar'); INSERT INTO `users_wallcomments` VALUES (4, 401, 1, 1, '1284540237', 'nr4 kommentar'); the fifth field.. (where the numbers starts with 1284..) is date unix timestamp. Now i want to sort it from this, by the query at the top, with limit 2; It limits to two, but it doesnt sort it out right when i do ORDER by date DESC.. I am receiving 3th(id) as last and 4th(id) above it? And i wish to have 4th at last(because it has the latest datestamp as you also can see, it has 37, and third has 25) but still it sort the 3th as last. What is wrong? A: Change DESC to ASC A date sorted in descending order (DESC) will always produce the most recent dates first and the earliest dates last. If you sort your dates in ascending order (ASC) you will get the entry with id of 3 first and then the entry with id of 4 next. UPDATE If you want only the last 2 rows sorted in date asc, then try this: SELECT * FROM (SELECT * FROM users_wallcomments WHERE wallID = '$displayWall[id]' ORDER BY date DESC LIMIT 2) recentWallComments ORDER BY date ASC
{ "pile_set_name": "StackExchange" }
Q: React/Redux load paged ID list, then load page I have a react component in a Redux enabled application that starts by loading a list of ID's in a 2D array. (Each "page" is represented by an element of the outer array [1rst dimension]) Here is the component: import React, { Component, Fragment } from "react"; import { loadInsiderPage, loadInsiderInfo } from "../../actions/insider"; import { connect } from "react-redux"; import IndividualInsider from "./individual"; import Paginate from "../common/paginate"; class InsiderList extends Component { componentDidMount() { if (this.props.insiderIds.length > 0) { this.props.loadInsiderPage(this.props.insiderIds[0]); } else { this.props.loadInsiderInfo(); } } render() { let { insiderIds, insiders } = this.props; let insiderFormat = insiders.map(x => { return <IndividualInsider key={x._id} insider={x} />; }); return ( <Fragment> <div className="container"> <Paginate pages={insiderIds} changePage={this.props.loadInsiderPage} /> {insiderFormat} </div> </Fragment> ); } } export default connect( null, { loadInsiderPage, loadInsiderInfo } )(InsiderList); This component will load the ID list if it's not filled by running the loadInsiderInfo() action, and if the ID list is not empty, it will trigger the page to be populated by running the loadInsiderPage() action which takes in a page from the ID list. How can I have this trigger properly after the ID list has been loaded? I was thinking I could do it in componentWillReceiveProps() but I'm not sure where to go with the nextProps property. My actions are as follows: export const loadInsiderInfo = () => dispatch => { Axios.get("insider/list/pages/25") .then(list => { dispatch({ type: LOAD_INSIDER_LIST, payload: list.data }); }) .catch(err => dispatch({ type: GET_ERRORS, payload: err })); }; export const loadInsiderPage = page => dispatch => { console.log(page); Axios.post("insider/page", { page }) .then(res => dispatch({ type: LOAD_INSIDER_PAGE, payload: res.data })) .catch(err => dispatch({ type: GET_ERRORS, payload: err })); }; Both simply grab data from the API and load it into the reducer. The big issue that I'm coming across is that the Component will sometimes have props passed that keep the loadInsiderPage action from being called with a page object passed in. A: In your action creator loadInsiderInfo() you can accept a param for the current page ID. Now when the Info is loaded, within this action creator you can dispatch another action by calling loadInsiderPage(id) in it. This way your page info is loaded for the first time by the insider info action creator itself. Something like this: export const loadInsiderInfo = (id) => dispatch => { Axios.get("insider/list/pages/25") .then(list => { dispatch({ type: LOAD_INSIDER_LIST, payload: list.data }); if(<your-data-loaded>){ loadInsiderPage(id)(dispatch); } }) .catch(err => dispatch({ type: GET_ERRORS, payload: err })); }; Now only call loadInsiderInfo(id) once, when there is no info loaded yet. For every other time, directly dispatch the loadInsiderPage(id) action instead. This way you handle every case, after the insider info data has been loaded.
{ "pile_set_name": "StackExchange" }
Q: Remove a value from a querystring I have a URL in which a querystring is produced by a PHP script. Various values are displayed in the querystring. Basically, I need to remove a specific value from the query string when a visitor clicks on a link or a 'remove' button. So, the querystring looks like this: http://www.foo.com/script.php?bar1=green&bar2=blue But when a link or 'remove' button is clicked by a user, bar1=green is removed, and the visitor is directed to the following URL: http://www.foo.com/script.php?bar2=blue I thought this would be easy using basic HTML with a form or anchor but I haven't been able to do it so far. Just so you know, i do not have access to the code on the PHP script itself; it is hosted remotely and is called to my webpage by a PHP wrapper using an iframe. Any suggestions greatly appreciated. Many thanks, Matt A: You can remove the value from the query string using this code: <?php function parseQueryString($url,$remove) { $infos=parse_url($url); $str=$infos["query"]; $op = array(); $pairs = explode("&", $str); foreach ($pairs as $pair) { list($k, $v) = array_map("urldecode", explode("=", $pair)); $op[$k] = $v; } if(isset($op[$remove])){ unset($op[$remove]); } return str_replace($str,http_build_query($op),$url); } echo parseQueryString( "http://www.foo.com/script.php?bar1=green&bar2=blue","bar2"); ?>
{ "pile_set_name": "StackExchange" }
Q: recursion over tuples list in haskell Is there a recursion way to do somethings like below? updateOs2 :: [(Rotor, Int)] -> [(Rotor, Int)] updateOs2 [(a,x),(b,y),(c,z)] | x == 25 && y == 25 && z == 25 = [(a,0),(b,0),(c,0)] | x == 25 && y == 25 = [(a,0),(b,0),(c,z+1)] | x == 25 = [(a,0),(b,y+1),(c,z)] | otherwise = [(a,x+1),(b,y),(c,z)] I have tried to do recursion, but quite confused. Because once the last element z is passed the list comes to empty, can not go back to x anymore. A: I think this should work updateOs2 [] = [] updateOs2 ((a,x):xs) | x == 25 = (a,0): (updateOs2 xs) | otherwise = (a,x+1):xs
{ "pile_set_name": "StackExchange" }
Q: RaiseEvent("onchange") I have a winform and a WebBrowser control and I am changing an option in select HTML control. webBrowser1.Document .GetElementsByTagName("select")[4] .GetElementsByTagName("option")[13] .SetAttribute("selected", "true"); Now it works and selects the required option, but it does not fire the onchange event. The select does not have an element id but it does have a class name. I tried: webBrowser1.Document .GetElementsByTagName("select")[4] .RaiseEvent("onchange"); and webBrowser1.Document .GetElementsByTagName("select")[4] .GetElementsByTagName("option")[13] .RaiseEvent("onchange"); But in vain. A: I tried and sent a TAB key after selecting an option and it raised the onchange event. webBrowser1.Document.GetElementsByTagName("select")[4].Focus(); webBrowser1.Document.GetElementsByTagName("select")[4] .GetElementsByTagName("option")[13].SetAttribute("selected", "true"); SendKeys.Send("{TAB}"); Everything is good now.
{ "pile_set_name": "StackExchange" }
Q: Creating multiple random numpy arrays with different range of values I got a question so I was trying to create a 3D array containing multiple 2D array with different range of values, for example I can do this: import numpy as np np.random.seed(1) arr = np.random.randint(1, 10, size = (2,2)) #Random 2D array with range of values (1, 10) arr2 = np.random.randint(11, 20, size = (2,2)) #Random 2D array with range of values (11, 20) ... and then create the 3D array by this newarr = np.array([arr, arr2, ...]) I try doing this: import numpy as np np.random.seed(1) n = 3 aux = [] for i in range (n): if i == 0: aux.append(rng4.randint(1, 10, size = (2, 2))) elif i == 1: aux.append(rng4.randint(11, 20, size = (2, 2))) elif i == 2: aux.append(rng4.randint(21, 30, size = (2, 2))) newarr = np.array(aux) The output is what I want but in either case if I want another range of values I need to "add" manually a new elif to give another range, is there a way I can do this? Thank you! A: It is a trivial loop programming exercise: newarr = np.empty(shape=(2, 2, n)) for i in range (n): newarr[:,:,i] = rng4.randint(i * 10 + 1, i * 10 + 10, size = (2, 2))
{ "pile_set_name": "StackExchange" }
Q: Cakephp request action gives me a never ending request loop I have an element with a requestAction but it gives me a never ending request loop. For example: This is my element <?php $plans = $this->requestAction('profile/Plans'); ?> <?php foreach($plans as $plan): ?> <div class="notificationsmall <?php echo $plan['sections']['lable']; ?>"> <p><b><?php echo $plan['plans']['plan_title']; ?></b></p> <p><?php echo $plan['plans']['plan_description']; ?></p> </div> <?php endforeach;?> And this is the function that. Its in the "profile" controller function Plans($id = Null){ $this->set('plans', $this->Plan->Query('SELECT * FROM plans, sections WHERE plans.user_id='.$id.' AND sections.id=plans.section_id')); } I have no idea what's wrong. A: Is the first piece of code the profile/plans view? If so, you get an infinite loop because the view calls the profile/plans action again, comes back to the same point in the view and so on. Judging by the code I think you have some misunderstanding on how elements work. You should use the requestAction when you need to insert the element, not inside the element itself. (I agree with Dunhamzzz that requestAction should be avoided, but sometimes it's not possible. You should consider if using actual elements would work in this case.)
{ "pile_set_name": "StackExchange" }
Q: Common-LISP Print function itself I want to print ,as described in the title, my whole function. (DEFUN X () ...) -> (DEFUN X () ...) What do i need to write in "..." ? A: #1=(defun x () (write '#1# :circle t))
{ "pile_set_name": "StackExchange" }
Q: Difference between viewDidAppear, viewDidLoad in iPhone/iOS? Bottom line is, I've been working on an app, and it seems that if I place a UIAlert in viewDidLoad, it gets called twice (from a delegate method of UIImagePickerController). If I put it in viewDidAppear, it gets called once. I've looked through documentation but it just confuses me. A: A UIView object can get loaded into memory and released multiple times without ever getting added to the view stack and appearing on the display. My guess is that you have 2 references to this view (maybe one in a nib file?), so it's getting loaded, then released when the second reference is loaded and assigned to the same property, then only the latter gets added to the view stack. You can see this by printing out (NSLog) the integer value of self ("%ld",(long int)self) in the viewDidLoad and viewDidAppear methods.
{ "pile_set_name": "StackExchange" }
Q: How to deal with initialization of non-const reference member in const object? Let's say you have a class class C { int * i; public: C(int * v):i(v) {}; void method() const; //this method does not change i void method(); //this method changes i } Now you may want to define const instance of this class const int * k = whatever; const C c1(k); //this will fail but this will fail because of non-const int C's constructor C(int * v) so you define a const int constructor C(const int * v):i(v) {}; //this will fail also But this will fail also since C's member "int * i" is non-const. What to do in such cases? Use mutable? Casting? Prepare const version of class? edit: After discussion with Pavel (below) I investigated this problem a bit. To me what C++ does is not correct. Pointer target should be a strict type, that means that you could not for example do the following: int i; const int * ptr; ptr = & i; In this case language grammar treats const as a promise not to change pointer's target. In addition int * const ptr is a promise not to change pointer value itself. Thus you have two places where const can be applied. Then you may want your class to model a pointer (why not). And here things are falling into pieces. C++ grammar provides const methods which are able to promise not to change field's values itself but there is no grammar to point out that your method will not change targets of your in-class pointers. A workaround is to define two classes const_C and C for example. It isn't a royal road however. With templates, their partial specializations it's hard not to stuck into a mess. Also all possible arguments variations like const const_C & arg, const C & arg, const_C & arg, C & arg don't look pretty. I really don't know what to do. Use separate classes or const_casts, each way seems to be wrong. In both cases should I mark methods which don't modify pointer's target as const? Or just follow traditional path that const method doesn't change object's state itself (const method don't care about pointer target). Then in my case all methods would be const, because class is modelling a pointer thus pointer itself is T * const. But clearly some of them modify pointer's target and others do not. A: Sounds like you want an object that can wrap either int* (and then behave as non-const), or int const* (and then behave as const). You can't really do it properly with a single class. In fact, the very notion that const applied to your class should change its semantics like that is wrong - if your class models a pointer or an iterator (if it wraps a pointer, it's likely to be the case), then const applied to it should only mean that it cannot be changed itself, and should not imply anything regarding the value pointed to. You should consider following what STL does for its containers - it's precisely why it has distinct iterator and const_iterator classes, with both being distinct, but the former being implicitly convertible to the latter. As well, in STL, const iterator isn't the same as const_iterator! So just do the same. [EDIT] Here's a tricky way to maximally reuse code between C and const_C while ensuring const-correctness throughout, and not delving into U.B. (with const_cast): template<class T, bool IsConst> struct pointer_to_maybe_const; template<class T> struct pointer_to_maybe_const<T, true> { typedef const T* type; }; template<class T> struct pointer_to_maybe_const<T, false> { typedef T* type; }; template<bool IsConst> struct C_fields { typename pointer_to_maybe_const<int, IsConst>::type i; // repeat for all fields }; template<class Derived> class const_C_base { public: int method() const { // non-mutating method example return *self().i; } private: const Derived& self() const { return *static_cast<const Derived*>(this); } }; template<class Derived> class C_base : public const_C_base<Derived> { public: int method() { // mutating method example return ++*self().i; } private: Derived& self() { return *static_cast<Derived*>(this); } }; class const_C : public const_C_base<const_C>, private C_fields<true> { friend class const_C_base<const_C>; }; class C : public C_base<C>, private C_fields<false> { friend class C_base<C>; }; If you actually have few fields, it may be easier to duplicate them in both classes rather than going for a struct. If there are many, but they are all of the same type, then it is simpler to pass that type as a type parameter directly, and not bother with const wrapper template. A: Your example doesn't fail, k is passed by value. The member i is 'implicitly constant' as direct members of C can't be changed when the instance is constant. Constness says that you can't change members after initialization, but initializing them with values in the initialization list is of course allowed - how else would you give them a value? What doesn't work is invoking the constructor without making it public though ;) update addressing updated question: Yes, C++ forces you into some verboseness sometimes, but const correctness is a common standard behaviour that you can't just redefine without breaking expectations. Pavels answer already explains one common idiom, which is used in proven libraries like the STL, for working around this situation. Sometimes you have to just accept that languages have limitations and still deal with the expectations of the users of the interface, even if that means applying an apparently sub-optimal solution.
{ "pile_set_name": "StackExchange" }
Q: show pop up when trying to add a duplicate record to the database Is there anyway that I could show a pop up when the user tries to enter a record which already exists in the database? Right now the user will be redirected to the Index View when he submits data which already exist in the database. Here is the current code: [HttpPost] public ActionResult Create(Product product) { if (ModelState.IsValid) { if(DQL.DuplicateCheck(product)) { // This is what I want to change return RedirectToAction("Index"); } else { db.Product.Add(product); db.SaveChanges(); TempData["product_model"] = product; return RedirectToAction("Product", "Success"); } } return View(product); } I searched now for a while but didn't found anything appropriate. Any help is highly appreciated :) A: Using jquery ui dialog you can achieve this. Add a TempData flag for duplication check and do the same in view using jQuery and display the popup window. [HttpPost] public ActionResult Create(Product product) { TempData["Duplicate"] = null; if (ModelState.IsValid) { if(DQL.DuplicateCheck(product)) { TempData["Duplicate"] = "Yes"; } else { db.Product.Add(product); db.SaveChanges(); TempData["product_model"] = product; return RedirectToAction("Product", "Success"); } } return View(product); } Create.cshtml or CreateView <div id="dialog-message" title="Message"> <p id="validMessage"> </p> </div> $(function () { $("#dialog-message").dialog({ modal: true, autoOpen: false, resizable: false, width: 400, buttons: { Ok: function () { $(this).dialog('close'); } } }); var isDuplicate = '@TempData["Duplicate"]'; if(isDuplicate == 'Yes') { $("#validMessage").html("Duplicate record found"); $("#dialog-message").dialog('open'); } }
{ "pile_set_name": "StackExchange" }
Q: Arquillian - Wildfly cannot deploy test.war (Could not connect to http-remoting://127.0.0.1:9990. The connection failed) I am trying to run a simple JPA test (persist, read, JSON serialize) with Arquillian and Wildfly (8.1.0.Final and 8.2.0.Final tested) container, but until now I was not able to deploy test.war to the embedded server. The test runs with Jboss 7.1.1.Final container. I have used arquillian-tutorial package given on Arquillian Getting Started Guide and Arquillian Example Project (google: github arquillian tutorial) I have used Arquillian - Wildfly configuration given here You can find a downloadable project package on google drive. You can see Maven and Arquillian configurations in that package. I have tried with or without Management realm credentials. On profile wildfy81-embedded-credentials (which is the default in the package), the build first unpacks wildfly package and then overwrites mgmt-users.properties and mgmt-groups.properties where admin user credentials and role is defined. The exception is INFO [org.jboss.ws.common.management] JBWS022052: Starting JBoss Web Services - Stack CXF Server 4.2.4.Final INFO [org.jboss.as] JBAS015961: Http management interface listening on http://127.0.0.1:9990/management INFO [org.jboss.as] JBAS015951: Admin console listening on http://127.0.0.1:9990 INFO [org.jboss.as] JBAS015874: WildFly 8.1.0.Final "Kenny" started in 3401ms - Started 184 of 233 services (81 services are lazy, passive or on-demand) INFO [org.xnio] XNIO version 3.2.0.Beta4 INFO [org.xnio.nio] XNIO NIO Implementation Version 3.2.0.Beta4 INFO [org.jboss.remoting] JBoss Remoting version 4.0.3.Final ERROR [org.jboss.remoting.remote.connection] JBREM000200: Remote connection failed: java.io.IOException: JBREM000202: Abrupt close on Remoting connection 0a93e136 to /127.0.0.1:9990 ERROR [org.jboss.remoting.remote.connection] JBREM000200: Remote connection failed: java.io.IOException: An existing connection was forcibly closed by the remote host ERROR [org.jboss.remoting.remote.connection] JBREM000200: Remote connection failed: java.io.IOException: JBREM000202: Abrupt close on Remoting connection 084cf5d6 to /127.0.0.1:9990 ERROR [org.jboss.remoting.remote.connection] JBREM000200: Remote connection failed: java.io.IOException: An existing connection was forcibly closed by the remote host WARN [org.jboss.as.arquillian.container.ArchiveDeployer] Cannot undeploy: test.war: org.jboss.as.controller.client.helpers.standalone.ServerDeploymentHelper$ServerDeploymentException: java.lang.RuntimeException: java.net.ConnectException: JBAS012174: Could not connect to http-remoting://127.0.0.1:9990. The connection failed at org.jboss.as.controller.client.helpers.standalone.ServerDeploymentHelper.undeploy(ServerDeploymentHelper.java:109) [wildfly-controller-client-8.1.0.Final.jar:8.1.0.Final] at org.jboss.as.arquillian.container.ArchiveDeployer.undeploy(ArchiveDeployer.java:55) [wildfly-arquillian-common-8.1.0.Final.jar:8.1.0.Final] at org.jboss.as.arquillian.container.CommonDeployableContainer.undeploy(CommonDeployableContainer.java:152) [wildfly-arquillian-common-8.1.0.Final.jar:8.1.0.Final] Caused by: java.lang.RuntimeException: java.net.ConnectException: JBAS012174: Could not connect to http-remoting://127.0.0.1:9990. The connection failed at org.jboss.as.controller.client.impl.AbstractModelControllerClient.executeAsync(AbstractModelControllerClient.java:103) [wildfly-controller-client-8.1.0.Final.jar:8.1.0.Final] at org.jboss.as.controller.client.helpers.standalone.impl.ModelControllerClientServerDeploymentManager.executeOperation(ModelControllerClientServerDeploymentManager.java:50) [wildfly-controller-client-8.1.0.Final.jar:8.1.0.Final] at org.jboss.as.controller.client.helpers.standalone.impl.AbstractServerDeploymentManager.execute(AbstractServerDeploymentManager.java:79) [wildfly-controller-client-8.1.0.Final.jar:8.1.0.Final] at org.jboss.as.controller.client.helpers.standalone.ServerDeploymentHelper.undeploy(ServerDeploymentHelper.java:106) [wildfly-controller-client-8.1.0.Final.jar:8.1.0.Final] ... 82 more Caused by: java.net.ConnectException: JBAS012174: Could not connect to http-remoting://127.0.0.1:9990. The connection failed at org.jboss.as.protocol.ProtocolConnectionUtils.connectSync(ProtocolConnectionUtils.java:117) [wildfly-protocol-8.1.0.Final.jar:8.1.0.Final] at org.jboss.as.protocol.ProtocolConnectionManager$EstablishingConnection.connect(ProtocolConnectionManager.java:256) [wildfly-protocol-8.1.0.Final.jar:8.1.0.Final] Could you please help me to find the issue here? Thanks in advance. Edit 1 From arquillian.xml <container qualifier="wildfly-embedded-credentials"> <configuration> <property name="jbossHome">target/wildfly-8.1.0.Final</property> <property name="modulePath">target/wildfly-8.1.0.Final/modules</property> <property name="managementAddress">127.0.0.1</property> <property name="managementPort">9990</property> <property name="username">admin</property> <property name="password">admin</property> <property name="outputToConsole">true</property> </configuration> </container> Deployment code: @Deployment public static WebArchive createDeployment() { return ShrinkWrap.create(WebArchive.class, "test.war") .addPackage(MyBean.class.getPackage()) .addAsLibraries(new File("target/test-libs/commons-collections.jar"), new File("target/test-libs/flexjson.jar")) .addAsResource("test-persistence.xml", "META-INF/persistence.xml") .addAsWebInfResource("jboss-ds.xml") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); } I wonder if this is because of URL INFO Http management interface listening on http://127.0.0.1:9990/management Edit 2 In the attached project (google drive link above), you will see there is another profile wildfy81-embedded in pom.xml with different arquillian configuration where I do not supply management address or username and password, only jbossHome and modulePath folders are defined. I get same exception (same port as well, 9990). <container qualifier="wildfly-embedded"> <configuration> <property name="jbossHome">target/wildfly-8.1.0.Final</property> <property name="modulePath">target/wildfly-8.1.0.Final/modules</property> <property name="outputToConsole">true</property> </configuration> </container> On my last test, I have noticed one more exception cause (maybe because of java version or eclipse version that I am using at home). This was the exception at the bottom of other exception lines Could not connect to http-remoting://127.0.0.1:9990. The connection failed Caused by: java.io.IOException: Invalid response at org.xnio.http.HttpUpgradeParser.parseVersion(HttpUpgradeParser.java:150) [xnio-api-3.2.0.Beta4.jar:3.2.0.Beta4] at org.xnio.http.HttpUpgradeParser.parse(HttpUpgradeParser.java:53) [xnio-api-3.2.0.Beta4.jar:3.2.0.Beta4] at org.xnio.http.HttpUpgrade$HttpUpgradeState$UpgradeResultListener.handleEvent(HttpUpgrade.java:299) [xnio-api-3.2.0.Beta4.jar:3.2.0.Beta4] at org.xnio.http.HttpUpgrade$HttpUpgradeState$UpgradeResultListener.handleEvent(HttpUpgrade.java:279) [xnio-api-3.2.0.Beta4.jar:3.2.0.Beta4] at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92) [xnio-api-3.2.0.Beta4.jar:3.2.0.Beta4] at org.xnio.conduits.ReadReadyHandler$ChannelListenerHandler.readReady(ReadReadyHandler.java:66) [xnio-api-3.2.0.Beta4.jar:3.2.0.Beta4] at org.xnio.nio.NioSocketConduit.handleReady(NioSocketConduit.java:87) [xnio-nio-3.2.0.Beta4.jar:3.2.0.Beta4] at org.xnio.nio.WorkerThread.run(WorkerThread.java:531) [xnio-nio-3.2.0.Beta4.jar:3.2.0.Beta4] at ...asynchronous invocation...(Unknown Source) at org.jboss.remoting3.EndpointImpl.doConnect(EndpointImpl.java:272) [jboss-remoting-4.0.3.Final.jar:4.0.3.Final] at org.jboss.remoting3.EndpointImpl.doConnect(EndpointImpl.java:253) [jboss-remoting-4.0.3.Final.jar:4.0.3.Final] at org.jboss.remoting3.EndpointImpl.connect(EndpointImpl.java:351) [jboss-remoting-4.0.3.Final.jar:4.0.3.Final] at org.jboss.remoting3.EndpointImpl.connect(EndpointImpl.java:339) [jboss-remoting-4.0.3.Final.jar:4.0.3.Final] at org.jboss.as.protocol.ProtocolConnectionUtils.connect(ProtocolConnectionUtils.java:78) [wildfly-protocol-8.1.0.Final.jar:8.1.0.Final] at org.jboss.as.protocol.ProtocolConnectionUtils.connectSync(ProtocolConnectionUtils.java:109) [wildfly-protocol-8.1.0.Final.jar:8.1.0.Final] ... 95 more A: I have encountered this exception (invalid response part) a few times because of Nvidia drivers on windows platform. NVIDIA Network Service is using the same port WildFly/JBoss AS is using. If you are using windows with nvidia, then please go to local services and stop this service, then check if the tests work :).
{ "pile_set_name": "StackExchange" }
Q: receiving push notification after realtime database value changes I want to send push notifications to user whenever a node gets updated to the FCM realtime DB. my FCM function triggers a notification . I can see this in the FCM logs. But I am not able to see the notification getting dicsplayed in my client app. Can some one help me? My logs are below: In the client side I have the below code to receive notification: MainActivity.java protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); String channelId = "1"; String channel2 = "2"; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { NotificationChannel notificationChannel = new NotificationChannel(channelId, "Channel 1",NotificationManager.IMPORTANCE_HIGH); notificationChannel.setDescription("This is BNT"); notificationChannel.setLightColor(Color.RED); notificationChannel.enableVibration(true); notificationChannel.setShowBadge(true); notificationManager.createNotificationChannel(notificationChannel); NotificationChannel notificationChannel2 = new NotificationChannel(channel2, "Channel 2",NotificationManager.IMPORTANCE_MIN); notificationChannel.setDescription("This is bTV"); notificationChannel.setLightColor(Color.RED); notificationChannel.enableVibration(true); notificationChannel.setShowBadge(true); notificationManager.createNotificationChannel(notificationChannel2); } // Get Firebase database reference this.mDatabase = FirebaseDatabase.getInstance().getReference().child("masterSheet"); //FirebaseMessaging.getInstance().subscribeToTopic("pushNotifications"); //FirebaseMessaging.getInstance().subscribeToTopic("pushNotifications"); // Init user list ListView list = (ListView) this.findViewById(R.id.dataList); this.listAdapter = new DataListAdapter(this, R.layout.list_view_cell); list.setAdapter(listAdapter); } MyFirebaseMessagingService.java public void onMessageReceived(RemoteMessage remoteMessage) { Intent notificationIntent = new Intent(this, MainActivity.class); if(MainActivity.isAppRunning){ //Some action }else{ //Show notification as usual } notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, notificationIntent, PendingIntent.FLAG_ONE_SHOT); //You should use an actual ID instead int notificationId = new Random().nextInt(60000); Bitmap bitmap = getBitmapfromUrl(remoteMessage.getData().get("image-url")); Intent likeIntent = new Intent(this,LikeService.class); likeIntent.putExtra(NOTIFICATION_ID_EXTRA,notificationId); likeIntent.putExtra(IMAGE_URL_EXTRA,remoteMessage.getData().get("image-url")); PendingIntent likePendingIntent = PendingIntent.getService(this, notificationId+1,likeIntent,PendingIntent.FLAG_ONE_SHOT); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { setupChannels(); } NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID) .setLargeIcon(bitmap) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(remoteMessage.getData().get("title")) .setStyle(new NotificationCompat.BigPictureStyle() .setSummaryText(remoteMessage.getData().get("message")) .bigPicture(bitmap))/*Notification with Image*/ .setContentText(remoteMessage.getData().get("message")) .setAutoCancel(true) .setSound(defaultSoundUri) .addAction(R.drawable.ic_favorite_true, getString(R.string.notification_add_to_cart_button),likePendingIntent) .setContentIntent(pendingIntent); notificationManager.notify(notificationId, notificationBuilder.build()); } Node.js const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); exports.pushNotification = functions.database.ref('/masterSheet/{pushId}').onWrite( event => { console.log('Push notification event triggered'); const payload = { notification: { title: 'App Name', body: "New message", sound: "default" }, data: { title: "New Title", message:"New message" } }; const options = { priority: "high", timeToLive: 60 * 60 * 24 //24 hours }; return admin.messaging().sendToTopic("notifications", payload, options); }); A: It doesn't look like you're subscriping to the topic "notification": FirebaseMessaging.getInstance().subscribeToTopic("notifications");
{ "pile_set_name": "StackExchange" }
Q: AngularJS directive to limit a container to a certain number of lines I wrote a directive to limit a container (div, p, etc.) to a certain number of lines. I took the code from Detect browser wrapped lines via javascript and wrapped it in a directive and added some checking for number of lines. The issue I am having is that I am dependent on jQuery because I don't know exactly how to inject text into a div, and then do calculations to create lines, because angular has a digest cycle I don't know how to get around. Here is my code: http://plnkr.co/edit/DTUjRxEjrXZiA25Kal4u?p=preview app.directive('lineLimit', function(){ return { restrict: 'A', templateUrl: 'temp.html', scope: { text: "=" }, link: function(scope, elem, attrs) { console.log("limit", attrs.lineLimit); var $cont = $(elem).children('.title-container'); $cont.text(scope.text); var text_arr = $cont.text().split(' '); for (i = 0; i < text_arr.length; i++) { text_arr[i] = '<span>' + text_arr[i] + ' </span>'; } $cont.html(text_arr.join('')); var $wordSpans = $cont.find('span'); var lineArray = [], lineIndex = 0, lineStart = true, lineEnd = false $wordSpans.each(function(idx) { var pos = $(this).position(); var top = pos.top; if (lineStart) { lineArray[lineIndex] = [idx]; lineStart = false; } else { var $next = $(this).next(); if ($next.length) { if ($next.position().top > top) { lineArray[lineIndex].push(idx); lineIndex++; lineStart = true } } else { lineArray[lineIndex].push(idx); } } }); for (var i = 0; i < lineArray.length; i++) { var start = lineArray[i][0], end = lineArray[i][1] + 1; /* no end value pushed to array if only one word last line*/ if (!end) { $wordSpans.eq(start).wrap('<span class="line_wrap">') } else { $wordSpans.slice(start, end).wrapAll('<span class="line_wrap">'); } } //console.log('children', $cont.children().length) $.each($cont.children(), function(index, value){ //console.log(index+1) if(index+1 > attrs.lineLimit){ value.remove(); } }); var sub = $cont.text().substring(0, $cont.text().length-3) $cont.text(sub+'...'); } }; }); What I'm trying to achieve is to limit a container to a certain number of lines and show an ellipsis on the last line A: A very good answer can be found here: https://github.com/dibari/angular-ellipsis /** * Angular directive to truncate multi-line text to visible height * * @param bind (angular bound value to append) REQUIRED * @param ellipsisAppend (string) string to append at end of truncated text after ellipsis, can be HTML OPTIONAL * @param ellipsisSymbol (string) string to use as ellipsis, replaces default '...' OPTIONAL * @param ellipsisAppendClick (function) function to call if ellipsisAppend is clicked (ellipsisAppend must be clicked) OPTIONAL * * @example <p data-ellipsis data-ng-bind="boundData"></p> * @example <p data-ellipsis data-ng-bind="boundData" data-ellipsis-symbol="---"></p> * @example <p data-ellipsis data-ng-bind="boundData" data-ellipsis-append="read more"></p> * @example <p data-ellipsis data-ng-bind="boundData" data-ellipsis-append="read more" data-ellipsis-append-click="displayFull()"></p> * */ (function(ng, app){ "use strict"; app.directive('ellipsis', function($timeout, $window) { return { restrict : 'A', scope : { ngBind : '=', ellipsisAppend : '@', ellipsisAppendClick : '&', ellipsisSymbol : '@' }, compile : function(elem, attr, linker) { return function(scope, element, attributes) { /* Window Resize Variables */ attributes.lastWindowResizeTime = 0; attributes.lastWindowResizeWidth = 0; attributes.lastWindowResizeHeight = 0; attributes.lastWindowTimeoutEvent = null; /* State Variables */ attributes.isTruncated = false; function buildEllipsis() { if (typeof(scope.ngBind) !== 'undefined') { var bindArray = scope.ngBind.split(" "), i = 0, ellipsisSymbol = (typeof(attributes.ellipsisSymbol) !== 'undefined') ? attributes.ellipsisSymbol : '&hellip;', appendString = (typeof(scope.ellipsisAppend) !== 'undefined' && scope.ellipsisAppend !== '') ? ellipsisSymbol + '<span>' + scope.ellipsisAppend + '</span>' : ellipsisSymbol; attributes.isTruncated = false; element.html(scope.ngBind); // If text has overflow if (isOverflowed(element)) { var bindArrayStartingLength = bindArray.length, initialMaxHeight = element[0].clientHeight; element.html(scope.ngBind + appendString); // Set complete text and remove one word at a time, until there is no overflow for ( ; i < bindArrayStartingLength; i++) { bindArray.pop(); element.html(bindArray.join(" ") + appendString); if (element[0].scrollHeight < initialMaxHeight || isOverflowed(element) === false) { attributes.isTruncated = true; break; } } // If append string was passed and append click function included if (ellipsisSymbol != appendString && typeof(scope.ellipsisAppendClick) !== 'undefined' && scope.ellipsisAppendClick !== '' ) { element.find('span').bind("click", function (e) { scope.$apply(scope.ellipsisAppendClick); }); } } } } /** * Test if element has overflow of text beyond height or max-height * * @param element (DOM object) * * @return bool * */ function isOverflowed(thisElement) { return thisElement[0].scrollHeight > thisElement[0].clientHeight; } /** * Watchers */ /** * Execute ellipsis truncate on ngBind update */ scope.$watch('ngBind', function () { buildEllipsis(); }); /** * Execute ellipsis truncate on ngBind update */ scope.$watch('ellipsisAppend', function () { buildEllipsis(); }); /** * When window width or height changes - re-init truncation */ angular.element($window).bind('resize', function () { $timeout.cancel(attributes.lastWindowTimeoutEvent); attributes.lastWindowTimeoutEvent = $timeout(function() { if (attributes.lastWindowResizeWidth != window.innerWidth || attributes.lastWindowResizeHeight != window.innerHeight) { buildEllipsis(); } attributes.lastWindowResizeWidth = window.innerWidth; attributes.lastWindowResizeHeight = window.innerHeight; }, 75); }); }; } }; }); })(angular, exampleApp);
{ "pile_set_name": "StackExchange" }
Q: C# casting int to float throwing exception (in runtime) This throws an exception that say the source can't be casted to destination: int a = 1; object b = (object)a; float c = (float)b; // Exception here Why? A: You can only cast boxed structs to the exact type, so you'll need to cast a to int first: float c = (float)(int)b; However since there's an implicit conversion to float from int, you can just do: float c = (int)b; A: This question is asked very frequently on SO. See my article on the subject for the details. http://blogs.msdn.com/b/ericlippert/archive/2009/03/19/representation-and-identity.aspx
{ "pile_set_name": "StackExchange" }
Q: Dynamic Allocation 2d array in C difference with a simple 2d array Mpi I have a MPI program for image processing (pgm file) in MPI C and I use Dynamic allocation for a 2D Array as follows. float **masterbuf; masterbuf = arralloc(sizeof(float), 2, M, N); When I use float masterbuf[M][N]; the image that the program gives looks fine. The problem is that when I use dynamic allocation the image loses some pixels in its left side. So these missing pixels create a black line. It's like the image has been shifted 2 pixels right. I don't do any other operations to the image, just read it and print it again. The function that I use to write the image is: void pgmwrite(char *filename, void *vx, int nx, int ny) { FILE *fp; int i, j, k, grey; float xmin, xmax, tmp, fval; float thresh = 255.0; float *x = (float *) vx; if (NULL == (fp = fopen(filename,"w"))) { fprintf(stderr, "pgmwrite: cannot create <%s>\n", filename); exit(-1); } printf("Writing %d x %d picture into file: %s\n", nx, ny, filename); /* * Find the max and min absolute values of the array */ xmin = fabs(x[0]); xmax = fabs(x[0]); for (i=0; i < nx*ny; i++) { if (fabs(x[i]) < xmin) xmin = fabs(x[i]); if (fabs(x[i]) > xmax) xmax = fabs(x[i]); } if (xmin == xmax) xmin = xmax-1.0; fprintf(fp, "P2\n"); fprintf(fp, "# Written by pgmwrite\n"); fprintf(fp, "%d %d\n", nx, ny); fprintf(fp, "%d\n", (int) thresh); k = 0; for (j=ny-1; j >=0 ; j--) { for (i=0; i < nx; i++) { /* * Access the value of x[i][j] */ tmp = x[j+ny*i]; /* * Scale the value appropriately so it lies between 0 and thresh */ fval = thresh*((fabs(tmp)-xmin)/(xmax-xmin))+0.5; grey = (int) fval; fprintf(fp, "%3d ", grey); if (0 == (k+1)%16) fprintf(fp, "\n"); k++; } } if (0 != k%16) fprintf(fp, "\n"); fclose(fp); } A: Your two definitions of masterbuf may both create 2D arrays, but they don't do so in the same way. The function arralloc() creates space for data and pointers--not just data as with the simple static array definition. What this works out to mean is that in pgmwrite(), while x[i][j] will return the same result regardless of the method used, x[i] will mean two different things because of the pointer involvement. It's worth noting that you'll be given a clue by the compiler as to the problem should you change void *vx in the prototype to float *vx. Since you're immediately and unconditionally casting this void * to a float *, it'd be much better practice to do this anyhow. (2nd edit:) Also, if interested, check out this response. It shows how to index using two dimensions into a single malloc'd block, without arralloc().
{ "pile_set_name": "StackExchange" }
Q: Вызов внешней программы В программе нужно вызвать внешнюю, в частности, среду моделирования GPSS World и передать туда текст описания. Может кто знает, есть ли у нее параметры вызова. Или как это еще можно сделать? Чтобы она открылась - и текст описания уже был в ней. Мое мнение: если есть параметры запуска, то system("gpssw.exe ...") или чрерз ShellExecute(...). A: Из руководства: A new Batch Mode of operation can be used to run simulations in the background. If you specify a Model File or a Simulation File on the DOS command line followed by the word "BATCH", GPSS World will run in a minimized window. It first opens the file and then passes it a Create Command (if a Model Object) or a CONTINUE Command (if a Simulation Object). In the former case, you would normally append the desired run control Commands in the Model itself. You can use the new EXIT 1 Command (or Exit(1) Library Procedure) to shut down the resulting Session by itself, automatically saving all the newly created or modified Objects. EXIT is discussed in Chapter 6.
{ "pile_set_name": "StackExchange" }
Q: Generate XML from PHP via SQL i have a error when running this code .. i run fine when there is no special characteres in database. if its has special characters then i got the error please solve me i am very thankful. Following Error are occured when any special charachers in database like " ' & ? " i don't why those error come .. and i am not using DOM or XMLWrite just simple create the xml via file, and clerify 1 thing that CDDATA also not working for my code i check it. Please tell me some thing how could i make the xml with error less.. following are the code: $file= fopen("../xml/{$productID}.xml" , "w"); $_xml ="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"; $_XML = "<!DOCTYPE Server SYSTEM \"opt/pdos/etc/pdoslrd.dtd\">"; $_xml .="<productsnode>"; while ($row = mysql_fetch_array($productQuery, MYSQL_ASSOC)) { $_xml .=" <product>"; $_xml .=" <productID>" . $row['productID'] . "</productID>"; $_xml .=" <productName>" . htmlspecialchars($row['productName']) . "</productName>"; $_xml .=" <productDescription>" . htmlspecialchars($row['productDescription']) . "</productDescription>"; $_xml .=" <productPicture>" . htmlspecialchars($row['productPic']) . "</productPicture>"; $_xml .=" <category>"; $_xml .=" <categoryID>" . $row['categoryID'] . "</categoryID>"; $_xml .=" <categoryName>" . htmlspecialchars($row['categoryName']) . "</categoryName>"; $_xml .=" <categoryDescription>" . htmlspecialchars($row['categoryDiscription']) . "</categoryDescription>"; $_xml .=" <categoryPicture>" . htmlspecialchars($row['categoryPic']) . "</categoryPicture>"; $_xml .=" <subCategory>"; $_xml .=" <subCategoryID>" . $row['subCategoryID'] . "</subCategoryID>"; $_xml .=" <subCategoryName>" . htmlspecialchars($row['subCategoryName']) . "</subCategoryName>"; $_xml .=" <subCategoryDetail>" . htmlspecialchars($row['subCategoryDescription']) . "</subCategoryDetail>"; $_xml .=" </subCategory>"; $_xml .=" </category>"; $_xml .=" </product>"; } $_xml .="</productsnode>"; fwrite($file, $_xml); fclose($file); A: Special chars are illegal in xml so you need to wrap everything between CDATA tags eg: $_xml .=" <subCategoryName><![CDATA[" . htmlspecialchars($row['subCategoryName']) . "]]></subCategoryName>"; read more at -> http://www.w3schools.com/xml/xml_cdata.asp your code should be something like: $_xml .=" <product>"; $_xml .=" <productID><![CDATA[" . $row['productID'] . "]]></productID>"; $_xml .=" <productName><![CDATA[" . htmlspecialchars($row['productName']) . "]]></productName>"; $_xml .=" <productDescription><![CDATA[" . htmlspecialchars($row['productDescription']) . "]]></productDescription>"; $_xml .=" <productPicture><![CDATA[" . htmlspecialchars($row['productPic']) . "]]></productPicture>"; $_xml .=" <category>"; $_xml .=" <categoryID><![CDATA[" . $row['categoryID'] . "]]></categoryID>"; $_xml .=" <categoryName><![CDATA[" . htmlspecialchars($row['categoryName']) . "]]></categoryName>"; $_xml .=" <categoryDescription><![CDATA[" . htmlspecialchars($row['categoryDiscription']) . "]]></categoryDescription>"; $_xml .=" <categoryPicture><![CDATA[" . htmlspecialchars($row['categoryPic']) . "]]></categoryPicture>"; $_xml .=" <subCategory>"; $_xml .=" <subCategoryID><![CDATA[" . $row['subCategoryID'] . "]]></subCategoryID>"; $_xml .=" <subCategoryName><![CDATA[" . htmlspecialchars($row['subCategoryName']) . "]]></subCategoryName>"; $_xml .=" <subCategoryDetail><![CDATA[" . htmlspecialchars($row['subCategoryDescription']) . "]]></subCategoryDetail>"; $_xml .=" </subCategory>"; $_xml .=" </category>"; $_xml .=" </product>"; If that doesn't work it means there is something else, I suggest you copy the error you get and put it in your answer and maybe take a screenshot of what is stored in the database. If you want help give us more details
{ "pile_set_name": "StackExchange" }
Q: Show byte representation of generic type I am new to Rust. I would like to know any better way of doing this and if it can be done preferably with safe code. use std::mem; use std::mem::size_of; fn show_byte <T> ( element: T) { let array: * mut u8 = unsafe{ mem::transmute(&element) }; for i in (0.. size_of::<T>()) { let current = (array as usize + i) as *mut u8; print!("{:X}", unsafe { *current }); } } fn main() { show_byte(-1i64); } A: I am not aware of any safe method in the standard library to do this, so we need some unsafe code. In your code, you have two unsafe blocks. However, the first one is unnecessary: you can use as to perform the cast, but you need two consecutive casts, because we can't cast from &T to *mut u8 directly. Actually, you should use *const u8 here instead, since you don't actually mutate the referent. So, instead of mem::transmute, you can write: let array = &element as *const T as *const u8; If you really need a *mut u8, then you'd need to define element as mut and write &mut element instead of &element. However, I would do this differently. I'd write a function to turn a &T into a slice of bytes (&[u8]), which would encapsulate the only unsafe operation of the program. Then, we can use a simple for loop on that slice to print each byte. use std::mem; use std::slice; fn bytes_of<T>(value: &T) -> &[u8] { unsafe { slice::from_raw_parts( value as *const T as *const u8, mem::size_of::<T>()) } } fn show_as_bytes<T>(element: T) { for b in bytes_of(&element) { print!("{:X}", b); } } fn main() { show_as_bytes(-1i64); } Note that the bytes_of function plays a very important role that would be lost if it was inlined (by hand): the lifetime of the returned byte slice is tied to the lifetime of the input parameter. It's as if it was written thus: fn bytes_of<'a, T>(value: &'a T) -> &'a [u8] { // ... } If the function's body was inlined, the slice returned by slice::from_raw_parts would be unconstrained, and the compiler wouldn't be able to report an error if the slice accidentally outlived the data it references, causing subtle memory errors at runtime. Bonus: Here's how I would format your original code (note the changes to whitespace and the removal of parentheses). use std::mem::size_of; fn show_byte<T>(element: T) { let array: *mut u8 = unsafe { mem::transmute(&element) }; for i in 0..mem::size_of::<T>() { let current = (array as usize + i) as *mut u8; print!("{:X}", unsafe { *current }); } } fn main() { show_byte(-1i64); }
{ "pile_set_name": "StackExchange" }
Q: Range hood - not powerful enough to clear smoke? Whenever I sear steak (or cook anything on high heat), despite having our range hood on the highest setting, the smoke alarms always go off and the entire house smells pretty bad for several hours. Aside from changing my cooking habits, I was wondering if there's anything else I can do to improve this situation. I am totally willing to replace our hood if need be, but I don't want to make an investment only to find out it doesn't actually change anything. Our hood is currently a 36" under-cabinet rated at 400 CFM. We have a standard gas stove with 4 burners. Our kitchen is an "open space" concept though meaning it's kinda merged with the living room in the same space. The exhaust is supposed to go outside. Would a higher CFM hood "fix" the issue? Any other recommendations to what I could check? A: As many have mentioned the exhaust duct needs to be sized properly, I have seen folks spend a lot on higher cfm fans that did no better because the root problem was the home was sealed so no air could get in to efficiently allow the hood to do its job. Try opening a window and see if the hood works better. If no change the duct may be two small, if the hood works with the window open you have a cheap fix. More expensive methods involve pressure switches and make up air from outside. A: From the comments: I haven't replaced the charcoal filters in several years That is very possibly the key right there. Just like a clothes dryer won't work properly if the lint trap is clogged, and just like a HVAC system won't work properly if the air filter is clogged, and just like your car engine won't work properly if the air filter is clogged, your exhaust fan will not work properly if the filter is clogged. An exhaust fan can have two types of filters: Grease filter - This is designed to catch grease and particulates to prevent them from going into the effectively uncleanable (and therefore dangerous with grease accumulation) ductwork. They should be cleaned or replaced periodically. Charcoal filter - This is designed to filter odors from the air. While it is not designed as a grease/particulate filter, if the grease and particulates are not filtered out elsewhere then they can clog up the charcoal filter. So clean or replace any/all filters you can find! Then see if things are improved. Also as noted in the comments: Charcoal filters are only used when venting to outside is not possible. I don’t think your unit is attached to an exterior duct. I agree that generally charcoal filters are for venting inside - the concept is that there is no point in spending money to filter out odors if you are exhausting the air containing the odors to the outside. But I have seen charcoal filters in other configurations too, so that is not an absolute guarantee that you are not exhausting to the outside.
{ "pile_set_name": "StackExchange" }
Q: Probability with Random.Next() I want to write a lottery draw program which needs to randomly choose 20000 numbers from 1-2000000 range. The code is as below: Random r = New Random(seed); //seed is a 6 digits e.g 123456 int i=0; while(true){ r.Next(2000000); i++; if(i>=20000) break; } My questions are: Can it make sure the same possibility of all the numbers from 1 to 2000000? Is the upper bound 2000000 included in the r.Next()? Any suggestion? A: The .NET Random class does a fairly good job of generating random numbers. However be aware that if you seed it with the same number you'll get the same "random" numbers each time. If you don't want this behavior don't provide a seed. If you're after much more random number generator than the built in .NET one then take a look at random.org. It's one of the best sites out there for getting true random numbers - I believe there's an API. Here's a quote from their site: RANDOM.ORG offers true random numbers to anyone on the Internet. The randomness comes from atmospheric noise, which for many purposes is better than the pseudo-random number algorithms typically used in computer programs. People use RANDOM.ORG for holding drawings, lotteries and sweepstakes, to drive games and gambling sites, for scientific applications and for art and music. The service has existed since 1998 and was built by Dr Mads Haahr of the School of Computer Science and Statistics at Trinity College, Dublin in Ireland. Today, RANDOM.ORG is operated by Randomness and Integrity Services Ltd. Finally Random.Next() is exlusive so the upper value you supply will never be called. You may need to adjust your code appropriately if you want 2000000 to be in there.
{ "pile_set_name": "StackExchange" }
Q: Scheduling the Storing of BO Reports in PDF Format Is it possible in BusinessObjects 4.0/4.1 to do the following: Create a report in PDF format Transfer and store the report on some Windows Share folder Schedule this process It this is possible, can anyone give short guidelines on how to do it? Thanks! A: Sure, that's basic scheduling functionality. From Launchpad, right-click on the report and hit "Schedule". Click the recurrence tab to set the scheduling recurrence. Click the Formats tab and select Acrobat. Click the Destinations tab and select File System. One important note on Destinations -- you can optionally enter the Windows user name and password that will be used to connect to the file share when the report is generated. You can leave this blank, in which case the BO server will connect to the file share as the account that BO runs as (that is, the user name that the SIA service runs as). In this case, the service account must have r/w permission to the file share. On the other hand, if you enter credentials manually, you need to make sure that any recurring schedules get updated if/when you change the accounts password, else the account will quickly get locked out (I know from experience....) For more info, click the Help menu in Launchpad, then review the section on Scheduling Objects.
{ "pile_set_name": "StackExchange" }
Q: Modifying a JQuery expression <script type="text/javascript"> $(function() { $('#theEmail').keyup(function() { if (this.value.match(/[^a-zA-Z0-9 ]/g)) { this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, ''); } }); }); </script> What do I modify to ensure the expression allows me to enter "_" and "-" in the above script? A: Change both instances of this regular expression /[^a-zA-Z0-9 ]/ to /[^\-_a-zA-Z0-9 ]/ Although as far as I can tell, the initial .match test is completely unnecessary.
{ "pile_set_name": "StackExchange" }
Q: How many times does a DNS server need to sign? I have a question about DNSSEC and how many times a DNS server must sign or in other words, how many signatures are there in a day. I know that DNSSEC builds on a chain of trust starting at the root level. Now lets assume that I run a DNS server that covers a zone with 1 million domains and the TTL of each record is 1 hour. Furthermore, the zone changes once a week. How many new signatures are there in one day? I can think of the two possibilities below: there are new signatures only when the zone changes, i.e. around 1M / 7 = 143k signatures per day Every time the TTL expires, the record must be re-signed. This would lead to 1M * 24 = 24M signatures per day Which one of them is right (if any)? And if none of them, how and way is it? Thanks a lot! A: The DNS server is free to do it as often as it wants/needs: signatures liftetime is a policy issue, covered by a DPS (DNSSEC Policy Statement). You can find examples and good practices, but if a server wants to create signatures even on the fly, it can (see https://doc.powerdns.com/authoritative/dnssec/modes-of-operation.html "In PowerDNS live signing mode, signatures, as served through RRSIG records, are calculated on the fly, and heavily cached." or https://www.cloudflare.com/dns/dnssec/dnssec-complexities-and-considerations/ "Cloudflare’s DNSSEC implementation leverages ECDSA’s efficient signature generation to sign DNSSEC records on-the-fly.") Signatures in RRSIG records have two dates: a beginning of validity and an end. This has nothing to do with the TTL value, nor the zone changes (signatures will change even if the zone does not change). See for example in A Framework for DNSSEC Policies and DNSSEC Practice Statements section 4.6.5. "Signature Lifetime and Re-Signing Frequency" that mandates a good policy document to have: This subcomponent describes the life cycle of the Resource Record Signature (RRSIG) record. Now let us look at some published DPS: .BE 17.6 Signature Life-time and Resigning Frequency: The KSK signatures of the TLD zone DNSKEY RRset will have a validity period of 40 days. The ZSK signatures of the TLD zone authoritative data will have a validity period of 10 days (default TTL: 86400s aka 1 day) RIPE NCC We re-sign our zones daily with a signature lifetime of 30 days. (default TTL: 3600s aka 1 hour) .NL RR sets are signed with ZSKs with a validity period of fourteen days and are resigned every two days. Zone file generation and the signing of new records takes place every hour. (default TTL: 3600s) .COM The signing practice of the COM Zone is divided into quarterly continuous time cycles of approximately 90 days. Time cycles begin at the following dates each year: January 15th April 15th July 15th October 15th The time cycle will never be less than 90 days, except in emergency situations (in which a key has been compromised) or if Verisign decides to begin using different key lengths. (default TTL: 172800s aka 2 days) etc. Also, take into account this part from RFC 4035 (section 5.3.3): If the resolver accepts the RRset as authentic, the validator MUST set the TTL of the RRSIG RR and each RR in the authenticated RRset to a value no greater than the minimum of: o the RRset's TTL as received in the response; o the RRSIG RR's TTL as received in the response; o the value in the RRSIG RR's Original TTL field; and o the difference of the RRSIG RR's Signature Expiration time and the current time.
{ "pile_set_name": "StackExchange" }
Q: how can I know whether render reason is property changed or state changed in react hook function? I have a displayer component implemented by react hook. The displayer component receives a set of records by property named 'rows'. It has two buttons used to show previous or next one, so I use a state named 'index' represents the current row no. It is easy to show prev/next one by decrease or increase the state 'index'. But when its rows changed, I want reset index to zero. How can I get the right condition without saving a copy of the rows to compare them? interface row { id: number; name: string; } interface tableProps { rows: row[]; } const Shower: React.FC<tableProps> = (props) => { const [index, setIndex] = useState<number>(0); // when should I reset the index to zero when receiving a new property rows? return <div> <button disabled={!(index > 0)} onClick={() => setIndex(index - 1)}>Prev</button> <span>{props.rows[index].id}:{props.rows[index].name}</span> <button disabled={!(index + 1 < props.rows.length)} onClick={() => setIndex(index + 1)}>Prev</button> </div>; } A: You can use useEffect ...... import {useEffect} from 'react' .... useEffect(()=>{ setIndex(0) },[props.rows])
{ "pile_set_name": "StackExchange" }
Q: What is the purpose of DBs like CouchDB ? When they can provide beneficts over standard DB or Object like DBs With Ruby On Rails? I'am Starting a new App (Something like an AngelList + hacker news but local), and got thinking if I should join the wave and get a CouchDB or stay with the old School and proved to work relational DBs, or try Object oriented DBs. After studying a bit of how CouchDB works I don't see where It can be useful, looks harder to make connection between the "Documents" and also I cannot find how they can do BI with this Kind of DB since Data Minning would result in a lake of info in a complete mess. I think I am missing the key points of the paradigm What am I missing ? I bet most people and Amazon are right and I am wrong, but where ? Specially the benefits with Ruby On Rails Object Mapping ? I would like to have some BI and cross some info after I get a lot of users... so... A: Take a look at this post: Cassandra vs MongoDB vs CouchDB vs Redis vs Riak vs HBase comparison
{ "pile_set_name": "StackExchange" }
Q: Uniform Convergence of Power Series Let $\sum_{n=0}^\infty a_n \left( x-x_0 \right)^n$ be a power series that converges uniformly over all $x\in \mathbb R$. Prove there exists $N\in\mathbb N$ such that for all $n>N,\; a_n = 0$. I fail to see how this is true. From the radius of convergence formula $$\frac{1}{R}=0=\limsup_{n\rightarrow\infty}\sqrt[n]{\left|a_n\right|}$$ Now for all $n$ choose $a_n=\frac{1}{n^n}\neq0$ and we get $a_n>a_{n+1}$ so that $$\limsup_{n\rightarrow\infty}\sqrt[n]{\left|a_n\right|}=\lim_{n\rightarrow\infty}\frac{1}{n}=0$$ We therefore got a convergent series over all the reals, thus uniformly convergent in every $[a,b]\in \mathbb R$ contradicting the above statement... A: Suppose that a sequence $f_n(x)$ converges pointwise to the function $f(x)$ for all $x\in S$. NEGATION OF UNIFORM CONVERGENCE The sequence $f_n(x)$ fails to converge uniformly to $f(x)$ for $x\in S$ if there exists a number $\epsilon>0$ such that for all $N$, there exists an $n_0>N$ and a number $x\in S$ such that $|f_{n_0}(x)-f(x)|\ge \epsilon$. Now, let $f_n(x)=a_nx^n$ with $\lim_{n\to \infty}f_n(x)=0$ for all $x\in \mathbb{R}$. Certainly, either $a_n=0$ for all $n$ sufficiently large or for any number $N$ there exists a number $n_0>N$ such that $a_{n_0}\ne 0$. Suppose that the latter case holds. Now, taking $\epsilon=1$, we find that $$|a_{n_0}x^{n_0}|\ge \epsilon$$ whenever $|x|\ge |a_{n_0}|^{-1/n_0}$. And this negates the uniform convergence of $f_n(x)$. And inasmuch as the sequence $f_n(x)$ fails to uniformly converge to zero, then the series $\sum_{n=0}^\infty f_n(x)$ fails to uniformly converge. Note for the example for which $a_n=n^n$ we can take $x>1/n$. NOTE: If $a_n=0$ for all $n>N+1$, then we have $$\sum_{n=0}^\infty a_nx^n = \sum_{n=0}^N a_nx^n$$ which is a finite sum and there is no issue regarding convergence.
{ "pile_set_name": "StackExchange" }
Q: write a loop to represent each polynomial from an array for n polynomials import csv import numpy from sympy import * import numpy as np from numpy import * import json reader=csv.reader(open("/Users/61/Desktop/pythonlearning/generator1.csv","rU"),delimiter=',') a=list(reader) result=numpy.array(a) print a b = [] for n in range(3): b.append(a[n+1][0:3]) print b e = np.array(b) f = e.astype(np.float) print f x = Symbol("x") y = Symbol("y") coeffs = f F1 = numpy.poly1d(f[0]) F12 = np.polyder(F1) print F12 F2 = numpy.poly1d(f[1]) F22 = np.polyder(F2) print F22 F3 = numpy.poly1d(f[2]) F32 = np.polyder(F3) print F32 this is my coding and f is a array of numbers like this:[[ 9.68000000e-04 6.95000000e+00 7.49550000e+02] [ 7.38000000e-04 7.05100000e+00 1.28500000e+03] [ 1.04000000e-03 6.53100000e+00 1.53100000e+03]]. Basically, I want to assign the value of f to form polynomials, and then differentiate the polynomials. The results it like this 0.001936 x + 6.95 0.001476 x + 7.051 0.00208 x + 6.531 My question is how could write a loop for Fn if instead of 3 polynomials, I have n polynomials instead. How could I write a loop to obtain the differentiation for the n polynomials and can easy use the polynomials with different name of it. eg, F1 represent the first polynomial and F2 represent the second and so on. i tried sth like this, but it doesnt work i = 1 if i < 3: F(i)=numpy.poly1d(f[i-1]) else: i = i+1 A: You need to use a loop to deal with a variable number of polynomials and a data structure to store them. Try using a dictionary, iterating using a for loop. numberPolynomials = 3 F = {} for n in range(1, numberPolynomials+1): F[n] = np.poly1d(f[n-1]) F[(n, 2)] = np.polyder(F[n]) print F[(n, 2)] Now you can refer to the polynomial not as F1, F2, etc. but as F[1], F[2], etc. For what you had called F12, F22, F32 would then be F[(1,2)], F[(2,2)], F[(3,2)]. Though, if you aren't going to be using the originals you should overwrite them and probably just use a list. This is assuming, you change the 3x imports of numpy to: import numpy as np
{ "pile_set_name": "StackExchange" }
Q: MySQLi Query error Couldn't fetch mysqli I am getting the following error when I'm trying the code down below: Error: Warning: mysqli::mysqli(): (HY000/2002): No such file or directory in /volume1/web/index.php on line 4 Warning: mysqli::query(): Couldn't fetch mysqli in /volume1/web/index.php on line 7 Warning: main(): Couldn't fetch mysqli in /volume1/web/index.php on line 23 The code that I am using.. <?php // Connect to the DB $mysqli = NEW MySQLi("localhost","root","","dbproject"); //Query the DB $resultSet = $mysqli->query("SELECT * FROM clients"); // Count the returned rows if($resultSet->num_rows != 0) { while($rows = $resultSet->fetch_assoc()) { $id = $rows['id']; $fname = $rows['firstname']; $lname = $rows['lastname']; $country = $rows['country']; echo "<p>ID: " .$id. " <br /> Name: ".$fname." ".$lname. "<br /> Country: ".$country." </p>"; } // Turn the results into an array // Display the results } else{ echo $mysqli->error; } ?> As the error reffers to line 4, 7 and 23 Line 4: $mysqli = NEW MySQLi("localhost","root","","dbproject"); Line 7: $resultSet = $mysqli->query("SELECT * FROM clients"); Line 23: echo $mysqli->error; Can someone please help me with this? Many thanks! A: The solution: I changed line 4 from: $mysqli = NEW MySQLi("localhost","root","","dbproject"); to $mysqli = NEW MySQLi("localhost:3307","root","","dbproject"); Adding the port somehow fixed it.
{ "pile_set_name": "StackExchange" }
Q: Is it always safe to assume that a integral is zero if it has equal bounds? I'm still a "newbie" on mathematical analysis and I stumbled upon this integral. This is my solution: $$\int_0^{2\pi}{\frac{x\cos x}{1+\sin^2x}dx}$$ Now I substitued with $t=\sin x$ $$=\int_0^0{\frac{a\sin x}{1+t^2}dt} = 0$$ But I found that the integral $\displaystyle\int_0^\pi{\frac{\cos x}{\sin^2 x}dx}$ which I solved by the same substitution is not $0$ but it is indeterminate. Not sure if this is right. A: The problem is that you cannot directly make a substitution which is not one-to-one on the domain of interest. Thus you can take $t=\sin(x)$, but to do so you need to split the domain between $[0,\pi/2],[\pi/2,3\pi/2],[3\pi/2,2\pi]$. This condition of being one-to-one can actually be relaxed. Indeed, in general $\int_a^b f(g(x)) g'(x) dx = \int_{g(a)}^{g(b)} f(t) dt$; this is just the fundamental theorem of calculus and the chain rule. But in substitution you need to be careful about using the right $g'(x)$ throughout the entire new interval, which in general amounts to picking the right "inverse" $x(t)$. For example, naively, you might compute $\int_{-1}^1 x^4 dx = \frac{1}{2} \int_1^1 u^{3/2} du$ with $u=x^2$. But in fact the correct way to do this substitution you find $\int_{-1}^1 x^4 dx = \frac{1}{2} \int_1^0 -u^{3/2} du + \frac{1}{2} \int_0^1 u^{3/2} du$ which is nonzero. This happens because when you pass through $u=0$ you need to switch from one local inverse of $x^2$, namely $-\sqrt{u}$, to the other, namely $\sqrt{u}$. A: Hidden parity trick: $$\begin{eqnarray*}\int_{0}^{2\pi}\frac{x\cos x}{1+\sin^2 x}\,dx = -\int_{-\pi}^{\pi}\frac{(z+\pi)\cos z}{1+\sin^2 z}\,dx &\color{red}{=}& -2\pi\int_{0}^{\pi}\frac{\cos z}{1+\sin^2 z}\,dz\\[0.2cm]&=&-2\pi\,\left.\arctan(\sin z)\right|_{0}^{\pi}\\&=&\color{red}{0}.\end{eqnarray*}$$
{ "pile_set_name": "StackExchange" }
Q: Is there a name for the parts that are connected by a conjunction? For example, the parts of a sentence that a preposition operates on are called "prepositional objects". I was wondering if there's a name for the parts that are connected by a conjunction? E.g. in "apples and oranges", would we say "apple" and "orange" are the objects of "and"? A: They are its coordinands; see http://www.glottopedia.org/index.php/Coordinand. (That page also lists some alternatives, namely term, member, coordinated unit, coordinate, and conjunct.) A: elements: when a coordinating conjunction is used to connect all the elements in a series, a comma is not used: Presbyterians and Methodists and Baptists are the prevalent Protestant congregations in Oklahoma. equivalent sentence elements: Correlative conjunctions always appear in pairs -- you use them to link equivalent sentence elements. elements: A coordinating conjunction joining three or more words, phrases, or subordinate clauses creates a series and requires commas between the elements.
{ "pile_set_name": "StackExchange" }
Q: rails application not deploying to heroku (application error message) I am trying to deploy a simple hello world Rails application to Heroku but am getting an application error. The weird thing is it worked fine for my other Rails application but it doesn't work for this one even though I made the same changes to both, including having the same Gemfile, controller action and root route. It works fine locally but not when I deploy it. http://calm-oasis-3599.herokuapp.com/ This is the error output when I run heroku run rails console and heroku logs. Any help with finding out why I am getting this error is greatly appreciated. Here's my Gemfile.lock: GEM remote: https://rubygems.org/ specs: actionmailer (4.2.4) actionpack (= 4.2.4) actionview (= 4.2.4) activejob (= 4.2.4) mail (~> 2.5, >= 2.5.4) rails-dom-testing (~> 1.0, >= 1.0.5) actionpack (4.2.4) actionview (= 4.2.4) activesupport (= 4.2.4) rack (~> 1.6) rack-test (~> 0.6.2) rails-dom-testing (~> 1.0, >= 1.0.5) rails-html-sanitizer (~> 1.0, >= 1.0.2) actionview (4.2.4) activesupport (= 4.2.4) builder (~> 3.1) erubis (~> 2.7.0) rails-dom-testing (~> 1.0, >= 1.0.5) rails-html-sanitizer (~> 1.0, >= 1.0.2) activejob (4.2.4) activesupport (= 4.2.4) globalid (>= 0.3.0) activemodel (4.2.4) activesupport (= 4.2.4) builder (~> 3.1) activerecord (4.2.4) activemodel (= 4.2.4) activesupport (= 4.2.4) arel (~> 6.0) activesupport (4.2.4) i18n (~> 0.7) json (~> 1.7, >= 1.7.7) minitest (~> 5.1) thread_safe (~> 0.3, >= 0.3.4) tzinfo (~> 1.1) arel (6.0.3) binding_of_caller (0.7.2) debug_inspector (>= 0.0.1) builder (3.2.2) byebug (8.2.0) coffee-rails (4.1.0) coffee-script (>= 2.2.0) railties (>= 4.0.0, < 5.0) coffee-script (2.4.1) coffee-script-source execjs coffee-script-source (1.10.0) debug_inspector (0.0.2) erubis (2.7.0) execjs (2.6.0) globalid (0.3.6) activesupport (>= 4.1.0) i18n (0.7.0) jbuilder (2.3.2) activesupport (>= 3.0.0, < 5) multi_json (~> 1.2) jquery-rails (4.0.5) rails-dom-testing (~> 1.0) railties (>= 4.2.0) thor (>= 0.14, < 2.0) json (1.8.3) loofah (2.0.3) nokogiri (>= 1.5.9) mail (2.6.3) mime-types (>= 1.16, < 3) mime-types (2.6.2) mini_portile (0.6.2) minitest (5.8.2) multi_json (1.11.2) nokogiri (1.6.6.3) mini_portile (~> 0.6.0) pg (0.17.1) rack (1.6.4) rack-test (0.6.3) rack (>= 1.0) rails (4.2.4) actionmailer (= 4.2.4) actionpack (= 4.2.4) actionview (= 4.2.4) activejob (= 4.2.4) activemodel (= 4.2.4) activerecord (= 4.2.4) activesupport (= 4.2.4) bundler (>= 1.3.0, < 2.0) railties (= 4.2.4) sprockets-rails rails-deprecated_sanitizer (1.0.3) activesupport (>= 4.2.0.alpha) rails-dom-testing (1.0.7) activesupport (>= 4.2.0.beta, < 5.0) nokogiri (~> 1.6.0) rails-deprecated_sanitizer (>= 1.0.1) rails-html-sanitizer (1.0.2) loofah (~> 2.0) rails_12factor (0.0.2) rails_serve_static_assets rails_stdout_logging rails_serve_static_assets (0.0.4) rails_stdout_logging (0.0.4) railties (4.2.4) actionpack (= 4.2.4) activesupport (= 4.2.4) rake (>= 0.8.7) thor (>= 0.18.1, < 2.0) rake (10.4.2) rdoc (4.2.0) json (~> 1.4) sass (3.4.19) sass-rails (5.0.4) railties (>= 4.0.0, < 5.0) sass (~> 3.1) sprockets (>= 2.8, < 4.0) sprockets-rails (>= 2.0, < 4.0) tilt (>= 1.1, < 3) sdoc (0.4.1) json (~> 1.7, >= 1.7.7) rdoc (~> 4.0) spring (1.4.3) sprockets (3.4.0) rack (> 1, < 3) sprockets-rails (2.3.3) actionpack (>= 3.0) activesupport (>= 3.0) sprockets (>= 2.8, < 4.0) sqlite3 (1.3.11) thor (0.19.1) thread_safe (0.3.5) tilt (2.0.1) turbolinks (2.5.3) coffee-rails tzinfo (1.2.2) thread_safe (~> 0.1) uglifier (2.7.2) execjs (>= 0.3.0) json (>= 1.8.0) web-console (2.2.1) activemodel (>= 4.0) binding_of_caller (>= 0.7.2) railties (>= 4.0) sprockets-rails (>= 2.0, < 4.0) PLATFORMS ruby DEPENDENCIES byebug coffee-rails (~> 4.1.0) jbuilder (~> 2.0) jquery-rails pg (= 0.17.1) rails (= 4.2.4) rails_12factor (= 0.0.2) sass-rails (~> 5.0) sdoc (~> 0.4.0) spring sqlite3 turbolinks uglifier (>= 1.3.0) web-console (~> 2.0) BUNDLED WITH 1.10.6 Here's the spring gem file #!/usr/bin/env ruby # This file loads spring without using Bundler, in order to be fast. # It gets overwritten when you run the `spring binstub` command. unless defined?(Spring) require 'rubygems' require 'bundler' if (match = Bundler.default_lockfile.read.match(/^GEM$.*?^ (?: )*spring \((.*?)\)$.*?^$/m)) Gem.paths = { 'GEM_PATH' => [Bundler.bundle_path.to_s, *Gem.path].uniq } gem 'spring', match[1] require 'spring/binstub' end end A: You may not need to include spring under test group as seen here Keep it under the development group alone. Also the version of spring in your gemlock is 1.4.3 and heroku is complaining about 1.4.2. Maybe you need to explicitly specify a version in your gemfile, delete your Gemfile.lock(which should not always happen), run bundle again, commit your changes and redeploy.
{ "pile_set_name": "StackExchange" }
Q: Compare NSArray elements to NSNumber I'm new to objective c. I am getting my data from an NSArray and want to return value according to some condition. My code is: NSArray *myData; NSNumber *day = 5; myData = [NSArray arrayWithObjects: @"5", nil]; for (int i = 0; i < [myData count]; i++) { if(day == myData[0]){ NSLog(@"date in valueForDay %@ ", da ); return 3; } } Above code doesn't execute my statements (NSLog and return one). But if i statically compare day with any number it got executed. Like: NSArray *myData; NSNumber *day = 5; myData = [NSArray arrayWithObjects: @"5", nil]; for (int i = 0; i < [myData count]; i++) { if(day == 5){ NSLog(@"date in valueForDay %@ ", da ); return 3; } } can anyone please tell me where i'm doing wrong? A: You have created array with string value not with number value. That's why object from your array is "5" which is not equal to integer 5. Make your array as number array. myData = [NSArray arrayWithObjects: @5, nil]; Also instead of for loop you can simply use indexOfObject to check array having object or not. NSInteger index = [myData indexOfObject: day]; if(index != NSNotFound) { return 3; }
{ "pile_set_name": "StackExchange" }
Q: Getting pixel data on setInterval with canvas I want to build an animated alphabet, made up of particles. Basically, the particles transform from one letter shape to another. My idea is to fill the letters as text on canvas real quickly (like for a frame), get the pixel data and put the particles to the correct location on setInterval. I have this code for scanning the screen right now: var ctx = canvas.getContext('2d'), width = ctx.canvas.width, height = ctx.canvas.height, particles = [], gridX = 8, gridY = 8; function Particle(x, y) { this.x = x; this.y = y; } // fill some text ctx.font = 'bold 80px sans-serif'; ctx.fillStyle = '#ff0'; ctx.fillText("STACKOVERFLOW", 5, 120); // now parse bitmap based on grid var idata = ctx.getImageData(0, 0, width, height); // use a 32-bit buffer as we are only checking if a pixel is set or not var buffer32 = new Uint32Array(idata.data.buffer); // using two loops here, single loop with index-to-x/y is also an option for(var y = 0; y < height; y += gridY) { for(var x = 0; x < width; x += gridX) { //buffer32[] will have a value > 0 (true) if set, if not 0=false if (buffer32[y * width + x]) { particles.push(new Particle(x, y)); } } } // render particles ctx.clearRect(0, 0, width, height); particles.forEach(function(p) { ctx.fillRect(p.x - 2, p.y - 2, 4, 4); // just squares here }) But this way I am only showing one word, without any changes throughout the time. Also, I want to set up initially like 200 particles and reorganise them based on the pixel data, not create them on each scan.. How would you rewrite the code, so on every 1500ms I can pass a different letter and render it with particles? A: Hopefully the different parts of this code should be clear enough : There are particles, that can draw and update, fillParticle will spawn particles out of a text string, and spawnChars will get a new part of the text rendered on a regular basis. It is working quite well, play with the parameters if you wish, they are all at the start of the fiddle. You might want to make this code cleaner, by avoiding globals and creating classes. http://jsbin.com/jecarupiri/1/edit?js,output // -------------------- // parameters var text = 'STACKOVERFLOW'; var fontHeight = 80; var gridX = 4, gridY = 4; var partSize = 2; var charDelay = 400; // time between two chars, in ms var spead = 80; // max distance from start point to final point var partSpeed = 0.012; // -------------------- var canvas = document.getElementById('cv'), ctx = canvas.getContext('2d'), width = ctx.canvas.width, height = ctx.canvas.height, particles = []; ctx.translate(0.5,0.5); // -------------------- // Particle class function Particle(startX, startY, finalX, finalY) { this.speed = partSpeed*(1+Math.random()*0.5); this.x = startX; this.y = startY; this.startX = startX; this.startY = startY; this.finalX =finalX; this.finalY =finalY; this.parameter = 0; this.draw = function() { ctx.fillRect(this.x - partSize*0.5, this.y - partSize*0.5, partSize, partSize); }; this.update = function(p) { if (this.parameter>=1) return; this.parameter += partSpeed; if (this.parameter>=1) this.parameter=1; var par = this.parameter; this.x = par*this.finalX + (1-par)*this.startX; this.y = par*this.finalY + (1-par)*this.startY; }; } // -------------------- // Text spawner function fillParticle(text, offx, offy, spread) { // fill some text tmpCtx.clearRect(0,0,tmpCtx.canvas.width, tmpCtx.canvas.height); tmpCtx.font = 'bold ' + fontHeight +'px sans-serif'; tmpCtx.fillStyle = '#A40'; tmpCtx.textBaseline ='top'; tmpCtx.textAlign='left'; tmpCtx.fillText(text, 0, 0); // var txtWidth = Math.floor(tmpCtx.measureText(text).width); // now parse bitmap based on grid var idata = tmpCtx.getImageData(0, 0, txtWidth, fontHeight); // use a 32-bit buffer as we are only checking if a pixel is set or not var buffer32 = new Uint32Array(idata.data.buffer); // using two loops here, single loop with index-to-x/y is also an option for(var y = 0; y < fontHeight; y += gridY) { for(var x = 0; x < txtWidth; x += gridX) { //buffer32[] will have a value > 0 (true) if set, if not 0=false if (buffer32[y * txtWidth + x]) { particles.push(new Particle(offx + x+Math.random()*spread - 0.5*spread, offy + y+Math.random()*spread - 0.5*spread, offx+x, offy+y)); } } } return txtWidth; } var tmpCv = document.createElement('canvas'); // uncomment for debug //document.body.appendChild(tmpCv); var tmpCtx = tmpCv.getContext('2d'); // -------------------------------- // spawn the chars of the text one by one var charIndex = 0; var lastSpawnDate = -1; var offX = 30; var offY = 30; function spawnChars() { if (charIndex>= text.length) return; if (Date.now()-lastSpawnDate < charDelay) return; offX += fillParticle(text[charIndex], offX, offY, spead); lastSpawnDate = Date.now(); charIndex++; } // -------------------------------- function render() { // render particles particles.forEach(function(p) { p.draw(); }); } function update() { particles.forEach(function(p) { p.update(); } ); } // -------------------------------- // animation function animate(){ requestAnimationFrame(animate); ctx.clearRect(0, 0, width, height); render(); update(); // spawnChars(); } // launch : animate();
{ "pile_set_name": "StackExchange" }
Q: C# Deriving a class from more than one abstract class I created two abstract classes and tried to create a class that inherits from both. But I get an error message. abstract class AbstractClassOne { public abstract void ShowMessage(); public abstract void DisplayName(); } abstract class AbstractClassTwo { public abstract void ShowMessage(); public abstract void DisplayPlace(); } class DerivedClass : AbstractClassOne, AbstractClassTwo // here under AbstractClassTwo it shows the error "cannot have multiple base classes:" { } So a class can only derive from one abstract class? If can derive from more than one abstract class, then what happens if both classes define the same method, as is the case above (abstract class one and two both have a method showmessage(), so which one will be in the derived class)? A: In C# it's not allowed to inherit from more than one class. To do what you want here, you need to use interfaces. abstract class AbstractClassOne { public abstract void ShowMessage(); public abstract void DisplayName(); } Interface IClassTwo { void ShowMessage(); void DisplayPlace(); } class DerivedClass : AbstractClassOne, IClassTwo { } A: Multiple inheritance is not allowed by C# but it is allowed by C++. To answer your question regarding the ShowMessage() method that is a known problem in c++ with multiple inheritance called "The Diamond Problem". see: http://en.wikipedia.org/wiki/Multiple_inheritance So basically you will have to excitability state to which method you are refereeing when calling it e.g. ParentA::ShowMessage() if you want to have a type that is polymorphic to 2 other types than you should create two separate interfaces and implement them. and if you want to reuse the same methods than you will have to use compositions. Interfaces example: public interface ISomeInterface { public void ShowMessage(); public void DisplayName(); } public class ClassOne : ISomeInterface { public void ShowMessage() { //implementation } public void DisplayName() { //implementation } } public class ClassTwo : ISomeInterface { public void ShowMessage() { //implementation } public void DisplayPlace() { //implementation } } Interface with reusable Show Message Method using composition: public class ClassTwo : ISomeInterface { private ISomeInterface _MyPrivateReusableComponent = new ClassOne(); public void ShowMessage() { _MyPrivateReusableComponent.ShowMessage() } public void DisplayPlace() { _MyPrivateReusableComponent.DisplayName() //implementation } }
{ "pile_set_name": "StackExchange" }
Q: for loop output in c when maximum value is neative one and assigned value is positive one why output is blank and why loop will run for(i=1;i<=-10;i++) printf("*"); if i=-1 or i= -10 doesn't matter its run once why A: Your loop will iterate as long as i is less than or equal to -10. As long as i is larger than -10 that condition will never be true and the loop will not iterate, not even once. If i == -10 to begin with, the loop will iterate once. Then you do i++ which increases the value of i? to -9 and the condition becomes false, and the loop won't iterate again. Note that the above is only true iff i is a signed integer. If i is an unsigned integer things becomes very different. Then the -10 will be converted to an unsigned value, and that value will become very large, and the loop will iterate a lot.
{ "pile_set_name": "StackExchange" }
Q: Upload and Store Image File in Database with description using PHP and MySQL I have been trying to uload image to a datebase with descriptionof the image and then get the data off the database and put the description uder the image i am new to php i cant find info the internet i have the uploaded to the datebase and displaying i just cant get the descriptiono working thanks for the help index.php <form action="upload.php" method="post" enctype="multipart/form-data"> Select Image File to Upload: <input type="file" name="file"> <br><input type="text" name="description" placeholder="description of your image"> <input type="submit" name="submit" value="Upload"> </form> upload.php // Create database connection $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); // Check connection if ($db->connect_error) { die("Connection failed: " . $db->connect_error); } $statusMsg = ''; // File upload path $targetDir = "upload/"; $fileName = basename($_FILES["file"]["name"]); $targetFilePath = $targetDir . $fileName; $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION); if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){ // Allow certain file formats $allowTypes = array('jpg','png','jpeg','gif','pdf'); if(in_array($fileType, $allowTypes)){ // Upload file to server if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){ // Insert image file name into database $insert = $db->query("INSERT into images (file_name, uploaded_on) VALUES ('".$fileName."', NOW())"); if($insert){ $statusMsg = "The file ".$fileName. " has been uploaded successfully."; }else{ $statusMsg = "File upload failed, please try again."; } }else{ $statusMsg = "Sorry, there was an error uploading your file."; } }else{ $statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.'; } }else{ $statusMsg = 'Please select a file to upload.'; } // Display status message echo $statusMsg; ?> A: Your code is not saving the description to the database. That's why you can't show it. First you need to add a new column description inside table images. After that, you must get the description sent in the request, as you did with $fileName $description = $_POST['description']; You can now insert into images: $insert = $db->query("INSERT INTO images (file_name, description, uploaded_on) VALUES ('".$fileName."', '".$description."', NOW())");
{ "pile_set_name": "StackExchange" }