text
stringlengths
175
47.7k
meta
dict
Q: Is there an alternative to Runtime.getRuntime().exec() Just wondering, if there is something better, newer, safer, faster, etc than Runtime.getRuntime().exec(). I want to run another process from my application on linux, and this is the only way i know how. Would be nice to have an alternative. A: How about ProcessBuilder? A bit more: Introduced in Java 1.5, allows you to gain more control on the process environment - set the working directory, let you redirect the error stream to the input stream (from java POV) and a few more things. From Oracle's site: ProcessBuilder - The new ProcessBuilder class provides a more convenient way to invoke subprocesses than does Runtime.exec. In particular, ProcessBuilder makes it easy to start a subprocess with a modified process environment (that is, one based on the parent's process environment, but with a few changes).
{ "pile_set_name": "StackExchange" }
Q: Macro to add formulas where the are multiple rows above I've been doing the company financial summaries, I've been doing a lot of the leg work manually (sorting by product, company, etc.). The problem is I've been using the below macro to add in two rows, so I can work out spends per customer. Now what I want to do is add in those breaks, but in the first blank row, I want to copy and paste the values from the cells above for columns A, B and C. In column D and E I would like to sum the contiguous cells above, while column F should work out the difference between the calculated values in D & E (so =D-E), while column G should work out the % (=(Fx/Dx)*100). If there is a way to do this only if there is more than one row above all the better. The code that I've been using so far is below, which gives me the line breaks I've been using. But with my RSI, copying the requisite cells and doing all the formulas manually isn't helping. Sub AddBlankRows() ' Dim iRow As Integer, iCol As Integer Dim oRng As Range Set oRng = Range("b1") iRow = oRng.Row iCol = oRng.Column Do ' If Cells(iRow + 1, iCol) <> Cells(iRow, iCol) Then Cells(iRow + 1, iCol).EntireRow.Insert Shift:=x1Down Cells(iRow + 1, iCol).EntireRow.Insert Shift:=x1Down iRow = iRow + 3 Else iRow = iRow + 1 End If ' Loop While Not Cells(iRow, iCol).Text = "" ' End Sub Example data What I'm aiming for I'm a complete novice in this, so any help would be appreciated. A: An alternative solution you might want to consider is to keep the data in its original format and add a total row. If the data is a table, you can do this by selecting Total Row from the Design tab; otherwise, you can use the SUBTOTAL() formula and auto-filtering to achieve the same result. I've used tables for my example. Without filtering, you get the results for the whole data set: When you filter on a particular value of Account or Customer, it instead summarises the values for those rows only:
{ "pile_set_name": "StackExchange" }
Q: compilation error in c statements I am trying to run this code.this code runs successfully.But when i change variables to constant numbers i get compilation error. My code that works fine: int a =5,b=6,c=7; int d; d = a,b,c; printf("%d",d); as i run the code its output is 5. but when i run this segment of code: d = 2,6,7; printf("%d",d); i get compilation error.I tried i on other compiler also. But the error still exists. What i am doing wrong. A: Your first code use the variables and assignment d = a and b and c just as expression there, so run the code: int main(int argc, char const *argv[]) { int a =5,b=5,c=7; int d; d = a,b,c+1; printf("%d",d); return 0; } You get 5, b and c+1 just valued and put them there useless.But if you run this code which includes comma expression: int main(int argc, char const *argv[]) { int a =5,b=5,c=7; int d; d = (a,b,c+1); printf("%d",d); return 0; } You get 8 as the last one valued expression. You can use the number play as an expression with (): int main(int argc, char const *argv[]) { int a =5,b=5,c=7; int d; d = (0,3,1); printf("%d",d); return 0; } get the last number or valued data. It works for me the code below: int main(int argc, char const *argv[]) { int a =5,b=5,c=7; int d; d = 0,3+1,1-1; printf("%d",d); return 0; } it output is 0, but if you don't with (), it meaningless by this way, why not just use d = 0;
{ "pile_set_name": "StackExchange" }
Q: Mysql - 'Select max' from multiple joined tables doesn't return correct values I have two tables - one is a list of addresses, and the other of attendance dates and EmployeeIDNumbers to identfy the engineer who attended. An engineer may have attended an address multiple times. I am trying to select the address name, and the most recent attendance date and corresponding engineerID select s.sitename, max(sd.scheduleddate), sd.EngineerID from sites as s left join scheduled_dates as sd on sd.idsites = s.idsites group by s.idsites This code correctly pulls each address and the most recent 'Scheduled Date' but does not pull the correct corresponding engineer id. How do I get the engineerID from the same row as the max(scheduleddate)? Think this is something to do with the 'greatest-n-per-group' discussion, but I can't see how to implement that code with a query that already has a join A: You can use a NOT EXISTS condition with a correlated subquery: select s.sitename, sd.EngineerID, sd.scheduleddate from sites as s inner join scheduled_dates as sd on sd.idsites = s.idsites where not exists ( select 1 from scheduled_dates sd1 where sd1.idsites = s.idsites and sd1.scheduleddate > sd.scheduleddate ) The condition ensures that there no other record exists in scheduled_dates for the current site with a date greater than the one on the record being selected. Notes: I turned you LEFT JOIN to an INNER JOIN, since I believe that it better fit your use cases, feel free to revert this if needed.
{ "pile_set_name": "StackExchange" }
Q: replace List.foreach to LINQ I'm new to LINQ and doing some experiments with it. Sorry if it is a duplicate but I cant seem to find proper guide (for me) to it I want to replace this code : DataTable table List<string> header = new List<string>(); table.Columns.Cast<DataColumn>().ToList().ForEach(col => header.Add(col.ColumnName)); with something LINQ like: var LINQheader = from mycol in table.Columns select mycol.ColumnName; LINQheader.tolist(); but it doesn't even compile. what I want Is not a one line solution but would like some logic to understand how construct it with more complicated environments (Like choosing many node in XML with some logic) A: You can use Enumerable.Aggregate() for this: var header = table.Columns.Cast<DataColumn>().Aggregate(new List<string>(), (list, col) => { list.Add(col.ColumnName); return list; }); In general, Linq allows for retrieval and transformation of sequences of data from data sources. What you want to do in this question is to iterate over a sequence and return an immediate result. That isn't the primary focus of Linq, but there are methods that perform tasks like this, including Aggregate(), Average(), Count(), Max() and so on. A: here is the original code table.Columns.Cast<DataColumn>().ToList().ForEach(col => header.Add(col.ColumnName)); Why Cast used? because it allows you to treat DataColumnCollection items as a DataColumn not an object. Why ToList used? becuase it converts your IEnumerable to List and allows you to call ForEach because this function is special method that exists in List class. Why ForEach used? because it allows you to do what you want for each element on the list (in your case it adds column name of each column to another list(header)). Simplified version: now assume you want to add column names to header where they starts with "Student" you can write something like this DataTable table = new DataTable(); List<string> header = new List<string>(); foreach (DataColumn col in table.Columns) { if (col.ColumnName.StartsWith("Id")) // you can remove this line if you want to add all of them header.Add(col.ColumnName); } you can also use this table.Columns.Cast<DataColumn>() .ToList() .ForEach(col => { if (col.ColumnName.StartsWith("Id")) header.Add(col.ColumnName) }); or var headers = table.Columns.Cast<DataColumn>() .Where(col => col.ColumnName.StartsWith("Id")) .Select(col => col.ColumnName); header.AddRange(headers);
{ "pile_set_name": "StackExchange" }
Q: Looping stops after the first item in the list places = [] persons = [] unknown = [] newlist = [] filename = 'file.html' tree = etree.parse(filename) input_file = open(filename, 'rU') def extract(tree): <some code> return places return persons return unknown def change_class(): extract(tree) for line in input_file: for x in places: for z in unknown: if x+'</dfn>' in line: newline = line.replace('"person"', '"place"') newlist.append(newline) elif z+'</dfn>' in line: newline = line.replace('"person"','"undefined"') newlist.append(newline) else: newlist.append(line) break break for x in newlist: print x I have an html-file of this kind with erroneous class values: <html> <head></head> <body> <p class ='person'><dfn>New-York</dfn> <p class = 'place'><dfn>John Doe</dfn> <p class ='person'><dfn>Paris</dfn> <p class = 'place'><dfn>Jane Doe</dfn> </body> </html> My script allows me to reprint the same file, but it replaces the class value only for the first item of both lists (places and unknown): <html> <head></head> <body> <p class ='place'><dfn>New-York</dfn> <p class = 'unknown'><dfn>John Doe</dfn> <p class ='person'><dfn>Paris</dfn> <p class = 'place'><dfn>Jane Doe</dfn> </body> </html> Then it kinda stops iterating over both lists and goes directly to the else-step and adds all the rest to the newlist without replacements. Python yelds no errors, list are successfully extracted with the extract() function as well, I checked... A: known_places = #list of known places unkowns = #list of unknown places and persons newlist = [] for line in input_file: if any(place in line for place in Known_places): line = line.replace("person", "place") elif any(unkown in line for unkown in unkowns): line = line.replace("person","undefined") newlist.append(line) Something like this might work.
{ "pile_set_name": "StackExchange" }
Q: Specify App Delegate for Storyboard in iOS I'm trying to change my App's main interface which currently is set to a .xib file in the project's "General Configuration Pane" to a new storyboard. I have created the storyboard, and selected it as the main interface. But when I launch the application in simulator, I get a black screen and the following message printed in the console : "There is no app delegate set. An app delegate class must be specified to use a main storyboard file." How should I do that ? A: The app delegate class is generally specified in main.m: int main(int argc, char *argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([TCAppDelegate class])); } } A: did you set mainWindow if you are not please set your window in your project
{ "pile_set_name": "StackExchange" }
Q: Swift 3.0 draw circle with same start and end angle results in line I've written following code to draw a rect with a whole in it: fileprivate let strokeWidth: CGFloat = 5 let shapeLayer = CAShapeLayer() shapeLayer.strokeColor = UIColor.white.cgColor shapeLayer.lineWidth = strokeWidth shapeLayer.fillColor = UIColor(white: 0.5, alpha: 0.9).cgColor let p = UIBezierPath(rect: bounds.insetBy(dx: -strokeWidth, dy: -strokeWidth)) let radius = bounds.size.width / 3 p.move(to: CGPoint(x: bounds.midX + radius, y: bounds.midY)) p.addArc(withCenter: CGPoint(x: bounds.midX, y: bounds.midY), radius: radius, startAngle: 0, endAngle: CGFloat(2 * Double.pi), clockwise: false) p.close() shapeLayer.path = p.cgPath layer.addSublayer(shapeLayer) The problem here is this line: p.addArc(withCenter: CGPoint(x: bounds.midX, y: bounds.midY), radius: radius, startAngle: 0, endAngle: CGFloat(2 * Double.pi), clockwise: false) Printing out the description of the path: UIBezierPath: 0x6000000b35c0; MoveTo {-5, -5}, LineTo {380, -5}, LineTo {380, 672}, LineTo {-5, 672}, Close, MoveTo {312.5, 333.5}, LineTo {312.5, 333.49999999999994}, Close As you can see, the last two entries are lineTo and close, which gives me not the expected result (a full circle), I'll get nothing because the line is too short between 333.5 and 333.4999999. This problem occurs since switching to Swift 3, in Objective-C this wasn't a problem. Changing the end angle to 1.9 * Double.pi will also work, no idea why. But the full circle should have 2 * Double.pi. Any idea or is it a Swift 3 bug? A: Try like this: let bounds = UIScreen.main.bounds let strokeWidth: CGFloat = 5 let shapeLayer = CAShapeLayer() shapeLayer.strokeColor = UIColor.white.cgColor shapeLayer.lineWidth = strokeWidth shapeLayer.fillColor = UIColor(white: 0.5, alpha: 0.9).cgColor let p = UIBezierPath(rect: bounds.insetBy(dx: -strokeWidth, dy: -strokeWidth)) let radius = bounds.size.width / 3 p.move(to: CGPoint(x: bounds.midX + radius, y: bounds.midY)) p.addArc(withCenter: CGPoint(x: bounds.midX, y: bounds.midY), radius: radius, startAngle: 2 * .pi, endAngle: 0, clockwise: false) p.close() shapeLayer.fillColor = UIColor.red.cgColor shapeLayer.strokeColor = UIColor.black.cgColor shapeLayer.lineWidth = 5 shapeLayer.path = p.cgPath let view = UIView(frame: bounds) view.backgroundColor = .yellow view.layer.addSublayer(shapeLayer) view
{ "pile_set_name": "StackExchange" }
Q: FragmentStatePageAdapter Doesn't Pause Fragments I'm using a FragmentStatePageAdapter (android.support.v4) and I have setOffscreenPageLimit set to 2, so it creates and stores Fragments 2 ahead and 2 behind of the currently displayed Fragment. Problem: When the off-screen Fragments are created, they are also immediately started and resumed even though they haven't been painted to the screen yet. (!) When the current page is changed and the corresponding Fragment is swiped off screen, it isn't paused or stopped. (!) I've tried logging the behavior of all the callbacks in FSPA and its super class - setPrimaryItem comes the closest to being usable but appears to be called for all sorts of reasons, not just when the fragment is displayed. How can you detect that one of your Fragments is no longer displayed, or returning to the display? A: You could use a listener. mPager.setOnPageChangeListener(new OnPageChangeListener(){ @Override public void onPageScrollStateChanged(int arg0) { } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageSelected(int position) { if(mPageSelectedListener!=null){ mPageSelectedListener.pageSelected(position); } } }); Where PageSelectedListener is defined by you like so public interface PageSelectedListener{ public void pageSelected(int position); }; public void setPageSelectedListener(PageSelectedListener l){ mPageSelectedListener = l; } And use it like this in your fragment if(getActivity() instanceof MyActivity ((MyActivity)getActivity()).setPageSelectedListener(new PageSelectedListener(){ @Override public void pageSelected(int position) { if(position==MyAdapter.MY_PAGE){ // do something with currently viewed page...like resume it } else { // do something with any other page..like pause it } } }); }
{ "pile_set_name": "StackExchange" }
Q: External Style Sheet does not work with `h1` in XAMPP I am trying to make a navigation bar in a separate file, so that I may include it with php later. The file, nav_menu.php, contains a h1 tag, a p tag, and an ul containing a tags.I made the CSS in an External Style Sheet. I styled all the elements. The h1 tag didn't work. Why? nav_menu.php: <html> <head> <link rel="stylesheet" type="text/css" href="nav_menu.css"> </head> <body> <h1 title="School Helping Program">------ S.H.P. ------</h1> <p title="S.H.P.">School Helping Program</p> <ul> <li><a href="home.php">home</a></li> <li><a href="marks.php">marks</a></li> <li><a onclick="logout()">log out</a></li> </ul> </body> </html> nav_menu.css: <style> h1{text-align:center;color:#CC0000;}/*Here's the prolbem*/ p{font-style:italic;text-align:center;} li{float:left;} ul{list-style-type:none;margin:0;padding:0;} a{ display:block; width:180px; text-align:center; background-color:#5CB8E6; text-transform:uppercase; color:#CC0000; text-decoration:none; padding:10px 135px; cursor: pointer; } A: This is because you got <style> in first line and browser threats it as <style>\n\nh1 selector.
{ "pile_set_name": "StackExchange" }
Q: RxJava - Can't create handler inside thread that has not called Looper.prepare() - API 16 Full disclosure, I'm still learning RxJava, it's a bit hard to grasp the idea if many of the tutorials available are not newbie friendly. This error happens on API 16, works fine on API 23 & above (have tested below). As you will see, I'm trying to replace Async Task with RxJava. This is my code: private void getGps() { TrackGPS gps = new TrackGPS(this); Single.fromCallable(() -> { if (gps.canGetLocation()) { mMainVariables.setLongitude(gps.getLongitude()); mMainVariables.setLatitude(gps.getLatitude()); if (mMainVariables.getLongitude() != 0.0) { Geocoder geocoder; List<Address> addresses = null; geocoder = new Geocoder(this, Locale.getDefault()); addresses = geocoder.getFromLocation(mMainVariables.getLatitude(), mMainVariables.getLongitude(), 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5 Log.e("Address:", addresses.get(0).getAddressLine(0)); mMainVariables.setAddress(addresses.get(0).getAddressLine(0)); mMainVariables.setCity(addresses.get(0).getLocality()); mMainVariables.setState(addresses.get(0).getAdminArea()); mMainVariables.setCountry(addresses.get(0).getCountryName()); mMainVariables.setPostalCode(addresses.get(0).getPostalCode()); mMainVariables.setKnownName(addresses.get(0).getFeatureName()); Log.d("Lat Long:", "Lat: " + Double.toString(mMainVariables.getLatitude()) + " Long: " + Double.toString(mMainVariables.getLongitude())); return addresses.get(0).getAddressLine(0); } else { gps.showSettingsAlert(); } } else { Toasty.error(this, "Can't locate GPS", Toast.LENGTH_SHORT, true).show(); } return ""; }).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe((result) -> { mTxtResult.setText(result); }); } EDIT: Stack below: 05-23 20:26:58.936 3420-3420/com.example.ga.realm3 E/AndroidRuntime: FATAL EXCEPTION: main io.reactivex.exceptions.OnErrorNotImplementedException: Can't create handler inside thread that has not called Looper.prepare() at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:704) at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:701) at io.reactivex.internal.observers.ConsumerSingleObserver.onError(ConsumerSingleObserver.java:45) at io.reactivex.internal.operators.single.SingleObserveOn$ObserveOnSingleObserver.run(SingleObserveOn.java:79) at io.reactivex.android.schedulers.HandlerScheduler$ScheduledRunnable.run(HandlerScheduler.java:109) at android.os.Handler.handleCallback(Handler.java:730) A: You cannot show UI related stuff in your Scheduler thread. You are trying to show a Toast and also I presume your showSettingsAlert() is also trying show a dialog. This is against the threading policy. Very similar to Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog
{ "pile_set_name": "StackExchange" }
Q: NSMutableArray parsing csv not working? I have this code where I use NSMutableArray to parse a csv file. There are no errors that stop me from running the app however the map doesn't display anything. NSString *csvFilePath = [[NSBundle mainBundle] pathForResource:@"Data2" ofType:@"csv"]; NSString *dataStr = [NSString stringWithContentsOfFile:csvFilePath encoding:NSUTF8StringEncoding error:nil]; NSMutableArray *allLinedStrings = [[NSMutableArray alloc]initWithArray:[dataStr componentsSeparatedByString:@"\r"]]; NSMutableArray *latitude = [[NSMutableArray alloc]init]; NSMutableArray *longitude = [[NSMutableArray alloc]init]; NSMutableArray *description = [[NSMutableArray alloc]init]; NSMutableArray *address = [[NSMutableArray alloc]init]; NSMutableArray *temperature = [[NSMutableArray alloc]init]; NSMutableArray *time = [[NSMutableArray alloc]init]; NSMutableArray *ambient = [[NSMutableArray alloc]init]; NSMutableArray *filteredLocations = [NSMutableArray array]; MKMapPoint* pointArr = malloc(sizeof(MKMapPoint) * filteredLocations.count); for (int idx = 0; idx < [allLinedStrings count]; idx++) { NSMutableArray *infos = [[NSMutableArray alloc]initWithArray:[[allLinedStrings objectAtIndex:idx] componentsSeparatedByString:@","]]; if ([infos count] > 1) { [latitude addObject:[infos objectAtIndex:4]]; [longitude addObject:[infos objectAtIndex:5]]; [description addObject:[infos objectAtIndex:0]]; [address addObject:[infos objectAtIndex:10]]; [temperature addObject:[infos objectAtIndex:6]]; [time addObject:[infos objectAtIndex:15]]; [ambient addObject:[infos objectAtIndex:8]]; if([[latitude objectAtIndex:4] isEqualToString:@"NULL"] || [[longitude objectAtIndex:5] isEqualToString:@"NULL"] || [[description objectAtIndex:0] isEqualToString:@"NULL"] || [[address objectAtIndex:10]isEqualToString:@"NULL"] || [[temperature objectAtIndex:6] isEqualToString:@"NULL"] || [[time objectAtIndex:15]isEqualToString:@"NULL"] || [[ambient objectAtIndex:8] isEqualToString:@"NULL"]) {continue;} CLLocationCoordinate2D coordinate; coordinate.latitude = [[latitude objectAtIndex:4] doubleValue]; coordinate.longitude = [[longitude objectAtIndex:5] doubleValue]; Location *annotation = [[Location alloc] initWithName:[description objectAtIndex:0] address:[address objectAtIndex:10] temperature:[temperature objectAtIndex:6] time:[time objectAtIndex:15] ambient:[ambient objectAtIndex:8] coordinate:coordinate] ; [mapview addAnnotation:annotation]; [filteredLocations addObject:annotation]; MKMapPoint point = MKMapPointForCoordinate(coordinate); pointArr[idx] = point; } } self.routeLine = [MKPolyline polylineWithPoints:pointArr count:filteredLocations.count]; [self.mapview addOverlay:self.routeLine]; free(pointArr); MKMapRect zoomRect = MKMapRectNull; for (id <MKAnnotation> annotation in mapview.annotations) { MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate); MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1); zoomRect = MKMapRectUnion(zoomRect, pointRect); } [mapview setVisibleMapRect:zoomRect animated:YES]; self.mapview.delegate = self; } I guess there must be something wrong with how I'm calling the objects or maybe the MKMapPoint but I don't manage to find what's blocking the app from displaying the data. I've tried using both "initWithObjects" and removing "if ([infos count] > 1){" but when ran it crashed showing a breakdown point in "NSMutableArray *latitude = [[NSMutableArray alloc]init];". A: Based on your previous questions about this project, you want to do the following at a high level: Parse a CSV file where each line has coordinate data. Ignore lines that have "null" data. (For the purpose of this answer, let's ignore that one could use a pre-built CSV parser, or use a different format altogether.) Show annotations for lines with "good" data. Connect all the annotations with a line. For requirement 1 (R1), you already know how to load the CSV file, loop through the lines, and identify the lines with "null" data. For requirement 2 (R2), after some research, you know that you can create and add annotations to the map one at a time and the map doesn't need to know ahead of time how many you will add so that means the first two requirements could be done in the same loop. For requirement 3 (R3), after some research, you know that to create and add a polyline to the map, you need to know ahead of time how many points will be in the line. For R1 and R2, you will be looping through the lines of the CSV and identify the non-null lines. So that means you will know how many points will be in the polyline after the loop that handles R1 and R2. That means the polyline must be created after that loop. But to create the polyline, you need not just the point count but the coordinates for each point as well. That means while looping through the lines in the CSV, you need to save the coordinate data somewhere (in the same order it appeared in the CSV). In Objective-C, a convenient structure that allows you to add data to it without knowing in advance how many objects will be added is an NSMutableArray. So now we have this very high-level plan: Loop through the CSV file, ignore lines with null data, create and add annotations, add the line data to an NSMutableArray (NSMA). Create a polyline using the point data in NSMA, add the polyline to the map. With this plan, we see we need one NSMutableArray. Notice that in the existing code, you have a Location class that holds (or could hold) all the data from each line of the CSV. That means we could simply add these Location objects to the NSMA. NSMutableArrays can hold any type of object (they don't have to be just NSStrings). So here's a slightly more detailed plan: Initialize an NSMutableArray called filteredLocations (eg. NSMutableArray *filteredLocations = [NSMutableArray array];). Loop through the CSV file, ignore lines with null data, create a Location object and add as an annotation, add the Location object to filteredLocations (eg. [filteredLocations addObject:annotation];). Initialize (malloc) a C array to hold the points of the polyline with the point count being the count of filteredLocations. Loop through filteredLocations, add point from filteredLocations to the C array. Create and add a polyline to the map. In this plan note we have two separate loops: The first one is for R1 and R2. The second one is for R3. If required, I will post sample code that implements this plan. First, just to explain your latest NSRangeException error, it is happening on this line: if([[latitude objectAtIndex:4] isEqualToString:@"NULL"] || ... because you've declared latitude as an array and the first time the if executes in the loop, latitude only has one object (a few lines above this if you do [latitude addObject:...). The index of an array starts at zero so the bounds of an array with one object are zero to zero hence the error message saying index 4 beyond bounds [0 .. 0]. There are many other issues with the rest of the code. There is not enough room in this answer to explain in detail. I urge you, if possible, to stop, step back and re-start with a much simpler project or tutorials and, most importantly, learn the absolute basics of programming in general. Here is an example of code that should work based on your sample data: -(void)viewDidLoad { [super viewDidLoad]; self.mapview.delegate = self; NSString *csvFilePath = [[NSBundle mainBundle] pathForResource:@"Data2" ofType:@"csv"]; NSString *dataStr = [NSString stringWithContentsOfFile:csvFilePath encoding:NSUTF8StringEncoding error:nil]; NSArray *allLinedStrings = [dataStr componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]; NSMutableArray *filteredLocations = [NSMutableArray array]; for (int idx = 0; idx < [allLinedStrings count]; idx++) { NSArray *infos = [[allLinedStrings objectAtIndex:idx] componentsSeparatedByString:@","]; if ([infos count] > 15) { NSString *latitude = [infos objectAtIndex:4]; NSString *longitude = [infos objectAtIndex:5]; NSString *description = [infos objectAtIndex:0]; NSString *address = [infos objectAtIndex:10]; NSString *temperature = [infos objectAtIndex:6]; NSString *time = [infos objectAtIndex:15]; NSString *ambient = [infos objectAtIndex:8]; if([latitude isEqualToString:@"NULL"] || [longitude isEqualToString:@"NULL"] || [description isEqualToString:@"NULL"] || [address isEqualToString:@"NULL"] || [temperature isEqualToString:@"NULL"] || [time isEqualToString:@"NULL"] || [ambient isEqualToString:@"NULL"]) { continue; } CLLocationCoordinate2D coordinate; coordinate.latitude = [latitude doubleValue]; coordinate.longitude = [longitude doubleValue]; Location *annotation = [[Location alloc] initWithName:description address:address temperature:temperature time:time ambient:ambient coordinate:coordinate]; [mapview addAnnotation:annotation]; [filteredLocations addObject:annotation]; } } MKMapPoint* pointArr = malloc(sizeof(MKMapPoint) * filteredLocations.count); for (int flIndex = 0; flIndex < filteredLocations.count; flIndex++) { Location *location = [filteredLocations objectAtIndex:flIndex]; MKMapPoint point = MKMapPointForCoordinate(location.coordinate); pointArr[flIndex] = point; } self.routeLine = [MKPolyline polylineWithPoints:pointArr count:filteredLocations.count]; [self.mapview addOverlay:self.routeLine]; free(pointArr); [self.mapview showAnnotations:self.mapview.annotations animated:YES]; }
{ "pile_set_name": "StackExchange" }
Q: How to insert xml text & value in html option text & value I want to insert a option tag with text and value from reading xml tags. Here I want to insert <option value> Text</option> like this way below: <option value[from each xml col1]> Text [from each xml col2] </option> Here is the code: var xml = ' <row id="1_2"> <col1>46.0</col1> <col2>Acting Allowance</col2> </row> <row > <col1>A1</col1> <col2>Allowance for 65 years plus</col2></row>', xmlDoc = $.parseXML(xml), $xml = $(xmlDoc); $xml.find('col2').each(function () { var option = $(this).text(), //i want to take text from each col2 as option text value = $(this).attr('value'); //i want to take text from each col1 as option value $("#selectID").append("<option value='" + value + "'>" + option + "</option>"); }); <select id="selectID"></select> Please let me know for further information. Thanks. A: Your XML was invalid. You have to insert any root node (I just was wrapped the xml with <root> node. var xml = '<root><row id="1_2"><col1>46.0</col1><col2>Acting Allowance</col2></row><row><col1>A1</col1><col2>Allowance for 65 years plus</col2></row></root>', xmlDoc = $.parseXML(xml), $xml = $(xmlDoc); $xml.find('row').each(function() { var row = $(this), option = row.find('col2').text(), //i want to take text from each col2 as option text value = row.find('col1').text(); //i want to take text from each col1 as option value $("#selectID").append("<option value='" + value + "'>" + option + "</option>"); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="selectID"></select>
{ "pile_set_name": "StackExchange" }
Q: Color each point individually in column chart highcharts I have a highchart as shown in the fiddle series: [{ data: [ [ 'Actual Wishlist Requests' , 6000], [ 'Actual Approved Wishlists', 3000], [ 'Actual Research Completed', 2000], [ 'Actual Interviews Scheduled', 1000], [ 'Actual Successful Interviews', 500], [ 'Actual Contracts Signed', 50]] }, { data: [ [ 'Target Wishlist Requests' , 9305 ], [ 'Target Approved Wishlists', 6557], [ 'Target Research Completed', 5069], [ 'Target Interviews Scheduled', 2290], [ 'Target Successful Interviews', 686], [ 'Target Contracts Signed', 37]] }] http://jsfiddle.net/Sq8fq/1/ I want to color each point with an individual color. How can i do this with the existing chart? Thanks Abhishek A: You can specify lots of attributes at the point level, including color. Try something like this: series: [{ data: [ {y:6000,color:'red'}, http://jsfiddle.net/G575t/
{ "pile_set_name": "StackExchange" }
Q: Jar dependencies compile time and runtime If by default, when I produce a jar application, the dependencies are not include, does that mean that the user should download all the dependencies of my app to use it? Why includes dependencies in jar is not the default thing? How can I expect users to have/download all the dependencies at with the exact version needed? A: From https://imagej.net/Uber-JAR: Advantages: A single JAR file is simpler to deploy. There is no chance of mismatched versions of multiple JAR files. It is easier to construct a Java classpath, since only a single JAR needs to be included. Disadvantages: Every time you need to update the version of the software, you must redeploy the entire uber-JAR (e.g., ImageJ is ~68 MB as of May 2015). If you bundle individual JAR components, you need only update those that changed. This issue is of particular relevance to Java applications deployed via Java Web Start, since it automatically downloads the latest available version of each JAR dependency; in that case, your application startup time will suffer if you use the uber-JAR. You cannot cherry-pick only the JARs containing the functionality you need, so your application's footprint may suffer from bloat. If downstream code relies on any of the same dependencies which are embedded in an unshaded uber-jar, you may run into trouble (e.g., NoSuchMethodError for unshaded uber-JARs) with multiple copies of those dependencies on your classpath, especially if you need to use a different version of that dependency than is bundled with the uber-JAR. As you can see, it is important to understand how use of the uber-JAR will affect your application. In particular, Java applications will likely be better served using the individual component JARs, ideally managed using a dependency management platform such as Maven or Ivy. But for non-Java applications, the uber-JAR may be sufficient to your needs. It basically depends on the use case. If the jar will be used in development of other applications and its dependencies might be updated time to time, it makes sense to use a normal jar, but if the jar is to be run/deployed, it might be better to use an uber/fat jar.
{ "pile_set_name": "StackExchange" }
Q: Compile error: Argument not optional vba excel I'm trying to write a code where I input an image after checking the info in each sheet of my workbook. Since I added for each to the code it stopped working and started giving me this compile error message, the code works without the for each but i want it to be automatic. Can you help? Sub ForEachWs() Dim ws As Worksheet For Each ws In ActiveWorkbook.Worksheets Call Worksheet_SelectionChange Next ws End Sub Sub Worksheet_SelectionChange(ByVal Target As Range) On Error Resume Next If Target.Column = 2 And Target.Row = 1 Then ' onde clicar para buscar imagem BuscarImagemTavares (Target.Value) End If End Sub Sub BuscarImagemTavares(Produto As String) On Error Resume Next 'Autor: Tavares If Range("B2") = "ok" Then 'Verifica se celula B2 tem ok se sim não insere a imagem novamente Exit Sub End If Dim Imagem, CaminhoImagem As String If Len(Produto) = 3 Then 'acrescenta 00 antes do cod do produto Produto = "00" & Produto End If If Len(Produto) = 4 Then 'acrescenta 0 antes do cod do produto Produto = "0" & Produto End If Imagem = Dir("\\Clfssrvfar\ENGENHARIA\GESTAO_DE_PROJETOS\04. FOLLOWUP\09. ARQUIVOS PARA FERRAMENTAS\09.1 IMAGENS\09.1.2 IMAGENS PRODUTOS\" & Produto & "*", vbDirectory) CaminhoImagem = "\\Clfssrvfar\ENGENHARIA\GESTAO_DE_PROJETOS\04. FOLLOWUP\09. ARQUIVOS PARA FERRAMENTAS\09.1 IMAGENS\09.1.2 IMAGENS PRODUTOS\" & Imagem With ActiveSheet.Pictures.Insert(CaminhoImagem) 'Mostra Imagem 'Define tamanho e posição da imagem With .ShapeRange .Width = 75 .Height = 115 .Top = 7 .Left = 715 '*above it's me trying to make white background transparent* 'With .PictureFormat '.TransparentBackground = True '.TransparencyColor = RGB(255, 0, 0) 'End With '.Fill.Visible = True 'End With 'ActiveSheet.Shapes.Range(Array("Picture 2")).Select 'Application.CommandBars("Format Object").Visible = False End With End With If CaminhoImagem <> "" Then 'Após inserir imagem informa "ok" na B2 para não inserir de novo Range("B2").Select ActiveCell.FormulaR1C1 = "OK" End If End Sub A: Since you want to run the sub BuscarImagemTavares for every worksheet you have, you have to alter both the subs ForEachWs and BuscarImagemTavares. ForEachWs: Sub ForEachWs() Dim ws As Worksheet For Each ws In ActiveWorkbook.Worksheets 'Here you can directly call the sub without the sub Worksheet_SelectionChange Call BuscarImagemTavares(ws, ws.Cells(1,2).Value) 'in BuscarImagemTavares you´ll need the ws reference to actually work on the right worksheet (otherwise youll always work on the selected one) Next ws End Sub BuscarImagemTavares: Sub BuscarImagemTavares(ByVal ws as Worrksheet, Produto As String) 'Mind the additional parameter 'ws' On Error Resume Next 'Autor: Tavares 'If Range("B2") = "ok" Then 'Verifica se celula B2 tem ok se sim não insere a imagem novamente If ws.Range("B2") = "ok" Then 'Here you actually have to use a reference to the Worksheet you want to use, otherwise alwys the same will be used Exit Sub End If ... 'You need the reference here as well so you won#t use the same worksheet over and over again With ws.Pictures.Insert(CaminhoImagem) 'Mostra Imagem ... If CaminhoImagem <> "" Then 'Após inserir imagem informa "ok" na B2 para não inserir de novo 'Range("B2").Select 'ActiveCell.FormulaR1C1 = "OK" 'If you don´t actually need the cell in excel to be selected after the programm finished you should´nt use the '.select' and '.selection' instead use this: ws.Range("B2").Value= "OK" 'Since you aren´t adding a formula you should address the '.value' property End If ... End Sub Hope I could help you a bit.
{ "pile_set_name": "StackExchange" }
Q: What happens if I do not call pthread_mutex_destroy when using PTHREAD_PROCESS_SHARED On Linux, a mutex can be shared between processes by using PTHREAD_PROCESS_SHARED attribute then saved in a mapped file that may be used by many processes. This is an example in https://linux.die.net/man/3/pthread_mutexattr_init that do the job above: For example, the following code implements a simple counting semaphore in a mapped file that may be used by many processes. /* sem.h */ struct semaphore { pthread_mutex_t lock; pthread_cond_t nonzero; unsigned count; }; typedef struct semaphore semaphore_t; semaphore_t *semaphore_create(char *semaphore_name); semaphore_t *semaphore_open(char *semaphore_name); void semaphore_post(semaphore_t *semap); void semaphore_wait(semaphore_t *semap); void semaphore_close(semaphore_t *semap); /* sem.c */ #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <pthread.h> #include "sem.h" semaphore_t * semaphore_create(char *semaphore_name) { int fd; semaphore_t *semap; pthread_mutexattr_t psharedm; pthread_condattr_t psharedc; fd = open(semaphore_name, O_RDWR | O_CREAT | O_EXCL, 0666); if (fd < 0) return (NULL); (void) ftruncate(fd, sizeof(semaphore_t)); (void) pthread_mutexattr_init(&psharedm); (void) pthread_mutexattr_setpshared(&psharedm, PTHREAD_PROCESS_SHARED); (void) pthread_condattr_init(&psharedc); (void) pthread_condattr_setpshared(&psharedc, PTHREAD_PROCESS_SHARED); semap = (semaphore_t *) mmap(NULL, sizeof(semaphore_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close (fd); (void) pthread_mutex_init(&semap->lock, &psharedm); (void) pthread_cond_init(&semap->nonzero, &psharedc); semap->count = 0; return (semap); } semaphore_t * semaphore_open(char *semaphore_name) { int fd; semaphore_t *semap; fd = open(semaphore_name, O_RDWR, 0666); if (fd < 0) return (NULL); semap = (semaphore_t *) mmap(NULL, sizeof(semaphore_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close (fd); return (semap); } void semaphore_post(semaphore_t *semap) { pthread_mutex_lock(&semap->lock); if (semap->count == 0) pthread_cond_signal(&semapx->nonzero); semap->count++; pthread_mutex_unlock(&semap->lock); } void semaphore_wait(semaphore_t *semap) { pthread_mutex_lock(&semap->lock); while (semap->count == 0) pthread_cond_wait(&semap->nonzero, &semap->lock); semap->count--; pthread_mutex_unlock(&semap->lock); } void semaphore_close(semaphore_t *semap) { munmap((void *) semap, sizeof(semaphore_t)); } The following code is for three separate processes that create, post, and wait on a semaphore in the file /tmp/semaphore. Once the file is created, the post and wait programs increment and decrement the counting semaphore (waiting and waking as required) even though they did not initialize the semaphore. /* create.c */ #include "pthread.h" #include "sem.h" int main() { semaphore_t *semap; semap = semaphore_create("/tmp/semaphore"); if (semap == NULL) exit(1); semaphore_close(semap); return (0); } /* post */ #include "pthread.h" #include "sem.h" int main() { semaphore_t *semap; semap = semaphore_open("/tmp/semaphore"); if (semap == NULL) exit(1); semaphore_post(semap); semaphore_close(semap); return (0); } /* wait */ #include "pthread.h" #include "sem.h" int main() { semaphore_t *semap; semap = semaphore_open("/tmp/semaphore"); if (semap == NULL) exit(1); semaphore_wait(semap); semaphore_close(semap); return (0); } But calling pthread_mutex_destroy() on a shared mutex is tricky because it can cause error on other process and the example above also does not call pthread_mutex_destroy(). So I am thinking not to destroy it. My question is: Is it safe if I init a PTHREAD_PROCESS_SHARED mutex, save it to a mapped file and use it forever on many processes without calling pthread_mutex_destroy() or re-initialize it? A: My question is: Is it safe if I init a PTHREAD_PROCESS_SHARED mutex, save it to a mapped file and use it forever on many processes without calling pthread_mutex_destroy() or re-initialize it? It is allowed for a process-shared mutex to outlive the process that initialized it. If you map such a mutex to a persistent regular file, then its state will persist indefinitely, even while no process has it mapped. As long as the integrity of its state is maintained -- including, but not limited to, no process destroying it via pthread_mutex_destroy() -- new processes can map it and use it. That is to say, the semantics of what you describe are well-defined. But is it safe? Not especially. The first issue is that you need to know when to create it, and you need to avoid race conditions when you do. If you rely on the processes that regularly use the mutex to initialize it at need, then you have to make sure that exactly one creates and initializes it when the file does not already exist. Another issue is that using a long-lived shared mutex like that produces a great deal of exposure to failures. For example, if a program crashes while holding the mutex locked then it will remain locked until you take some kind of manual corrective action. Or if the mapped file is manipulated directly then the mutex state can easily be corrupted, producing undefined behavior in all programs using it -- even across reboots. If you really need a long-persisting synchronization object, then I would suggest considering a POSIX named semaphore. It is designed for the purpose, taking the above considerations and others into account. It differs somewhat, however, in that such semaphores reside in the kernel and have kernel persistence, so they do not persist across reboots (which is generally a good thing), and they are not susceptible to ordinary file manipulation. Alternatively, you could consider a System V semaphore. This is an older semaphore implementation that also has kernel persistence. Its interface is considerably clunkier than that of the POSIX semaphore, but it has a few useful features that the POSIX semaphore does not, such as providing for automatic unlocking when the process holding one locked terminates (even abnormally).
{ "pile_set_name": "StackExchange" }
Q: Jenkins DSL add secret file I would like to add secret file to my job, but I can't find which keyword from Jenkis DSL it is, any suggestions? In xml it looks like this: <project> ... <properties>...</properties> <scm class="hudson.scm.NullSCM"/> <builders>...</builders> <buildWrappers> <org.jenkinsci.plugins.credentialsbinding.impl.SecretBuildWrapper plugin="credentials-binding@1.10"> <bindings> <org.jenkinsci.plugins.credentialsbinding.impl.FileBinding> <credentialsId>my-keytab</credentialsId> <variable>KEYTAB</variable> </org.jenkinsci.plugins.credentialsbinding.impl.FileBinding> </bindings> </org.jenkinsci.plugins.credentialsbinding.impl.SecretBuildWrapper> </buildWrappers> </project> A: You can use file within the credentialsBinding context. job('example') { wrappers { credentialsBinding { file('KEYTAB', 'my-keytab') } } } See the API Viewer for details.
{ "pile_set_name": "StackExchange" }
Q: Insert multiple rows from one AJAX POST into database using PHP? Post header: seasonString: Sommer,Hebst,Frühling,Winter holidaywishString: 3,4,7,8 PHP: //Insert Seasons data $sqli="INSERT INTO seasons(season)VALUES('{$mysqli->real_escape_string($_POST['seasonString'])}')"; $insert=$mysqli->query($sql); // $userID = mysqli_insert_id($mysqli); //Insert Desires data $sqli="INSERT INTO desires(desires)VALUES('{$mysqli->real_escape_string($_POST['holidaywishString'])}')"; $insert=$mysqli->query($sql); // $userID = mysqli_insert_id($mysqli); In this case the data is inserted into my database table tbl_season on one column: Sommer, Hebst, Frühling, Winter holidaywishString:3, 4, 7, 8 But I want it to be this way: tbl_season; id season -1 Sommer -1 Hebst -2 winter -3 hebst How can I achieve that? A: $arrSeason = explode(',', $_POST['seasonString']); foreach($arrSeason as $season ){ $sqlSeason = "INSERT INTO seasons(season,iduserinfo)VALUES('".$mysqli->real_escape_string($season)."','$userID')"; $mysqli->query($sqlSeason); } /problem solved Thanx a lot
{ "pile_set_name": "StackExchange" }
Q: What exactly is an instance in Java? What is the difference between an object, instance, and reference? They say that they have to create an instance to their application? What does that mean? A: An object and an instance are the same thing. Personally I prefer to use the word "instance" when referring to a specific object of a specific type, for example "an instance of type Foo". But when talking about objects in general I would say "objects" rather than "instances". A reference either refers to a specific object or else it can be a null reference. They say that they have to create an instance to their application. What does it mean? They probably mean you have to write something like this: Foo foo = new Foo(); If you are unsure what type you should instantiate you should contact the developers of the application and ask for a more complete example. A: "instance to an application" means nothing. "object" and "instance" are the same thing. There is a "class" that defines structure, and instances of that class (obtained with new ClassName()). For example there is the class Car, and there are instance with different properties like mileage, max speed, horse-power, brand, etc. Reference is, in the Java context, a variable* - it is something pointing to an object/instance. For example, String s = null; - s is a reference, that currently references no instance, but can reference an instance of the String class. *Jon Skeet made a note about the difference between a variable and a reference. See his comment. It is an important distinction about how Java works when you invoke a method - pass-by-value. The value of s is a reference. It's very important to distinguish between variables and values, and objects and references. A: When you use the keyword new for example JFrame j = new JFrame(); you are creating an instance of the class JFrame. The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class. Take a look here Creating Objects The types of the Java programming language are divided into two categories: primitive types and reference types. The reference types are class types, interface types, and array types. There is also a special null type. An object is a dynamically created instance of a class type or a dynamically created array. The values of a reference type are references to objects. Refer Types, Values, and Variables for more information
{ "pile_set_name": "StackExchange" }
Q: Spring/Angular get current user and save post to that user Sorry, I am back with just one more question. I have am using Spring security and Angular front end. My question is once I log in, how do I save a post to the current user. Post model: @Id @GeneratedValue private Long id; private String title; @Column(columnDefinition = "TEXT") private String body; @JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss a", timezone = "America/New_York") private Date createdAt; private String pictureUrl; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user") private User user; UserDetailsServiceImpl: @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository repository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // Get the user's username User currentUser = repository.findByUsername(username); // Create a new UserDetails called user and set to user's : // username, current users password, user is enabled, account Non expired, creds non expired // account non locked, UserDetails user = new org.springframework.security.core.userdetails.User(username, currentUser.getPassword(), true, true, true, true, AuthorityUtils.createAuthorityList(currentUser.getRole())); return user; } } Obviously this works fine with the command line runner: Post post1 = new Post("Title", "Some content", date, user1); Angular: addPost() { const title = this.eventForm.get('title').value; const body = this.eventForm.get('body').value; const newTask: Task = { post, body }; this.data.addPost(newPost).subscribe((res) => { console.log(res); this.getPost(); }); } How can I, once logged in, get the actual user object to save the post object. A: I have no idea if this is the correct way to do this, but it works at least! Lol... It works for now anyways, haha. @Autowired private PostRepository repository; @Autowired UserRepository userRepository; @PostMapping("/posts") public void addPost(@RequestBody Post post) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); User user = userRepository.findByUsername(auth.getName()); post.setUser(user); this.repository.save(post); }
{ "pile_set_name": "StackExchange" }
Q: Interacting with box2D objects How can I interact with an object in box2d, I'm completely new to this so I have no clue what to do. The box is created like this: bodyDef.type = b2Body.b2_dynamicBody; fixDef.shape = new b2PolygonShape; fixDef.shape.SetAsBox(0.5, 0.5); // Half-Width, Half-Height bodyDef.position.x = 5; bodyDef.position.y = 5; world.CreateBody(bodyDef).CreateFixture(fixDef); How can I change the x, y positions of that box, tried bodyDef.position.x--; but it returned "bodyDef is not defined". How do I access this? A: For moving here is SetTransform, for interacting MouseJoint. BodyDef is used to make creation of bodies easier, so it is used just in that function, you have to store value returned by CreateBody, and read documentation first.
{ "pile_set_name": "StackExchange" }
Q: Core Data Detail View from To-Many relationship I'm struggling with some aspects of Core Data, namely setting up a UITableView to list data from a to-many relationship. I have three entities, Teams, TeamDetails and Players: In the first view, I list the names of all the teams in the Teams entity, then tapping each cell segues to an intermediate view with buttons to either edit a team's details or edit a team's players. Tapping on a button segues to another UITableView that lists the Team's details or Players. Listing the TeamDetails works, since it is a one-to-one relationship and a static cell table. I'm trying to set up a UITableViewController that lists all the players that are associated with the selected team. So I pass the ManagedObjectContext etc to the table view controller via the segue as shown below: else if ([segue.identifier isEqualToString:@"ShowPlayersSegue"]){ NSLog(@"Setting ShowPlayersTVC as a delegate of EditPlayerTVC"); ShowPlayersTVC *showPlayerTVC = segue.destinationViewController; showPlayerTVC.delegate = self; showPlayerTVC.managedObjectContext = self.managedObjectContext; showPlayerTVC.team = self.team; showPlayerTVC.player = self.team.playerDetails; } So, in my showPlayerTVC I want to get the set of players for that specific team, then have a row for each one that shows the playerName attribute as the cell textlabel.text. I've been reading tutorials and playing around for ages without getting much success. I think I need to create an array of Player objects from the NSSet, which I can do, but I can't get the UITableview to list the objects. I'm probably missing something fundamental here, but any suggestions would be appreciated. A: First, there are some issues with your data model. The one-to-one to details I do not understand - why not just add attributes to the Team entity? Also, you may want to transform some of these into more flexible relationships, such as a Trainer entity, etc. Also, your naming is flawed and will lead to programming errors or at least make your code difficult to read. Note the singular / plural confusion. Here is my suggestion for naming your entities / relationships: Team - players <--------------->> team - Player To display data in an a table view you should use NSFetchedResultsController. Let the FRC fetch the Player entity and give its fetch request the following predicate: [NSPredicate predicateWithFormat:@"team = %@", teamObject]; Your segue code is almost correct. Give the new view controller a team attribute and use this in the above predicate of its fetched results controller. You do not need any player or "playerDetails" information (they are linked to the team anyway).
{ "pile_set_name": "StackExchange" }
Q: Its or Their to refer to a company? The company will issue (their, its) annual report next month. In this case, should I use "its" or "their"? A: Both its and their are pronouns. While its is a singular pronoun, their is a plural pronoun. A company is a collective noun. In AmE, Company takes a singular verb form and singular pronoun. While in BrE, Company takes a plural verb form and plural pronoun. So, depending on that, both are correct. In AmE: The company will issue its annual report next month. In BrE: The company will issue their annual report next month. A: Your question: should I use its or their in: The company will issue their/its annual report next month? In this instance, I'd recommend using its: The company will issue its annual report next month. This, among other things, echoes Kelly's answer and Fantasier's answer to an old question: "If a collective noun is seen as a whole, sole, impersonal unit, then singular verbs are more common. If it is seen as a collection of people doing personal things, then plural verbs are more common. In American English the verb for the noun is usually singular in all cases except family (if you don't quantify it with members of, people in etc)." Which also echoes an old answer by FumbleFingers: "(in "British English") [W]e quite naturally use singular or plural for things like company, family, group, according to context", and information relating to collective nouns which is relatively to find around the web, including on English Language & Usage Stack Exchange. Back to your sentence, it's clear that it's safer to use its in either British or American English. Even though it may be possible to use their in British English (and also in American English), I'd personally use it in that specific instance; and though I can't say exactly why, this Google Ngram chart appears to support my choice: A: For what it's worth, Google Books Ngram Viewer would suggest that company is more often treated as singular. But all you can really draw from this is that it's acceptable to treat company as either singular or plural. I think it comes down to whether or not you want to emphasise the single legal entity or the group of people who make up the company. In the case of an annual report, it is issued by the single legal entity and so I would use the singular: The company will issue its annual report next month.
{ "pile_set_name": "StackExchange" }
Q: Android READ PHONE STATE? I'm trying to make app to READ PHONE STATE and when the phone state is changed to display Toast with the current state. But when I start it, the app stops unexpectedly. my class : import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.widget.TextView; public class TelephonyDemo extends Activity { TextView textOut; TelephonyManager telephonyManager; PhoneStateListener listener; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Get the UI textOut = (TextView) findViewById(R.id.textOut); // Get the telephony manager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); // Create a new PhoneStateListener listener = new PhoneStateListener() { @Override public void onCallStateChanged(int state, String incomingNumber) { String stateString = "N/A"; switch (state) { case TelephonyManager.CALL_STATE_IDLE: stateString = "Idle"; break; case TelephonyManager.CALL_STATE_OFFHOOK: stateString = "Off Hook"; break; case TelephonyManager.CALL_STATE_RINGING: stateString = "Ringing"; break; } textOut.append(String.format("\nonCallStateChanged: %s", stateString)); } }; // Register the listener with the telephony manager telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE); } } my manifest is : <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.marakana" android:versionCode="1" android:versionName="1.0" > <application android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@android:style/Theme.Light" > <activity android:name=".TelephonyDemo" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-sdk android:minSdkVersion="7" /> </manifest> My layout is : <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Telephony Demo" android:textSize="22sp" /> <TextView android:id="@+id/textOut" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Output" > </TextView> </LinearLayout> A: I did not see <uses-permission android:name="android.permission.READ_PHONE_STATE" /> in your Manifest file. It is required for your application to be able to read that state. A: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.marakana" android:versionCode="1" android:versionName="1.0" > /* permission should be added like below*/ <uses-permission android:name="android.permission.READ_PHONE_STATE"/> <application android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@android:style/Theme.Light" > <activity android:name=".TelephonyDemo" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-sdk android:minSdkVersion="7" /> </manifest>
{ "pile_set_name": "StackExchange" }
Q: how to get a textbox value from dynamically created div I am creating dynamic div with html elements and i need to get value that textbox This is my dynamic created content now i need to get the <div id="TextBoxContainer"> <div id="newtextbox1"> // this id is dynamic id <div class="row cells2"> <div class="cell"> <label>Patient Name</label> <div class="input-control text full-size"> <input type="text" id="PatientName1" placeholder="Patient Name"/> // this id is dynamic id </div> </div> <div class="cell"> <label>Patient ICNo</label> <div class="input-control text full-size" > <input type="text" id="PatientICNo" placeholder="Patient ICNo"/> </div> </div> </div> </div> </div> here i am trying to get value in jquery if ($("#TextBoxContainer") != null && $("#TextBoxContainer").length > 0) { var count = 1; $("#TextBoxContainer").each(function () { debugger; var Pid = "input#PatientName" + count; var childdiv = "div#newtextbox" + count; count++; var patientname = $(this).closest(childdiv).children(Pid).val(); }); } A: Here you go with a solution https://jsfiddle.net/p9ywL4pm/1/ if ($("#TextBoxContainer") != null && $("#TextBoxContainer").length > 0) { var count = 1; $("#TextBoxContainer").children().each(function () { var Pid = "input#PatientName" + count; var patientname = $(this).find(Pid).val(); console.log(Pid, patientname); count++; }); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="TextBoxContainer"> <div id="newtextbox1"> <div class="row cells2"> <div class="cell"> <label>Patient Name</label> <div class="input-control text full-size"> <input type="text" id="PatientName1" placeholder="Patient Name" /> </div> </div> <div class="cell"> <label>Patient ICNo</label> <div class="input-control text full-size" > <input type="text" id="PatientICNo" placeholder="Patient ICNo"/> </div> </div> </div> </div> <div id="newtextbox2"> <div class="row cells2"> <div class="cell"> <label>Patient Name</label> <div class="input-control text full-size"> <input type="text" id="PatientName2" placeholder="Patient Name"/> </div> </div> <div class="cell"> <label>Patient ICNo</label> <div class="input-control text full-size" > <input type="text" id="PatientICNo" placeholder="Patient ICNo"/> </div> </div> </div> </div> </div> I considered two child elements inside #TextBoxContainer container. Change the #PatientICNo input to <input type="text" class="PatientICNo" placeholder="Patient ICNo"/> Use class instead of ID because ID need to unique. Hope this will help you.
{ "pile_set_name": "StackExchange" }
Q: NoSuchMethodError while parsing xsd to generate classes using JAXB I'm new to JAXB. I'm trying to parse the xsd to generate the jaxb classes. It works fine with other xsd files but the one I'm trying to parse now is generating exceptions. This is the stack trace parsing a schema... Exception in thread "main" java.lang.NoSuchMethodError: com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>([Ljava/lang/Class;Ljava/util/Collection;Ljava/util/Map;Ljava/lang/String;ZLcom/sun/xml/bind/v2/model/annotation/RuntimeAnnotationReader;ZZ)V at com.sun.tools.xjc.reader.xmlschema.bindinfo.BindInfo.getJAXBContext(BindInfo.java:332) at com.sun.tools.xjc.reader.xmlschema.bindinfo.AnnotationParserFactoryImpl$1.<init>(AnnotationParserFactoryImpl.java:80) at com.sun.tools.xjc.reader.xmlschema.bindinfo.AnnotationParserFactoryImpl.create(AnnotationParserFactoryImpl.java:79) at com.sun.xml.xsom.impl.parser.NGCCRuntimeEx.createAnnotationParser(NGCCRuntimeEx.java:323) at com.sun.xml.xsom.impl.parser.state.annotation.action0(annotation.java:48) at com.sun.xml.xsom.impl.parser.state.annotation.enterElement(annotation.java:73) at com.sun.xml.xsom.impl.parser.state.NGCCRuntime.sendEnterElement(NGCCRuntime.java:378) at com.sun.xml.xsom.impl.parser.state.NGCCHandler.spawnChildFromEnterElement(NGCCHandler.java:74) at com.sun.xml.xsom.impl.parser.state.complexType.enterElement(complexType.java:500) at com.sun.xml.xsom.impl.parser.state.NGCCRuntime.sendEnterElement(NGCCRuntime.java:378) at com.sun.xml.xsom.impl.parser.state.NGCCHandler.revertToParentFromEnterElement(NGCCHandler.java:111) at com.sun.xml.xsom.impl.parser.state.foreignAttributes.enterElement(foreignAttributes.java:50) at com.sun.xml.xsom.impl.parser.state.NGCCRuntime.sendEnterElement(NGCCRuntime.java:378) at com.sun.xml.xsom.impl.parser.state.NGCCHandler.spawnChildFromEnterElement(NGCCHandler.java:74) at com.sun.xml.xsom.impl.parser.state.complexType.enterElement(complexType.java:255) at com.sun.xml.xsom.impl.parser.state.NGCCRuntime.sendEnterElement(NGCCRuntime.java:378) at com.sun.xml.xsom.impl.parser.state.complexType.enterElement(complexType.java:373) at com.sun.xml.xsom.impl.parser.state.NGCCRuntime.sendEnterElement(NGCCRuntime.java:378) at com.sun.xml.xsom.impl.parser.state.complexType.enterElement(complexType.java:213) at com.sun.xml.xsom.impl.parser.state.NGCCRuntime.sendEnterElement(NGCCRuntime.java:378) at com.sun.xml.xsom.impl.parser.state.complexType.enterElement(complexType.java:347) at com.sun.xml.xsom.impl.parser.state.NGCCRuntime.sendEnterElement(NGCCRuntime.java:378) at com.sun.xml.xsom.impl.parser.state.complexType.enterElement(complexType.java:305) at com.sun.xml.xsom.impl.parser.state.NGCCRuntime.sendEnterElement(NGCCRuntime.java:378) at com.sun.xml.xsom.impl.parser.state.complexType.enterElement(complexType.java:464) at com.sun.xml.xsom.impl.parser.state.NGCCRuntime.startElement(NGCCRuntime.java:219) at org.xml.sax.helpers.XMLFilterImpl.startElement(XMLFilterImpl.java:551) at com.sun.tools.xjc.util.SubtreeCutter.startElement(SubtreeCutter.java:104) at com.sun.tools.xjc.reader.ExtensionBindingChecker.startElement(ExtensionBindingChecker.java:144) at org.xml.sax.helpers.XMLFilterImpl.startElement(XMLFilterImpl.java:551) at com.sun.tools.xjc.reader.xmlschema.parser.IncorrectNamespaceURIChecker.startElement(IncorrectNamespaceURIChecker.java:113) at org.xml.sax.helpers.XMLFilterImpl.startElement(XMLFilterImpl.java:551) at com.sun.tools.xjc.reader.xmlschema.parser.CustomizationContextChecker.startElement(CustomizationContextChecker.java:188) at org.xml.sax.helpers.XMLFilterImpl.startElement(XMLFilterImpl.java:551) at com.sun.tools.xjc.ModelLoader$SpeculationChecker.startElement(ModelLoader.java:455) at org.xml.sax.helpers.XMLFilterImpl.startElement(XMLFilterImpl.java:551) at com.sun.tools.xjc.reader.internalizer.VersionChecker.startElement(VersionChecker.java:98) at org.xml.sax.helpers.XMLFilterImpl.startElement(XMLFilterImpl.java:551) at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:509) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:380) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2787) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:118) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777) at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141) at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213) at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:643) at org.xml.sax.helpers.XMLFilterImpl.parse(XMLFilterImpl.java:357) at com.sun.xml.xsom.parser.JAXPParser.parse(JAXPParser.java:79) at com.sun.tools.xjc.ModelLoader$2.parse(ModelLoader.java:479) at com.sun.tools.xjc.ModelLoader$XMLSchemaParser.parse(ModelLoader.java:262) at com.sun.xml.xsom.impl.parser.NGCCRuntimeEx.parseEntity(NGCCRuntimeEx.java:301) at com.sun.xml.xsom.impl.parser.ParserContext.parse(ParserContext.java:88) at com.sun.xml.xsom.parser.XSOMParser.parse(XSOMParser.java:147) at com.sun.tools.xjc.ModelLoader.createXSOMSpeculative(ModelLoader.java:496) at com.sun.tools.xjc.ModelLoader.loadXMLSchema(ModelLoader.java:366) at com.sun.tools.xjc.ModelLoader.load(ModelLoader.java:167) at com.sun.tools.xjc.ModelLoader.load(ModelLoader.java:113) at com.sun.tools.xjc.Driver.run(Driver.java:313) at com.sun.tools.xjc.Driver.run(Driver.java:191) at com.sun.tools.xjc.Driver._main(Driver.java:116) at com.sun.tools.xjc.Driver.access$000(Driver.java:74) at com.sun.tools.xjc.Driver$1.run(Driver.java:96) here is the xsd link:XSD FILE A: It looks like you have incompatible libraries in your classpath. Look which Version of jaxb-xjc.jar and jaxb-impl you have in your classpath
{ "pile_set_name": "StackExchange" }
Q: Can ggplot change the direction of axis.ticks from downward to upward? Something I want to realize is like the following: You see the direction of the axis.ticks is upward. So can ggplot make the direction of axis.ticks upward? For now I can realize this You can see the axis.ticks.length have been set to zero with the command of Axis Attributes · hadley/ggplot2 Wiki · GitHub But this is not what I want and there seems little description of it online. Thank you! A: I think this achieves your goal: library(ggplot2) library(grid) gg <- ggplot(mtcars, aes(mpg, drat)) gg <- gg + geom_point(size=3) gg <- gg + theme_bw() gg <- gg + theme(axis.text.x=element_text(size=17, vjust=-0.25, color="black")) gg <- gg + theme(axis.text.y=element_text(size=17, hjust=1, color="black")) gg <- gg + theme(axis.ticks=element_line(color="black", size=0.5)) gg <- gg + theme(axis.ticks.length=unit(-0.25, "cm")) gg <- gg + theme(axis.ticks.margin=unit(0.5, "cm")) gg We're just modifying the tick size and "reversing" the length then making sure the tick labels are positioned properly after that.
{ "pile_set_name": "StackExchange" }
Q: CSS framework with no Javascript I need to built a website but I have specific instructions to not use javascript. In addition to that I also have to make one that work for iPhone/mobile devices (also no javascript). It's fine for me to switch style sheets base on devices with some PHP magic, so it doesn't have to be the same CSS file. What I want to know is, what are some recommended CSS frameworks for either or both scenarios? A: You would use media queries to achieve this. https://developer.mozilla.org/en-US/docs/CSS/Media_queries The basic idea is to design from mobile up, or "responsive" design. You should google search that for more insight. You then use such operators as @media only screen and (max-width: 480px){ #content{ display:block; } } for example, to define how a particular element changes for each view. There are tons of resources for this that can be found with basic searches, so the need to outline in detail here is none. You can also add in specific style sheets like so: <link rel="stylesheet" media="all and (max-width: 480px)" href="http://foo.bar.com/stylesheet.css" /> if you want to separate the style sheets for each view. good luck. If you have specific questions, feel free to ask and I can update.
{ "pile_set_name": "StackExchange" }
Q: I am having trouble starting my node app in Bluemix I am trying to start my node app in Bluemix and getting a weird error. My app works locally. I have copied a snippet out of my app below. var express = require("express"), app = express(); app.get("/", function (request, response) { response.render("index"); }); app.listen(8080); My app never starts in Bluemix. The error I am getting on Bluemix is below. [11:07 AM] jsloyer@Jeffs-MacBook-Pro [testapp]>cf push myapp Creating app myapp in org myemail@co.com / space demos as myemail@co.com... OK Creating route myapp.mybluemix.net... OK Binding myapp.mybluemix.net to myapp... OK Uploading myapp... Uploading app files from: /Users/jsloyer/Downloads/testapp Uploading 566, 2 files Done uploading OK Starting app myapp in org myemail@co.com / space demos as myemail@co.com... -----> Downloaded app package (4.0K) -----> Node.js Buildpack Version: v1.15-20150331-2231 -----> Resetting git environment TIP: Specify a node version in package.json -----> Defaulting to latest stable node: 0.10.38 -----> Installing IBM SDK for Node.js from cache -----> Checking and configuring service extensions -----> Installing dependencies npm WARN package.json bluemix-deploy@ No description npm WARN package.json bluemix-deploy@ No repository field. npm WARN package.json bluemix-deploy@ No README data ├── methods@0.1.0 ├── parseurl@1.0.1 ├── merge-descriptors@0.0.2 ├── escape-html@1.0.1 ├── debug@0.8.1 ├── cookie-signature@1.0.3 ├── fresh@0.2.2 ├── range-parser@1.0.0 ├── qs@0.6.6 ├── buffer-crc32@0.2.1 ├── cookie@0.1.0 ├── path-to-regexp@0.1.2 ├── accepts@1.0.0 (negotiator@0.3.0, mime@1.2.11) ├── send@0.2.0 (mime@1.2.11) -----> Caching node_modules directory for future builds -----> Cleaning up node-gyp and npm artifacts -----> No Procfile found; Adding npm start to new Procfile -----> Building runtime environment -----> Checking and configuring service extensions -----> Installing App Management -----> Uploading droplet (8.9M) 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 down 0 of 1 instances running, 1 down 0 of 1 instances running, 1 down 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 down 0 of 1 instances running, 1 down 0 of 1 instances running, 1 down 0 of 1 instances running, 1 down 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting FAILED Start app timeout TIP: use 'cf logs myapp --recent' for more information Here is the logs from when the app tries to deploy. [11:10 AM] jeff@jeffs-mbp [node-red]>cf logs myapp --recent Connected, dumping recent logs for app myapp in org myemail@co.com / space demos as myemail@co.com... 2015-04-09T11:07:12.97-0400 [API] OUT Created app with guid de2f73ce-e19a-4daa-b4a9-6ab59588a069 2015-04-09T11:07:16.60-0400 [API] OUT Updated app with guid de2f73ce-e19a-4daa-b4a9-6ab59588a069 ({"route"=>"e518e637-6b86-4110-8359-b8cdeda946e2"}) 2015-04-09T11:07:48.28-0400 [DEA] OUT Got staging request for app with id de2f73ce-e19a-4daa-b4a9-6ab59588a069 2015-04-09T11:08:13.54-0400 [API] OUT Updated app with guid de2f73ce-e19a-4daa-b4a9-6ab59588a069 ({"state"=>"STARTED"}) 2015-04-09T11:08:13.71-0400 [STG] OUT -----> Downloaded app package (4.0K) 2015-04-09T11:08:14.39-0400 [STG] OUT -----> Node.js Buildpack Version: v1.15-20150331-2231 2015-04-09T11:08:14.39-0400 [STG] OUT -----> Resetting git environment 2015-04-09T11:08:14.84-0400 [STG] OUT TIP: Specify a node version in package.json 2015-04-09T11:08:14.84-0400 [STG] OUT -----> Defaulting to latest stable node: 0.10.38 2015-04-09T11:08:14.84-0400 [STG] OUT -----> Installing IBM SDK for Node.js from cache 2015-04-09T11:08:15.27-0400 [STG] OUT -----> Checking and configuring service extensions 2015-04-09T11:08:15.39-0400 [STG] OUT -----> Installing dependencies 2015-04-09T11:08:16.14-0400 [STG] OUT npm WARN package.json bluemix-deploy@ No description 2015-04-09T11:08:16.14-0400 [STG] OUT npm WARN package.json bluemix-deploy@ No repository field. 2015-04-09T11:08:16.14-0400 [STG] OUT npm WARN package.json bluemix-deploy@ No README data 2015-04-09T11:08:18.57-0400 [STG] OUT ├── methods@0.1.0 2015-04-09T11:08:18.57-0400 [STG] OUT ├── parseurl@1.0.1 2015-04-09T11:08:18.57-0400 [STG] OUT ├── merge-descriptors@0.0.2 2015-04-09T11:08:18.57-0400 [STG] OUT ├── escape-html@1.0.1 2015-04-09T11:08:18.57-0400 [STG] OUT ├── debug@0.8.1 2015-04-09T11:08:18.57-0400 [STG] OUT ├── cookie-signature@1.0.3 2015-04-09T11:08:18.57-0400 [STG] OUT ├── fresh@0.2.2 2015-04-09T11:08:18.57-0400 [STG] OUT ├── range-parser@1.0.0 2015-04-09T11:08:18.57-0400 [STG] OUT ├── qs@0.6.6 2015-04-09T11:08:18.57-0400 [STG] OUT ├── buffer-crc32@0.2.1 2015-04-09T11:08:18.57-0400 [STG] OUT ├── cookie@0.1.0 2015-04-09T11:08:18.57-0400 [STG] OUT ├── path-to-regexp@0.1.2 2015-04-09T11:08:18.57-0400 [STG] OUT ├── accepts@1.0.0 (negotiator@0.3.0, mime@1.2.11) 2015-04-09T11:08:18.57-0400 [STG] OUT ├── send@0.2.0 (mime@1.2.11) 2015-04-09T11:08:18.64-0400 [STG] OUT -----> Caching node_modules directory for future builds 2015-04-09T11:08:18.69-0400 [STG] OUT -----> Cleaning up node-gyp and npm artifacts 2015-04-09T11:08:18.70-0400 [STG] OUT -----> No Procfile found; Adding npm start to new Procfile 2015-04-09T11:08:18.71-0400 [STG] OUT -----> Building runtime environment 2015-04-09T11:08:18.71-0400 [STG] OUT -----> Checking and configuring service extensions 2015-04-09T11:08:18.86-0400 [STG] OUT -----> Installing App Management 2015-04-09T11:08:19.07-0400 [STG] ERR 2015-04-09T11:08:22.56-0400 [STG] OUT -----> Uploading droplet (8.9M) 2015-04-09T11:08:29.25-0400 [DEA] OUT Starting app instance (index 0) with guid de2f73ce-e19a-4daa-b4a9-6ab59588a069 2015-04-09T11:08:56.16-0400 [App/0] OUT 2015-04-09T11:08:56.16-0400 [App/0] OUT > bluemix-deploy@ start /home/vcap/app 2015-04-09T11:08:56.16-0400 [App/0] OUT > node app.js 2015-04-09T11:09:55.54-0400 [DEA] ERR Instance (index 0) failed to start accepting connections 2015-04-09T11:09:55.58-0400 [API] OUT App instance exited with guid de2f73ce-e19a-4daa-b4a9-6ab59588a069 payload: {"cc_partition"=>"default", "droplet"=>"de2f73ce-e19a-4daa-b4a9-6ab59588a069", "version"=>"0d4e67c9-1c0c-4e11-bbfb-027bb45e0d67", "instance"=>"eab34911da3947a3bb1b9e2a5564da72", "index"=>0, "reason"=>"CRASHED", "exit_status"=>-1, "exit_description"=>"failed to accept connections within health check timeout", "crash_timestamp"=>1428592195} 2015-04-09T11:09:56.14-0400 [App/0] ERR 2015-04-09T11:10:28.80-0400 [DEA] OUT Starting app instance (index 0) with guid de2f73ce-e19a-4daa-b4a9-6ab59588a069 Any ideas? A: I found out it was an issue with Cloud Foundry starting my app. In digging into my code I was trying to bind to port 8080 locally. That is fine, but however in Cloud Foundry you need to bind to a specified port. To do this you need to read an environment variable called VCAP_APP_PORT. I have pasted a code snippet below on how I fixed it. var express = require("express"), app = express(); var port = process.env.VCAP_APP_PORT || 8080; app.get("/", function (request, response) { response.render("index"); }); app.listen(port); A: Another suggestion: Add this prior to the call to app.listen(...) process.on('uncaughtException', function (err) { console.log(err); }); Your console logs will then include a helpful stack trace if the startup code fails for an unforeseen reason instead of receiving the default "app crashed" message.
{ "pile_set_name": "StackExchange" }
Q: Graphite: How to make historic whisper data available through web app I've recently reconfigured my graphite setup from a single carbon-cache instance to several carbon-cache instances. As I needed to cook this up on a new host without bringing down the old graphite server while setting up, I now have a whisper directory with the historic metrics from the old server that I need to make available through the webapp on the new host. I copied the dir to the new host and added an entry in the webapp local_settings.py: DATA_DIRS = ['/carbon1/whisper','/carbon2/whisper','/carbon3/whisper','/carbon4/whisper','/whisper-archive'] whisper-archive is the dir I'm talking about. Unfortunately, the data is not showing up. Am I doing something wrong or is there a better way to do this? running graphite 0.10.0 source install on freebsd 10.0-RELEASE-p12 A: I think it's just going to look in these places and use the data from the first one it finds. If you want to have the old data in the same graphs as the new one, then I think you're going to have to use whisper-dump to dump the data out of both the old and new metrics and whisper-merge to combine them.
{ "pile_set_name": "StackExchange" }
Q: PrimeFaces PickList : two String fields filter I was wondering if it's possible to have a two fields filter with a picklist of primefaces. I tried this but it's not working. I would like to filter on firstname and name but they are in two different fields. <p:pickList value="#{bean.usersDualModel}" var="user" itemValue="#{user}" itemLabel="#{user.firstname} #{user.name}" converter="user" showSourceFilter="true" showTargetFilter="true" filterMatchMode="contains" > <p:column> <h:outputText value="#{user.firstname} #{user.name}" /> </p:column> </p:pickList> Thanks A: This is not possible with the default component. However you can create a custom filter (example taken from Primefaces manual): <p:pickList value="#{pickListBean.cities}" var="city" itemLabel="#{city}" itemValue="#{city}" showSourceFilter="true" showTargetFilter="true filterMatchMode="custom" filterMatchMode="myfilter"> </p:pickList> function myfilter(itemLabel, filterValue) { //Filter for firstname or name //return true or false } Of course you can also create a custom component by extending the primefaces picklist or create two seperate inputtext fields and fire any filtering manually with javascript/jquery.
{ "pile_set_name": "StackExchange" }
Q: When to use {#v.attrib} vs {!v.attrib}? I have seen some uses of {#v.attrib} in a few of lightning components, and I'm a person who is used to {!v.attrib}. Is there a difference between them or is there a scenario where '#' has to be used/is better instead of '!'? Thanks in advance for your reply! A: If you want to show a value dynamically based on a aura:attribute, generally we tend to use: {!v.attrib} Eg: <ui:button label="{!v.attrib}" /> So if you do cmp.set('v.attrib','test'), then aura:framework automagically does an dirty checking and changes the value accordingly.(Two-way binding) So the label of the <ui:button> is set to test, just think of this as special expression that directly point to the live reference of the attribute in the component(JS perspective), which is quiet similar to {{v.attrib}} expression in Angularjs which eventually does the same thing. What if you want to show a value dynamically based on a aura:attribute but it needs to work only once,when it is rendered in the view initially. So you should go with : {#v.attrib} expression, which might improve the performance if there large no.of such expression(where you don't need such bindings), because it won't be taken into account during dirty checking.AngularJS also has the same one-way binding stuff in its armour : {{::v.attrib}} Here's a video Mastering Lightning Component - Part 1 on this topic. <aura:component> <aura:attribute name="test" type="String" default="world"/> hello {#v.test} // print hello world and does not change hello {!v.test} // prints hello world and 'test' changes based on input value <ui:inputText value="{!v.test}"/> </aura:component>
{ "pile_set_name": "StackExchange" }
Q: for remembering passwords, sessions or cookies or both? If a user decides to remember their password based on a checkbox when logging in, is it good practice to set both session and cookies? or would it be better to just do cookies? I think I understand to do sessions when user logs in and DOES NOT like to remember the password. Which one is good practice for remembering logging in? Thanks for your time! A: Since a session gets killed by default after 20 minutes, what do you think is the best solution for long-time storage? I hope you're not thinking of actually storing the password in either a cookie or a session, but to store some random ID you also store in your database, which you check on every page view?
{ "pile_set_name": "StackExchange" }
Q: Hibernate HQL Projection Using Entities ManyToMany Definitions Issue Problem: HQL query is not returning any results when I reference an entities collection field as part of the HQL statement. It works for one HQL projection for example like this: select inc.categoryTypes as categoryTypes from IncidentEntity inc where (inc.id = :id105019) The categoryTypes is one of the IncidentEntity classes fields (which is a collection defined as a ManyToMany join as seen below). This works fine, but the issue arises when I am attempting to reference another projection collection that is mapped as a ManyToMany join. select inc.categoryTypes as categoryTypes, inc.consequences as consequences from IncidentEntity inc where (inc.id = :id105019) As soon as I do it like this, I get an empty set. Which means the SQL query that hibernate generates isn't returning anything. I have verified this by executing the command within SQL Manager which returns no results. Here is the IncidentEntity: /** * Database entity for the 'incidents' table records.<br> * Entity domain object is {@link nz.co.doltech.ims.shared.domains.Incident} * @author Ben Dol * */ @javax.persistence.Entity(name = "incidents") @Cache(usage=CacheConcurrencyStrategy.TRANSACTIONAL) public class IncidentEntity implements Entity { ... @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "incident_categorytype", joinColumns = { @JoinColumn(name = "incident_id") }, inverseJoinColumns = { @JoinColumn(name = "categorytype_id") }) private Set<CategoryTypeEntity> categoryTypes = new HashSet<CategoryTypeEntity>(); @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "incident_consequence", joinColumns = { @JoinColumn(name = "incident_id") }, inverseJoinColumns = { @JoinColumn(name = "consequence_id") }) private Set<ConsequenceEntity> consequences = new HashSet<ConsequenceEntity>(); ... public Set<CategoryTypeEntity> getCategoryTypes() { return categoryTypes; } public void setCategoryTypes(Set<CategoryTypeEntity> categoryTypes) { this.categoryTypes = categoryTypes; } public Set<ConsequenceEntity> getConsequences() { return consequences; } public void setConsequences(Set<ConsequenceEntity> consequences) { this.consequences = consequences; } ... } CategoryTypeEntity relationship definition: @ManyToMany(fetch = FetchType.LAZY, mappedBy = "categoryTypes") private Set<IncidentEntity> incidents = new HashSet<IncidentEntity>(); ConsequenceEntity relationship definition: @ManyToMany(fetch = FetchType.LAZY, mappedBy = "consequences") private Set<IncidentEntity> incidents = new HashSet<IncidentEntity>(); Data structure: Using Hibernate 3.6.10 Maybe I have setup the definitions wrong, or I am missing a limitation with the HQL here, I'm not sure. Would appreciate any help that I could get here. Thanks! Regards, Ben A: You know that you are generating a Cartesian product with this query, right? The query can be better visualized as: select categoryTypes, consequences from IncidentEntity inc inner join inc.categoryTypes as categoryTypes inner join inc.consequences as consequences where (inc.id = :id105019) Because you haven't specify an explicit join, an INNER JOIN is assumed not a LEFT JOIN. Let's assume there are categories for the specified incident. So this query will return the categories for this incident, which is what you also reported: select categoryTypes from IncidentEntity inc inner join inc.categoryTypes as categoryTypes where (inc.id = :id105019) But when there are no consequences, the INNER JOIN will return no result, so: select categoryTypes, consequences from IncidentEntity inc inner join inc.consequences as consequences where (inc.id = :id105019) will not return anything, but then this can happen for your query too: select categoryTypes, consequences from IncidentEntity inc inner join inc.categoryTypes as categoryTypes inner join inc.consequences as consequences where (inc.id = :id105019)
{ "pile_set_name": "StackExchange" }
Q: Selection field type elements cannot be shown. How to properly add a custom entity representation to Sulu form? Following by Sulu documentation, I try to add selection field type to display collection type resource (Room object) in admin form. Currently, I can select these elements from list, select element selected element but after form submit and reload any record cannot be shown, despite that the Room object exist in Event entity: empty list What I do wrong? Code: sulu_admin.yaml sulu_admin: ... # Registering Selection Field Types in this section field_type_options: selection: room_selection: default_type: list_overlay resource_key: rooms types: list_overlay: adapter: table list_key: rooms display_properties: - name icon: su-clock label: 'app.rooms' overlay_title: 'app.rooms' event_details.xml <property name="rooms" type="room_selection"> <meta> <title>app.rooms</title> </meta> </property> A: Your api response should just contain a flat list of room ids for rooms. Assuming you have an Event entity with a $rooms property, add a public function getRoomIds() {} to your Event entity and add the @VirtualProperty("rooms") annotation to that method. Probably you have to add the @Exclude annotation to public function getRooms() {} EDIT: I just tried it, if you have an entity like the following, it works as expected. If it's still not working, maybe you have a problem with your jms serializer config. /** * @Serializer\ExclusionPolicy("all") */ class Event { /** * @Serializer\Expose() */ private $otherProperty; /** * @var Collection<int, Room> */ private $rooms; public function getRooms(): Collection { return $this->rooms; } /** * @Serializer\VirtualProperty() * @Serializer\SerializedName("rooms") */ public function getRoomIds(): array { return $this->rooms->map(function (Room $room) { return $room->getId(); }); } }
{ "pile_set_name": "StackExchange" }
Q: Android back stack one fragment, when pressing hardware back button shows the back stacked one. Android back stack one fragment, when pressing hardware back button shows the back stacked one. Below is my expected scenario: I have one activity with navigation drawer. Each navigation element navigate to different fragments on click. I want to back stack only the home fragment. when pressing back button from any other fragments , navigate to the home fragment. When pressing the back button from home fragment, app exits. A: You can handle onBackPressed method in this method, comment the line //super.onBackPressed(); @Override public void onBackPressed() { // super.onBackPressed(); //Now check if current fragment is not home fragment // then replace current fragment with home fragment //if current fragment is home fragment then execute the following code Intent homeIntent = new Intent(Intent.ACTION_MAIN); homeIntent.addCategory( Intent.CATEGORY_HOME ); homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(homeIntent); }
{ "pile_set_name": "StackExchange" }
Q: Use Android phone as ARM dev board? Is it possible to have a similar peripheral control with Android then we have when making device drivers? I'm searching for a way to turn off all peripherals on a Android phone (e.g. Display, Wi-Fi, GPS) to put the phone on a power saving mode (1-5 mA). Basically, I want to develop an application that wake up from time to time, get coordinates, exchange information with a server (Wi-Fi or GSM) and then go to sleep, no need for display. Is that possible using a regular android phone? A: You can only program ARM on Android in User Mode. You don't have access to such instructions as MRC in ARM assembly, which require Privileged Modes. Perhaps there are custom ROMs you can install onto your phone to do that, but I doubt it. This web site has the closest description to what you're looking for.
{ "pile_set_name": "StackExchange" }
Q: Ethereum implementation of a non-fungible but divisible token? (ERC721 seems not to work for that) I am struggling currently with finding the right implementation possibility for a token with the following properties: Asset-backed token based on a non-fungible asset (like a piece of art) More than one owner per token (crowd-ownership on each non fungible asset) e.g. multiple owners of one piece of art A non fungible asset would lead into the direction of using ERC721 (which has been used e.g. by cryptokitties). The problem of this standard is that it would not allow multiple owners of a token because each token is not divisible. I thought about multiple options but couldnt find out whether they are possible. For example would it be possible to have an ERC20 token "own" a ERC721? Any suggestions? A: The problem of this standard is that it would not allow multiple owners of a token because each token is not divisible. Is there possibly confusion between the idea of divisibility and fractional ownership? They're quite different concerns. Divisibility is about division. For example, you can divide $100 into two $50 but you wouldn't want to saw a kitty in two because that would be very bad for the cat. Still, joint ownership of a single kitty is possible. It's true that ERC721 considers only a single owner. This is a common pattern that keeps the core standard and code compact but it doesn't prevent joint/fractional ownership, if that is what is needed. The trick is that the "owner" could be a contract. That's up to you at an application-design level. You could put any sort of multi-signature or governance contract in place and give it custody of assets. Hope it helps.
{ "pile_set_name": "StackExchange" }
Q: Add GraphStream graph into my custom jPanel I am working on GraphStream library. For now, When I run my program it opens new window for my graph and separate window for my graph. I tried to create a JFrame and add JPanel into JFrame, after all this I tried to add graph into my JPanel but it says that graph object is not a component. Here is my code: import java.awt.BorderLayout; import java.awt.EventQueue; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import org.graphstream.graph.*; import org.graphstream.graph.implementations.*; public class GraphExplore { static Connection conn2; static String result, result2; static JFrame frame; static JPanel panel; public static void main(String args[]) throws SQLException { EventQueue.invokeLater(new Runnable() { public void run() { try { showData(); } catch (SQLException e) { e.printStackTrace(); } } }); } private static void showData() throws SQLException { JFrame frame = new JFrame(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(30, 50, 1300, 600); panel = new JPanel(); panel.setBorder(new EmptyBorder(5, 5, 5, 5)); panel.setLayout(new BorderLayout(0, 0)); frame.setContentPane(panel); Graph graph = new SingleGraph("tutorial 1"); graph.setAutoCreate(true); graph.setStrict(false); graph.display(); // panel.add(graph); try { Class.forName("org.h2.Driver"); conn2 = DriverManager.getConnection("jdbc:h2:file:G:/hs_data/h2_db/test", "sa", "sa"); } catch (Exception e) { e.printStackTrace(); } Statement stmt2 = conn2.createStatement(); ResultSet rs2 = stmt2.executeQuery("SELECT ANUMBER,BNUMBER,DATETIME FROM TEST"); while (rs2.next()) { result = rs2.getString("ANUMBER"); result2 = rs2.getString("BNUMBER"); graph.addNode(result); graph.addNode(result2); int i; for (i = 0; i < 200; i++) graph.addEdge("string" + i, result, result2); // JOptionPane.showMessageDialog(null, i); } for (Node node : graph) { node.addAttribute("ui.label", node.getId()); } } } This program opens separate windows for both jframe and graph. I want to show my graph into my JFrame or JPanel. Any idea about how to do this? I have seen this link, but it doesn't explains me well. A: As shown in Graph Visualization: Advanced view: Integrating the viewer in your GUI, "you will need to create the viewer by yourself." Also, call setVisible() after you have constructed the frame. It shows error on frame.add(view). It looks like the tutorial cited is a little dated. The Viewer method addDefaultView() now returns a ViewPanel, which can be added to a Container. In the complete example below, a border is set on an enclosing JPanel having GridLayout, and that panel is added to the frame. Also note the need to give the panel a preferred size by overriding getPreferredSize(). Resize the window to see the effect. import java.awt.*; import javax.swing.*; import javax.swing.border.*; import org.graphstream.graph.*; import org.graphstream.graph.implementations.*; import org.graphstream.ui.swingViewer.*; import org.graphstream.ui.view.*; /** @see https://stackoverflow.com/a/45055683/230513 */ public class GraphSwing { public static void main(String args[]) { EventQueue.invokeLater(new GraphSwing()::display); } private void display() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(new GridLayout()){ @Override public Dimension getPreferredSize() { return new Dimension(640, 480); } }; panel.setBorder(BorderFactory.createLineBorder(Color.blue, 5)); Graph graph = new SingleGraph("Tutorial", false, true); graph.addEdge("AB", "A", "B"); Node a = graph.getNode("A"); a.setAttribute("xy", 1, 1); Node b = graph.getNode("B"); b.setAttribute("xy", -1, -1); Viewer viewer = new Viewer(graph, Viewer.ThreadingModel.GRAPH_IN_GUI_THREAD); ViewPanel viewPanel = viewer.addDefaultView(false); panel.add(viewPanel); frame.add(panel); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
{ "pile_set_name": "StackExchange" }
Q: Will exception be thrown back if try catch is already present with only a specific catch? I have a java method as follows regarding exception throws public void wrapException(String input) throws MyBusinessException { // do something } MyBusinessException extends Exception class and returns any(every) exception to the caller. My doubt is, Imagine my code is now changed to handle one specific exception in a special way as below. public void wrapException(String input) throws MyBusinessException { try { // do something } catch (NumberFormatException e) { throw new MyBusinessException("there was a number error", e); } } Would the throws on the method signature still return any exception apart from NumberFormatException to the caller or would I have to redesign the methods as follows? public void wrapException(String input) throws MyBusinessException { try { // do something } catch (NumberFormatException e) { throw new MyBusinessException("there was a number error", e); } catch(Exception e) { throws MyBusinessException(e.message()); } } Appreciate any insight. A: In your first solution, it will just catch exceptions with type NumberFormatException and any class that inherits from it. public void wrapException(String input) throws MyBusinessException { try { // do something } catch (NumberFormatException e) { throw new MyBusinessException("there was a number error", e); } } However in your later solution, since you have catch(Exception e) in your method body, your method will catch any exception that inherits from Exception class including your very own MyBusinessException. Hence, you don't have to put throws MyBusinessException in the method signature. public void wrapException(String input) throws MyBusinessException { try { // do something } catch (NumberFormatException e) { throw new MyBusinessException("there was a number error", e); } catch(Exception e) { throws MyBusinessException(e.message()); } } This is enough; public void wrapException(String input) { try { // do something } catch (NumberFormatException e) { throw new MyBusinessException("there was a number error", e); } catch(Exception e) { throws MyBusinessException(e.message()); } }
{ "pile_set_name": "StackExchange" }
Q: Best way to secure ASP.NET Web API 2 where multiple client use it What is the best way to secure a Web API when you have multiple different clients to use? Each client should have its own API key to connect with. Now I have read different things but I still have some questions. I have found this one: http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/#comments but is it sufficient? So basically: client connects with given username/password client gets a bearer token back client uses this token in each post to the api until the timestamp is over I also have read about giving a API Secret key to each client which he can uses: http://bitoftech.net/2014/12/15/secure-asp-net-web-api-using-api-key-authentication-hmac-authentication/ What is the best approach? A: You are on the right track by using Token based authentication. Here is a link which shows the implementation details- Token based authentication in Web API without any user interface Additionally, I think you can secure the channel using SSL- http://www.c-sharpcorner.com/UploadFile/55d2ea/creating-and-using-C-Sharp-web-application-over-https-ssl/
{ "pile_set_name": "StackExchange" }
Q: Migrating existing database to Amazon RDS How can I import existing MySQL database into Amazon RDS? A: I found this page on the AWS docs which explains how to use mysqldump and pipe it into an RDS instance. Here's their example code (use in command line/shell/ssh): mysqldump acme | mysql --host=hostname --user=username --password acme where acme is the database you're migrating over, and hostname/username are those from your RDS instance. You can connect to RDS as if it were a regular mysql server, just make sure to add your EC2 IPs to your security groups per this forum posting. I had to include the password for the local mysqldump, so my command ended up looking more like this: mysqldump --password=local_mysql_pass acme | mysql --host=hostname --user=username --password acme FWIW, I just completed moving my databases over. I used this reference for mysql commands like creating users and granting permissions. Hope this helps! A: There are two ways to import data : mysqldump : If you data size is less than 1GB, you can directly make use of mysqldump command and import your data to RDS. mysqlimport : If your data size is more than 1GB or in any other format, you can compress the data into flat files and upload the data using sqlimport command. A: I'm a big fan of the SqlYog tool. It lets you connect to your source and target databases and sync schema and/or data. I've also used SQLWave, but switched to SqlYog. Been so long since I made the switch that I can't remember exactly why I switched. Anyway, that's my two cents. I know some will object to my suggestion of Windows GUI tools for MySQL. I actually like the SqlYog product so much that I run it from Wine (works flawlessly from Wine on Ubuntu for me). This blog might be helpful.
{ "pile_set_name": "StackExchange" }
Q: Android - ListView scrollig too slow I have a ListView that has one image and two lines of texts for each element (organized by a RelativeLayout). It works ok, but it's too slow and I know where the problem comes from! This is the getView() method for the custom adapter that I'm using: public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = mLayoutInflater.inflate(R.layout.list_view_item, parent, false); mViewHolder = new ViewHolder(); mViewHolder.cover = (ImageView) convertView.findViewById(R.id.app_icon); mViewHolder.title = (TextView) convertView.findViewById(R.id.selection); mViewHolder.description = (TextView) convertView.findViewById(R.id.app_short_description); convertView.setTag(mViewHolder); } else { mViewHolder = (ViewHolder) convertView.getTag(); } // Here is the origin of the issue ! final Feed currentFeed = getItem(position); mViewHolder.title.setText(currentFeed.getTitle()); mViewHolder.description.setText(currentFeed.getDescription()); try { if(currentFeed.getThumbnailUrl() != null) { downloadThumbnail(mViewHolder.cover, currentFeed.getThumbnailUrl()); } } catch(Exception e) { e.printStackTrace(); } return convertView; } private static class ViewHolder { TextView title; TextView description; ImageView cover; } So I have done some manual benchmarking and it appears that allocating an instance of Feed is the source of this slowness: final Feed currentFeed = getItem(position); I know this because I have written another version of this to compare the two: // Here is the origin of the issue ! //final Feed currentFeed = getItem(position); mViewHolder.title.setText("Title"); mViewHolder.description.setText("Description"); try { if(currentFeed.getThumbnailUrl() != null) { downloadThumbnail(mViewHolder.cover, "some url"); } } catch(Exception e) { e.printStackTrace(); } This one was way smoother (even with the downloadThumbnail() method working). I also precise that there are only 15 items on my ListView. I know that allocating objects is very expensive because of garbage collection but I can't any other way to do it! Any idea? Thanks! EDIT Don't mind too much about the downloadThumbnail() method, it already does some caching. And actually even without any picture, it's still slow. A: When user scrolls the list, getView gets called on the adapter. Make sure that you dont do same things repeatedly, for example generating thumbnail. If number of items is limited (for example video content), then you can create all views and keep it ready for get view. Otherwise you may have to implement cacheing. Below code shows an adapter and listView implementation, where in all listviews are created and stored in memory. Since this is meant for video browsing, memory does not pose any issue. (limited number of content, max 100) Video List Adapter import java.util.ArrayList; import java.util.Formatter; import java.util.HashMap; import java.util.List; import java.util.Locale; import android.content.ContentResolver; import android.content.Context; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Color; import android.provider.MediaStore; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.LinearLayout.LayoutParams; public class VideoListAdapter extends BaseAdapter { private Context mContext = null; private HashMap<String, VideoListItem> mHashedItems = new HashMap<String, VideoListItem>(); private static final String TAG = "VideoListAdapter"; public static final int VIDEO_CONTENT_ID = 0; public static final int VIDEO_CONTENT_TITLE = 1; public static final int VIDEO_CONTENT_DURATION = 2; public static final int VIDEO_CONTENT_RESOLUTION = 3; public static final int VIDEO_CONTENT_MIME = 4; private Cursor mCursorForVideoList = null; private ContentResolver mContentResolver = null; private int mListCount = 0; VideoListAdapter(Context context, ContentResolver cr) { mContext = context; mContentResolver = cr; Log.i(TAG, "In the Constructor"); mCursorForVideoList = mContentResolver.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.MediaColumns._ID, MediaStore.MediaColumns.TITLE, MediaStore.Video.VideoColumns.DURATION, MediaStore.Video.VideoColumns.RESOLUTION }, null, null, null); mListCount = mCursorForVideoList.getCount(); } @Override public int getCount() { return mListCount; } @Override public Object getItem(int arg0) { return getVideoListItem(arg0); } @Override public long getItemId(int position) { //Log.i(TAG, "position : " + position); return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { //Log.i(TAG, "GetView :: Position : " + position); return getVideoListItem(position); } private VideoListItem getVideoListItem(int position) { //Log.i(TAG, "getVideoListItem :: Position : " + position); String key = Integer.toString(position); VideoListItem item = mHashedItems.get(key); if(item == null) { //Log.i(TAG, "New getVideoListItem :: Position : " + position); mCursorForVideoList.moveToPosition(position); mHashedItems.put(key, new VideoListItem(mContext, mContentResolver, mCursorForVideoList)); } return mHashedItems.get(key); } }; Video List View import java.util.Formatter; import java.util.Locale; import android.content.ContentResolver; import android.content.Context; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Typeface; import android.provider.MediaStore; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TableLayout; import android.widget.TextView; import android.widget.LinearLayout.LayoutParams; class VideoListItem extends LinearLayout { private static final String TAG = "VideoListAdapter"; private ImageView mThumbnail = null; private TextView mDuration = null; private TextView mTitle = null; private TextView mResolution = null; private LayoutInflater mLayoutFactory = null; private long mContentId = 0; public VideoListItem(Context context, ContentResolver cr, Cursor cursor) { super(context); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); params.setMargins(10, 10, 10, 10); mLayoutFactory = LayoutInflater.from(context); View thisView = mLayoutFactory.inflate(R.layout.videolistitem, null); addView(thisView); mThumbnail = (ImageView) findViewById(R.id.thumbnail); mDuration = (TextView) findViewById(R.id.DDuration); mTitle = (TextView) findViewById(R.id.DTitle); mResolution = (TextView) findViewById(R.id.DResolution); mThumbnail.setLayoutParams(new LinearLayout.LayoutParams(144, 144)); Resources r = this.getResources(); Bitmap bMap = MediaStore.Video.Thumbnails.getThumbnail(cr, cursor.getLong(VideoListAdapter.VIDEO_CONTENT_ID), MediaStore.Video.Thumbnails.MINI_KIND, null); if(bMap != null) { mThumbnail.setImageBitmap(Bitmap.createScaledBitmap(bMap, 128, 128, true)); } else { mThumbnail.setImageDrawable(r.getDrawable(R.drawable.error)); } mThumbnail.setPadding(16, 16, 16, 16); mTitle.setText(cursor.getString(VideoListAdapter.VIDEO_CONTENT_TITLE)); mTitle.setSingleLine(); mTitle.setTextColor(Color.GREEN); mResolution.setText(cursor.getString(VideoListAdapter.VIDEO_CONTENT_RESOLUTION)); mResolution.setSingleLine(); mResolution.setTextColor(Color.RED); mDuration.setText(stringForTime(cursor.getInt(VideoListAdapter.VIDEO_CONTENT_DURATION))); mDuration.setSingleLine(); mDuration.setTextColor(Color.CYAN); mContentId = cursor.getLong(VideoListAdapter.VIDEO_CONTENT_ID); } public long getContentId() { return mContentId; } private StringBuilder mFormatBuilder = null; private Formatter mFormatter = null; private String stringForTime(int timeMs) { int totalSeconds = timeMs / 1000; mFormatBuilder = new StringBuilder(); mFormatter = new Formatter(mFormatBuilder, Locale.getDefault()); int seconds = totalSeconds % 60; int minutes = (totalSeconds / 60) % 60; int hours = totalSeconds / 3600; mFormatBuilder.setLength(0); if (hours > 0) { return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString(); } else { return mFormatter.format("%02d:%02d", minutes, seconds).toString(); } } }; Shash
{ "pile_set_name": "StackExchange" }
Q: MVC Razor RadioButtonFor in ForEach loop I am new to MVC. I am trying to render questions with options using radio buttons. Here is what I have tried. I am able to display questions with options using radio buttons, but I can select only one radio button across the questions. Model: public class CheckListModel() { IEnumerable<QuestionModel> Questions { get; set; } } Public class QuestionModel() { Int Id { get; set; } string Question { get; set; } IEnumerable<AnswerModel> Answers { get; set; } } Public class AnswerModel() { Int Id { get; set; } string Answer { get; set; } } View: @if (Model != null) { if (Model.CheckListModel != null) { int i = 0; <div class="form-group"> <fieldset> @foreach (var question in Model.CheckListModel.Questions) { <legend>@question.Question</legend> foreach (var answer in question.Answers) { i++; string nameAtt = "Grp" + i.ToString(); <div class="radio"> @Html.RadioButtonFor(a => a.eCheckListModel.Questions.Where( q => q.Id == question.Id).FirstOrDefault().Answers.Where(b => b.Id == answer.Id).FirstOrDefault ().Answer, answer.Id.ToString(), new { @name = nameAtt, @id = nameAtt }) @answer.Answer </div> } } </fieldset> </div> } } A: Your approach wont work because the name attribute of each radio button is not being renered correctly. Using ... new { @name = nameAtt,.. is pointless because Html Helpers override any attempt to set the name attribute. Firstly, populate your view models in the controller (populate each question with the answers relevant to that question) and add a property to the QuestionModel that allows you to bind the selected answer. Models public class CheckListModel { public List<QuestionModel> Questions { get; set; } // use List (easier for indexing the name attribute ... // other properties of model } public class QuestionModel { public int Id { get; set; } public string Question { get; set; } public int SelectedAnswer { get; set; } // Add this public List<AnswerModel> Answers { get; set; } } public class AnswerModel { public int ID { get; set; } public string Answer { get; set; } } View @model YourAssembly.CheckListModel @using (Html.BeginForm()) { .... for (int i = 0; i < Model.Questions.Count; i++) { @Html.HiddenFor(m => m.Questions[i].ID) // for postback <p>@Model.Questions[i].Question</p> for (int j = 0; j < Model.Questions[i].Answers.Count; j++) { <div> @Html.RadioButtonFor(m => m.Questions[i].SelectedAnswer, Model.Questions[i].Answers[j].ID) <span>@Model.Questions[i].Answers[j].Answer</span> </div> } } .... } This will render inputs <input type="hidden" name="Questions[0].ID".., <input type="radio" name="Questions[0].SelectedAnswer".. etc
{ "pile_set_name": "StackExchange" }
Q: CSS Browser Detection I dont understand why the HTML5 website I am working on is different in all browsers. I know it must be CSS, but I dont know what. on Chrome: http://slackmoehrle.com/chrome.png on Safari: http://slackmoehrle.com/safari.png on IE 7: http://slackmoehrle.com/ie7.png on FireFox Mac: http://slackmoehrle.com/firefox.png the style sheet can be found here: http://slackmoehrle.com/css.css Can anyone shed any insight? Many are saying that browser detection is not a good method, but I dont see what to do to make this all work in the various browsers UPDATE: without using a CSS reset: http://slackmoehrle.com/test/without-reset/ with using a CSS reset: http://slackmoehrle.com/test/with-reset/ A: Have a look at using a CSS reset stylesheet My personal favorite is Meyer's: http://meyerweb.com/eric/tools/css/reset/
{ "pile_set_name": "StackExchange" }
Q: How do I debug a stack overflow? I was wondering if anyone has had a similar experience. I am trying to trace the source of a problem but am coming up with nil. I have a project in Delphi 5 which has Report Builder reports on it. I needed an upgraded version of reportbuilder so I tried running the project in Delphi 7. When my project runs and I click a button to view a report, it views fine. However, if I use a paramstr to run the report (showmainform is set false) and show report procedure runs, I get get a stack overflow error. The original code was : if lowercase(ParamStr(1)) = 'termsexceeded' then begin reportsdata.termsexceeded.close; reportsdata.termsexceeded.open; reports.ppTermsExceeded.print; reportsdata.termsexceeded.close; application.terminate; end; And it gave me the stack overflow error on the .print function. The code that works in Delphi 7 is : if lowercase(ParamStr(1)) = 'termsexceeded' then begin reportsdata.termsexceeded.close; reportsdata.termsexceeded.open; reports.left := -10000; reports.show; reports.ppTermsExceeded.print; reportsdata.termsexceeded.close; application.terminate; end; Has anybody got a suggestion on how I could debug this to see if the problem lies with my Delphi 7 or with Reportbuilder ? There are no events on the .show event of the reports form. Any advice on how to get to the bottom of this would be appreciated. Regards A: When you get a stack overflow, use the debugger. It will interrupt your program when the OS throws the exception, and at that time, you can use the debugger's call stack window to see the path a function calls that lead there. You'll probably see a certain function or sequence of functions repeated many times. When you've found the repeating pattern, check the code to see why it's repeating. Look for a condition is supposed to have changed, but doesn't.
{ "pile_set_name": "StackExchange" }
Q: How to collect a number of asynchronous callbacks? Are there any techiques to collect a number of gwt-rpc service callback results? I have a dialog window used to create new or edit existing object. These objects have a number of references to other object. So when user creating or editing an object he may pick one in the ListBox. public class School { private String name; private String address; } public class Car { private String model; private String type; } public class Person { private String firstName; private String lastName; private School school; private Car firstCar; } When the dialog window appears on the screen it should request all available values for all referencing fields. These values are requested with AsyncCallback's via gwt-rpc, so I can handle it one-by-one. service.getAllSchools(new AsyncCallback<List<School>>() { @Override public void onSuccess(List<School> result) { fillSchoolListBox(result); } @Override public void onFailure(Throwable caught) { Window.alert("ups..."); } }); ... service.getAllSchools(new AsyncCallback<List<Car>>() { @Override public void onSuccess(List<Car> result) { fillCarListBox(result); } @Override public void onFailure(Throwable caught) { Window.alert("ups..."); } }); How to get all result in one place? Thanks. A: The best solution would be Command Patter as igorbel said, but if you are beginner you can design for example Bean Container that only contains beans that must be transported at one request. For example: public class BeanContainer{ private ArrayList<School> schools = new ArrayList<School>(); private ArrayList<Car> cars = new ArrayList<Car>; private ArrayList<Person> people = ArrayList<Person>(); public void addSchool(School school){ this.schools.add(school); } public void addSchoolCollection(ArrayList<School> schools){ this.schools.add(schools); } public ArrayList<School> getSchoolCollection(){ return schools; } ... }
{ "pile_set_name": "StackExchange" }
Q: Steam error: ''You are missing the following 32-bit libraries, and Steam may not run: libGL.so.1'' Yeah like i said in the title it brings up the terminal that is installing the plugin then it fails to download them. Then it closes. Next it brings up You are missing the following 32-bit libraries, and Steam may not run: libGL.so.1 Finally I close that and steam box opens up and says Steam-fatal error'' Fatal error:failed to load Steamui.so''. That's basically my problem. A: For me this was solved by: Creating /etc/ld.so.conf.d/steam.conf with the contents: /usr/lib32 /usr/lib/i386-linux-gnu/mesa Running sudo ldconfig to update the shared library cache installing/reinstalling the 32bit mesa libraries: sudo apt-get install --reinstall libgl1-mesa-glx:i386 Source
{ "pile_set_name": "StackExchange" }
Q: Converting a json schema to ng2-tree treemodel in Angular 4 I want to display in Tree view of Json in UI which can be edit and save dynamically. Currently I am trying with TreeModel in Angular 4 but here Json schema and TreeModel schema is different. I searched for the same in internet but could able to find. 1.Is there any way I can convert Json schema to treeModel? 2.Is there other way I can directly use json as input and show/edit it dynamically? TreeModel example: { value: 'Programming languages by programming paradigm', children: [{ value: 'Object-oriented programming', children: [{ value: 'Java' }, { value: 'C++' }, { value: 'C#' } ] }, { value: 'Prototype-based programming', children: [{ value: 'JavaScript' }, { value: 'CoffeeScript' }, { value: 'Lua' } ] } ] } Json Example: { "compileOnSave": false, "compilerOptions": { "outDir": "./dist/out-tsc", "baseUrl": "src", "sourceMap": true, "declaration": false, "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "target": "es5", "typeRoots": [ "node_modules/@types" ], "lib": [ "es2016", "dom" ] } } A: You can build a class and a component for a Json node and recurvisely display them after parsing the Json string into your JsonNode tree. export class JsonNode { value: string; children: JsonNode[]; } Build a tree of JsonNode objects, and in template: selector: 'json-node' template: '... <div *ngFor="let child of children"></div>'
{ "pile_set_name": "StackExchange" }
Q: How to invite a users friends to an event? Facebook Graph API I have an application using the Graph API. I have it creating events for the user, but would like to let the user invite their friends from our site instead of having to go to the events Facebook page. Does anyone know of the request I have to send the friends' IDs too to invite them like with the old API? Or if it even exists? I am finding a lot of the finer details in the API documentation are vague. Thank you! Also, side question, can you send an event photo with the create POST? I see no mention on how to submit a photo with the event creation. Thanks. A: I actually was able to get an answer from the Facebook team and they just told me to use the old API through the new PHP interface. They have yet to convert this functionality and don't know if it will be converted. Edit: Here is the code I used to invite friends after I got the IDs from the new api ($id_array). This is applied in a wrapper around the PHP Facebook object I used to hold all my Facebook specific code. $fb = new FacebookGraph(array( 'appId' => 'xxxx', 'secret' => 'xxxx', 'cookie' => true, )); $fb->api(array( 'method' => 'events.invite', 'eid' => $event_id, 'uids' => $id_array, 'personal_message' => $message, )); A: This is actually possible with the Graph API, specifically the invited connection of the event's object: POST /EVENT_ID/invited/USER_ID Invite a user to an event. Returns true if the request is successful. POST /EVENT_ID/invited?users=USER_ID1,USER_ID2,USER_ID3 Invite multiple users to an event. Returns true if the request is successful. You'll need the create_event permission. More info is available in this post. A: The possibility to invite users to an Event was removed in v2.4 of the Graph API: The Event node no longer supports GET operations on the endpoints /v2.4/{event_id}/invited, /v2.4/{event_id}/likes, or /v2.4/{event_id}/sharedposts. There is no way to invite users to an Event anymore, you have to use facebook.com instead.
{ "pile_set_name": "StackExchange" }
Q: Why is my class variable changing its value between methods? I am trying to load a bitmap animation to the screen. I have a float variable holdTime that is specified to hold the "holdtime" value for the animation. In my constructor I set the holdtimevariable to 0.1f but when I try to access the method in the class that is using the holdTime variable, the value of holdTime has changed to -107374176f. So somewhere between my constructor call and the method call the value has changed from 0.1f to -107374176f. To make things a little bit more clearer let me show you some code: Here is the header file for the Game class, this is where I call the constructor of the Animation class that has the holdTime variable. #pragma once #include "Graphics.h" #include "Surface.h" #include "Animation.h" #include "FrameTimer.h" class Game { public: Game( class MainWindow& wnd ); void Go(); private: void UpdateModel(); private: MainWindow& wnd; FrameTimer ft; Surface surf = Surface("Test32x48.bmp"); Animation testAnimation = Animation(0, 0, 32, 48, 4, surf, 0.1f); }; You see that I have this testAnimation at the bottom of the class. The last argument in the constructor call is the value that is ought be in holdTime. This is how my Animation header file looks like: #include "Surface.h" #include "Graphics.h" #include <vector> class Animation { public: Animation(int x, int y, int width, int height, int count, const Surface& sprite, float holdtime, Color chroma = Colors::Magenta); void Update(float dt); private: void Advance(); private: std::vector<RectI> frames; int iCurFrame = 0; float holdTime = 0; float curFrameTime = 0.0f; }; And this is the Animation Cpp file: #include "Animation.h" Animation::Animation(int x, int y, int width, int height, int count, const Surface& sprite, float holdtime, Color chroma) : sprite(sprite), holdTime(holdTime), chroma(chroma) { for (int i = 0; i < count; i++) { frames.emplace_back(x + i * width, x + (i + 1) * width,y, y + height); } } void Animation::Update(float dt) { curFrameTime += dt; while(curFrameTime >= holdTime) { Advance(); curFrameTime -= holdTime; } } void Animation::Advance() { if (++iCurFrame >= frames.size()) { iCurFrame = 0; } } There is only one method that is making use of holdTime and that is the method Update(float dt). If we go back to the Game class and look at the Game.cpp file: #include "MainWindow.h" #include "Game.h" Game::Game( MainWindow& wnd ) : wnd( wnd ), gfx( wnd ) { } void Game::Go() { UpdateModel(); } void Game::UpdateModel() { testAnimation.Update(ft.Mark()); } In the Method Go() we call the method UpdateModel() which in turn is calling the Update() method in the animation class. This means that the first method to be executed in the Animation class after the constructor call is the update() method. When I debug the program I can see that the value of holdtime has changed between the constructor call and the Update() method call. But I don't know how since it I am not modifying the value somewhere else. It also seemes that the new value of holdTime is garbage value. It became a lot of code in this question and it looks a bit messy and even though I lack the skills of writing a good Title I hope I made you somewhat clear what my problem is. Thanks! Update: Here is the code for the FrameTimer class since the value returned from one of its methods is passed in into the Update() method: FrameTimer.H: #pragma once #include <chrono> class FrameTimer { public: FrameTimer(); float Mark(); private: std::chrono::steady_clock::time_point last; }; FrameTimer.cpp: #include "FrameTimer.h" using namespace std::chrono; FrameTimer::FrameTimer() { last = steady_clock::now(); } float FrameTimer::Mark() { const auto old = last; last = steady_clock::now(); const duration<float> frameTime = last - old; return frameTime.count(); } Edit: main.cpp: int WINAPI wWinMain( HINSTANCE hInst,HINSTANCE,LPWSTR pArgs,INT ) { MainWindow wnd( hInst,pArgs ); Game game( wnd ); while( wnd.ProcessMessage() ) { game.Go(); } } As you can see the game.Go() method is the first method that is called in main. A: Your Animation constructor is at fault: Animation::Animation(int x, int y, int width, int height, int count, const Surface& sprite, float holdtime, Color chroma) : sprite(sprite), holdTime(holdTime), chroma(chroma) { for (int i = 0; i < count; i++) { frames.emplace_back(x + i * width, x + (i + 1) * width,y, y + height); } } Here you attempt to initialise the member holdTime from the parameter holdTime. Except, there is no parameter holdTime. There is only the parameter holdtime. Hence instead you are actually initialising the member holdTime from itself (the next nearest "match" for that name), so it only retains its original, unspecified value (and in fact, reading an uninitialised variable results in your program having undefined behaviour). So, you see, your member variable doesn't "change" at all — you never set it correctly. You'd have known that had you put some diagnostic output inside that constructor to examine the value and see whether it's what you thought it should be. None of the rest of the code was relevant or necessary. A properly-configured compiler should have warned you about this.
{ "pile_set_name": "StackExchange" }
Q: Dependency on 3rd party at runtime? We have created an applet with javafx and it seems that in order to load the applet several jar, jnlp and js files are required to be downloaded from dl.javafx.com. I tried to work out which files were needed so I could host them on our own server but after spending an hour or so on it I got tired of reading code and gave up. Doesn't it seem bizarre that to use javafx the client has a dependency on the javafx server? There was an instance a few months ago where their server was down which is completely unacceptable. I feel like scrapping it and starting again in something else but I can't throw a years work away. What are everyone else's views? Have you experienced/solved this? Any suggestions where I should go from here will be gratefully accepted. A: This issue has come up a few times and it is one of the main gripes people have with JavaFX. There is a dependency on the runtime, however I believe it is technically possible to distribute an app "offline" (though I've never tried it). See here and here. I am not sure whether or not it is a breach of the license to distribute offline. I have sympathy with your frustration, but I would argue that it would not be worth scrapping a year's work. I imagine the uptime of the Oracle servers would be no worse than any outage that could be expected of any web application.
{ "pile_set_name": "StackExchange" }
Q: How can I create a /* comments section with /// like in XCode? In XCode, there is an add-on called vvdocument, which can detect three / hits, and transfer /// into: /*! * @author Robbie Yi JIANG, 29-Jan-2016 14:01:45 * * */ How can I do this in Vim. A: The method in my earlier answer doesn't transform well to dynamic content. This is where snippet plugins like UltiSnips and SnipMate come in. I'll provide a demo of UltiSnips here. Install it using your favourite method from How do I install a plugin in vim/vi? Now, make an UltiSnips directory in your .vim or _vimfiles directory. In it, place a c.snippet file containing: snippet /// "My header" A /*! * @author Robbie Yi JIANG, `date +'%d-%b-%Y %T'` * * */ endsnippet Now, if you open a C file and type ///, it should automatically get replaced with the header, including the current date and time. That's it! Usually, UltiSnips inserts a snippet when you press Tab. Here, we have specified that the snippet should be automatically entered - that's what the A at the end of the first line indicates. Checkout :help UltiSnips-syntax for more information on writing snippets. Most people, however, start off with a collection of snippets, such as vim-snippets. There are too many to describe here, but you might some of them very useful. A: One way would be to create a file containing this snippet, and read it when you type ///. For example, create ~/.vim/snippets/my_header.snip containing this header. Then define this mapping: inoremap /// <esc>:r ~/.vim/snippets/my_header.snip<cr>i Or: inoremap /// <esc>:call append(line('.')-1, readfile(expand('~/.vim/snippets/my_header.snip')))<cr>i In the first mapping, your cursor will be placed on the first line of the inserted text; and in the second, the cursor will be placed below the inserted text. Perhaps the simplest mapping, in terms of jumping around modes, is: inoremap /// <c-r><c-o>=readfile(expand('~/.vim/snippets/my_header.snip'))<cr> For more general usage, you might want to look into snippet plugins. UltiSnips and SnipMate are two popular ones. I don't use either, so I won't recommend one. A: Write a function that returns the string and call it. function! InsertHeader() let l:header = "/*!\n" \. "* @author Robbie Yi JIANG, " . strftime('%d-%b-%Y %H:%M:%S') . "\n" \. "*\n" \. "* \n" \. "*/\n" return l:header endfunction inoremap /// <C-R>=InsertHeader()<Enter><C-O>2k<C-O>$ The details of strftime depend on your platform, if you're not on Windows and it's not working then you'll need to man strftime to figure out the arguments. This works in insert mode but it does weird things to forward-slash processing. If you're doing C++-style // comments, the second slash won't come out until you type a space or something after it. The <C-R>= inserts an expression at the cursor position. The InsertHeader()<Enter> bit is the expression that gets evaluated. I build up the string line by line in the function, . is string concatenation and \ is the line continuation character (where continuation says "combine this with the previous line," in contrast to how C and its family do it). Finally, two <C-O> operations, one to move up two lines and one to move to the end of the line where presumably a file comment is going to be entered; note the space at the end of the string in the fourth line of l:header.
{ "pile_set_name": "StackExchange" }
Q: Log scale with a different factor and base I see that set_xscale accepts a base parameter, but I also want to scale with a factor; i.e. if the base is 4 and the factor is 10, then: 40, 160, 640, ... Also, the documentation says that the sub-grid values represented by subsx should be integers, but I will want floating-point values. What is the cleanest way to do this? A: I'm not aware of any built-in method to apply a scaling factor after the exponent, but you could create a custom tick locator and formatter by subclassing matplotlib.ticker.LogLocator and matplotlib.ticker.LogFormatter. Here's a fairly quick-and-dirty hack that does what you're looking for: from matplotlib import pyplot as plt from matplotlib.ticker import LogLocator, LogFormatter, ScalarFormatter, \ is_close_to_int, nearest_long import numpy as np import math class ScaledLogLocator(LogLocator): def __init__(self, *args, scale=10.0, **kwargs): self._scale = scale LogLocator.__init__(self, *args, **kwargs) def view_limits(self, vmin, vmax): s = self._scale vmin, vmax = LogLocator.view_limits(self, vmin / s, vmax / s) return s * vmin, s * vmax def tick_values(self, vmin, vmax): s = self._scale locs = LogLocator.tick_values(self, vmin / s, vmax / s) return s * locs class ScaledLogFormatter(LogFormatter): def __init__(self, *args, scale=10.0, **kwargs): self._scale = scale LogFormatter.__init__(self, *args, **kwargs) def __call__(self, x, pos=None): b = self._base s = self._scale # only label the decades if x == 0: return '$\mathdefault{0}$' fx = math.log(abs(x / s)) / math.log(b) is_decade = is_close_to_int(fx) sign_string = '-' if x < 0 else '' # use string formatting of the base if it is not an integer if b % 1 == 0.0: base = '%d' % b else: base = '%s' % b scale = '%d' % s if not is_decade and self.labelOnlyBase: return '' elif not is_decade: return ('$\mathdefault{%s%s\times%s^{%.2f}}$' % (sign_string, scale, base, fx)) else: return (r'$%s%s\times%s^{%d}$' % (sign_string, scale, base, nearest_long(fx))) For example: fig, ax = plt.subplots(1, 1) x = np.arange(1000) y = np.random.randn(1000) ax.plot(x, y) ax.set_xscale('log') subs = np.linspace(0, 1, 10) majloc = ScaledLogLocator(scale=10, base=4) minloc = ScaledLogLocator(scale=10, base=4, subs=subs) fmt = ScaledLogFormatter(scale=10, base=4) ax.xaxis.set_major_locator(majloc) ax.xaxis.set_minor_locator(minloc) ax.xaxis.set_major_formatter(fmt) ax.grid(True) # show the same tick locations with non-exponential labels ax2 = ax.twiny() ax2.set_xscale('log') ax2.set_xlim(*ax.get_xlim()) fmt2 = ScalarFormatter() ax2.xaxis.set_major_locator(majloc) ax2.xaxis.set_minor_locator(minloc) ax2.xaxis.set_major_formatter(fmt2)
{ "pile_set_name": "StackExchange" }
Q: Can't upload files larger than 97.66 KB in Yii2 Framework with Kartik's FileInput widget When I try to upload a file larger than 97.66 KB I get this error (translated from spanish): "File is too large. Its size cannot exceed 97.66 Kib." This is my widget setup: Modal::begin([ //'title'=>'File Input inside Modal', 'header' => 'Agregar foto', 'toggleButton' => [ 'label'=>'Agregar foto', 'class'=>'btn btn-default', //'href' => Url::to(['afiliado/foto']), 'value' => Url::to('index.php?r=afiliado/foto&id=' . $model->id), ], ]); echo $form->field($model, 'image')->widget(FileInput::classname(), [ 'options' => ['accept' => 'image/*'], 'pluginOptions'=>[ 'maxFileCount' => 1, 'allowedFileExtensions'=>['jpg','jpeg','gif','png'], 'showUpload' => false, 'maxImageWidth' => 2400, 'maxImageHeight' => 2400, 'resizeImage' => true, 'maxFilePreviewSize' => 10240, 'minImageWidth' => 50, 'minImageHeight'=> 50, 'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ', 'maxFileSize' => 1024 ], ]); Modal::end(); And in My php.ini, I set: upload_max_filesize = 99MB post_max_size = 100MB Thanks in advance. A: You need to get the file using UploadedFile::getInstance('image'), and change you model rules to use maxSize around 1024 * 1024 * 100 to set limit around 100MB [['image'], 'file', 'skipOnEmpty' => false, 'extensions' => 'jpg, png, gif, jpeg', 'maxSize' => 1024 * 1024 * 100, 'tooBig' => 'The file was larger than 100MB. Please upload a smaller file.', ],
{ "pile_set_name": "StackExchange" }
Q: Ordering a List by string to find the newer version C# I have a folder with several Directories that are named after a version of an update such as UPDATE_20080311_3.5.9. I need to find the latest update on that list by veryfing the "3.5.9", I made a code to parse the name and add just the version to a list. Is there anyway to Sort tha list by using List.Sort in order to get the latest version "number"? This is the code I made so far, I don't know how to properly use the .Sort() method and if this can be done. I appreciate any help given public string NewerVersion(string Directoria) { List<string> Lista = new List<string>(); DirectoryInfo dir = new DirectoryInfo(Directoria); DirectoryInfo[] dirs = dir.GetDirectories(); foreach (DirectoryInfo Info in dirs) { string Dir = Info.Name.ToString(); Lista.Add(Dir.Substring(Dir.LastIndexOf('_'), Dir.Length)); } Lista.Sort() //Lista.ToArray(); } A: You can use Version which implements IComparable, so it supports sorting. For example with this LINQ query: Version version = null; Version lastVersion = new DirectoryInfo(Directoria).EnumerateDirectories() .Where(d => d.Name.StartsWith("UPDATE_")) .Select(d => new {Directory = d, Token = d.Name.Split('_')}) .Where(x => x.Token.Length == 3 && Version.TryParse(x.Token[2], out version)) .Select(x => new {x.Directory, Date = x.Token[1], Version = version}) .OrderByDescending(x => x.Version) .Select(x => x.Version) .FirstOrDefault(); string latestVersion = lastVersion.ToString(); // if you want it as string After I find the newer version I need to be able to return the name of the directory Then use this query: var lastVersion = new DirectoryInfo(Directoria).EnumerateDirectories() .Where(d => d.Name.StartsWith("UPDATE_")) .Select(d => new {Directory = d, Token = d.Name.Split('_')}) .Where(x => x.Token.Length == 3 && Version.TryParse(x.Token[2], out version)) .Select(x => new {x.Directory, Date = x.Token[1], Version = version}) .OrderByDescending(x => x.Version) .FirstOrDefault(); if (lastVersion != null) Console.WriteLine(lastVersion.Directory.FullName); A: Edit: Continuing from your solution, there is a problem which the way you add your item: string Dir = Info.Name.ToString(); Lista.Add(Dir.Substring(Dir.LastIndexOf('_'), Dir.Length)); Notice two mistakes here: You get the Substring from LastIndexOf('_') instead of from LastIndexOf('_') + 1, which is what you really want You use Dir.Length while you should use Dir.Length - LastIndexOf('_') + 1 instead Change that into: string Dir = Info.Name.ToString(); int indexStart = Dir.LastIndexOf('_') + 1; Lista.Add(Dir.Substring(indexStart, Dir.Length - indexStart)); Then you could further process the Lista that you have populated to have the version number alone by LINQ OrderBy and ThenBy as well as string.Split('.') var result = Lista.Select(x => x.Split('.')) .OrderBy(a => Convert.ToInt32(a[0])) .ThenBy(a => Convert.ToInt32(a[1])) .ThenBy(a => Convert.ToInt32(a[2])) .Last(); string finalVersion = string.Join(".", result); To get the final version among the listed items. To get your directory path back based on your finalVersion, simply do: string myDirPath = dirs.Select(x => x.FullName).SingleOrDefault(f => f.EndsWith(finalVersion));
{ "pile_set_name": "StackExchange" }
Q: Resolving NUnit "No suitable constructor was found" message I have a unit test class: [TestFixture] public class SomeClassIntegrationTests : SomeClass With public constructor: public SomeClassIntegrationTests (ILogger l) : base(l) { } When I attempt to run the test I get "No suitable constructor was found" error. I tried changing the TestFixture attribute to [TestFixture(typeof(ILogger))] but it results in the same error message not allowing me to run or debug the test. Any idea how to modify the TestFixture attribute to get the test to run or resolve this issue in some other way? A: You probable need an instance of a class implementing ILogger. Option 1: use null (if the logger is not really required): [TestFixture(null)] Option 2: use always the same concrete class (or a mock): add a parameterless constructor SomeClassIntegrationTests() : this(new MyLogger()) { } and [TestFixture] Option 3: you may want to test with different loggers SomeClassIntegrationTests(Type t) : this((Ilogger)Activator.CreateInstance(t)) { } and [TestFixture(typeof(MyLogger))]
{ "pile_set_name": "StackExchange" }
Q: Number of Strings with two specific letters How many ways can you construct a string four letters (from 26 alphabet characters) that have both the letters j and k in them? A: It is easier to count the complement. There are $25^4$ strings that don't have $j$, and $25^4$ that don't have $k$. If we add these, we will count twice the strings that have neither $j$ nor $k$. There are $24^4$ of these. So the required number is $$26^4 -\left(25^4+25^4-24^4\right).$$
{ "pile_set_name": "StackExchange" }
Q: Read hexadecimal from file with scilab I have a file that looks like the following: Time M1:Address 480008C0 0 79F9446F 0.000125 7AE7446B 0.00025 7BA8446F ... It is 2 numbers separated by a tab, one is a hexadecimal number. I am looking to read these into a decimal array in scilab. I have tried to open and read the file as follows: u=mopen('proper_log_with_fail.txt','r'); // open the file for reading s = mscanf(u, '%s'); // Forget the first line [time,val]=mfscanf(u,'%e\t%x'); // Get the second line So i am not ever able to read any values ...? I cannot even read the first string? Am i doing something super obvious wrong? A: Maybe a typo, but for the first row you are using mscanf which should be mfscanf for reading from file. When changing this it shows that your first line isn't matching, note that %sonly matches one word and then stops at the next whitespace. To read (and discard) the first line, use mgetl and tell it to read 1 line. If the rest of the input file is data formatted the same way, you can use the niter argument of mfscanf to keep matching up until the end of the file (EOF). file_path = 'proper_log_with_fail.txt'; // open the file for reading fd=mopen(file_path,'r'); // Read/display header line number_of_lines_to_read = 1; header = mgetl(fd, number_of_lines_to_read); disp(header); // Scan all lines up until EOF niter = -1 s = mfscanf(niter, fd, '%e %x'); disp(s) // Close the file after reading mclose(fd)
{ "pile_set_name": "StackExchange" }
Q: AngularJS with TypeScript $resource error: "Response does not match configured parameter" I have an AngularJS + TypeScript app and I keep getting the following error: Error: $resource:badcfg Response does not match configured parameter Error in resource configuration for action: Expected response to contain an get but got an object (Request: array GET) My AngularJS version is 1.4.8 and TypeScript version is 3.0.1. My tsconfig.json looks like this: { "compileOnSave": true, "compilerOptions": { "allowJs": true, "lib": [ "dom", "es5", "scripthost" ], "noImplicitAny": true, "noEmitOnError": true, "removeComments": false, "sourceMap": true, "target": "es5" }, "include": [ "App/TypeScriptCode/**/*.ts", "typings" ], "exclude": [ "node_modules", "definitions", "wwwroot", "App/Old", "Scripts", "*.js" ] } And here is my package.json { "dependencies": { "@types/angular": "^1.6.49", "@types/angular-resource": "^1.5.14", "@types/uuid": "^3.4.3", "npm": "^6.3.0", "ts-node": "^7.0.0" }, "devDependencies": { "angular": "1.5.0", "bootstrap": "3.3.6", "grunt": "0.4.5", "grunt-bower-task": "0.4.0", "typescript": "^3.0.1", "typings": "1.3.0" }, "name": "my-app", "private": true, "scripts": { "demo": "./node_modules/.bin/ts-node ./test.ts" }, "version": "1.0.0" } The error happens in function GetEmployeeTypes in the following controller: namespace App { 'use strict'; class EmployeeTypeController { noRecords: boolean; employeeTypeApi: IEmployeeTypeApi; storage: ngStorage.IStorageService; /// public constructor($localStorage: ngStorage.IStorageService, employeeTypeApi: IEmployeeTypeApi) { this.noRecords = true; this.employeeTypeApi = employeeTypeApi; this.storage = $localStorage; this.GetEmployeeTypes(); } /// public GetEmployeeTypes(): void { const employeeTypes: IEmployeeType[] = this.employeeTypeApi.employeeType.get(function success(): void { this.storage.employeeTypes = employeeTypes; }); }; } angular .module('App') .controller('EmployeeTypeController', EmployeeTypeController); } The api service EmployeeTypeApi for loading employee types from the backend looks like this: namespace App { 'use strict'; export interface IEmployeeTypeApi { employeeType: IEmployeeTypeClass; } export class EmployeeTypeApi implements IEmployeeTypeApi { constructor(public $resource: angular.resource.IResourceService) {} publishDescriptor: angular.resource.IActionDescriptor = { method: 'GET', isArray: true }; public employeeType: IEmployeeTypeClass = this.$resource<IEmployeeType[], IEmployeeTypeClass>('https://localhost:44300/api/employeetypes', null, { publish: this.publishDescriptor }); } // Now register the service with the Angular app angular .module('App') .service('employeeTypeApi', EmployeeTypeApi); } And finally, here are IEmployeeType and IEmployeeTypeClass: namespace App { export interface IEmployeeType extends angular.resource.IResource<IEmployeeType> { id: number; clientId: number; employeeTypeName: string; description: string; $publish(): IEmployeeType; $unpublish(): IEmployeeType; } } namespace App { export interface IEmployeeTypeClass extends angular.resource.IResourceClass<IEmployeeType[]> { get(): IEmployeeType[] ; get(onSuccess: Function): IEmployeeType[]; publish(): IEmployeeType[]; } } So what I am trying to achieve here is to load an array of IEmployeeType objects from the backend. The backend itself is an ASP.NET Web API 2 service, consisting of a number of controllers. I've verified that the controller for loading Employee Type data is correctly called and it does return an array of EmployeeType instances, meaning the problem is most likely somewhere in the front end code. As you can see in EmployeeTypeApi, I've clearly set the isArray flag to "true", so I am not sure why the error is occurring. What am I doing wrong here? A: The problem was the following, in EmployeeTypeApi I have a definition for how the "publish" method should behave, i.e. this: publishDescriptor: angular.resource.IActionDescriptor = { method: 'GET', isArray: true }; However, in my EmployeeTypeController, I call the "get" method instead: const employeeTypes: IEmployeeType[] = this.employeeTypeApi.employeeType.get(function success(): void { this.storage.employeeTypes = employeeTypes; }); Since there was no definition of how "get" should behave, i.e. what request method to use and what data type to expect, it defaulted to expecting an object and thus it produced the error I outlined in my original post. Once I replaced "get" with "publish" in the controller, the error went away. Of course, the better solution is to set the "isArray" flag for "get" to true, but either way, the problem is solved now.
{ "pile_set_name": "StackExchange" }
Q: How to know whether the window is maximized or minimised in extjs? Does any one know how to check whether the form is maximised or minimised in IE8. Raj A: Its solved by using this code: var S = this.tabpanelFormation.getPosition(); if (Ext.isIE8 && S[0] == 751) { this.tabpanelFormation.setPagePosition(749,370,true); this.tabpanelFormation.setHeight(230); this.tabpanelFormation.setWidth(350); } If its maximised then S[0] = 751. By this we can find whet
{ "pile_set_name": "StackExchange" }
Q: using javax.tools.JavaCompiler etc I am looking for working examples of Oracle's Java Compiler API usage. I want to build something close to javac to customize/extend errors logging capabilities. A: See the STBC (the SSCCE Text Based Compiler). The source is available in stbc.zip.
{ "pile_set_name": "StackExchange" }
Q: MYSQL Select From 2 Table And Group Them One of them keep hotel's information and one of them keep their price within the date range. My hotel information table CREATE TABLE IF NOT EXISTS `yurtici_oteller` ( `yo_id` int(10) NOT NULL AUTO_INCREMENT, `yo_bolge_id` int(10) NOT NULL, `yo_konaklama` int(10) NOT NULL, `yo_isim` varchar(150) COLLATE utf8_turkish_ci NOT NULL, `yo_seo_isim` varchar(200) COLLATE utf8_turkish_ci NOT NULL, `yo_konum` varchar(300) COLLATE utf8_turkish_ci NOT NULL, `yo_resim` varchar(300) COLLATE utf8_turkish_ci NOT NULL, `yo_resim_k` varchar(300) COLLATE utf8_turkish_ci NOT NULL, `yo_video` varchar(1000) COLLATE utf8_turkish_ci NOT NULL, `yo_harita` varchar(1000) COLLATE utf8_turkish_ci NOT NULL, `yo_aciklama` text COLLATE utf8_turkish_ci NOT NULL, `yo_yemek` int(3) NOT NULL, `yo_oda` int(3) NOT NULL, `yo_hizmet` int(3) NOT NULL, `yo_aktivite` int(3) NOT NULL, `yo_genel_puan` int(3) NOT NULL, PRIMARY KEY (`yo_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci AUTO_INCREMENT=11 ; INSERT INTO `yurtici_oteller` (`yo_id`, `yo_bolge_id`, `yo_konaklama`, `yo_isim`, `yo_seo_isim`, `yo_konum`, `yo_resim`, `yo_resim_k`, `yo_video`, `yo_harita`, `yo_aciklama`, `yo_yemek`, `yo_oda`, `yo_hizmet`, `yo_aktivite`, `yo_genel_puan`) VALUES (9, 3, 4, 'DELPHİN DE LUXE RESORT ALANYA', 'delphin-de-luxe-resort-alanya', 'ALANYA / OKURCALAR', '', '', '', '', '<h1>OTEL HAKKINDA</h1>\r\n\r\n<p>Denize Uzaklığı (sıfır) , Hava Alanına Uzaklığı (90 km) , Şehir Merkezine Uzaklığı (10 km)</p>\r\n\r\n<h1>KONSEPT</h1>\r\n\r\n<div style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-size: 11px; background-color: rgb(210, 209, 208); color: rgb(0, 0, 0); font-family: Verdana, Geneva, sans-serif; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 11px; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-position: initial initial; background-repeat: initial initial;">ULTRA HER ŞEY DAHİL</div>\r\n\r\n<p style="text-align:start">Ultra her şey dahil sisteminde olup; a&ccedil;ık b&uuml;fe&nbsp;kahvaltı, &ouml;ğle ve akşam yemeği, brunch (Pazar&nbsp;g&uuml;nleri), &ccedil;ocuk akşam yemeği ile 10.00-24.00&nbsp;arası t&uuml;m yerli ve bazı ithal alkoll<span style="font-size:11px"><span style="font-family:verdana,geneva,sans-serif">&uuml; / alkols&uuml;z&nbsp;i&ccedil;ecekler &uuml;cretsizdir.</span></span></p>\r\n\r\n<h1>OTEL &Ouml;ZELLİKLERİ</h1>\r\n\r\n<p><span style="background-color:rgb(210, 209, 208); color:rgb(0, 0, 0); font-family:verdana,geneva,sans-serif; font-size:11px">Tesiste 2 adet y&uuml;zme havuzu, 2 adet &ccedil;ocuk&nbsp;havuzu, kapalı y&uuml;zme havuzu, kapalı &ccedil;ocuk&nbsp;havuzu, jakuzi havuzu, aquapark, ana restaurant,&nbsp;6 adet a la carte restaurant, fantasy-snack bar,&nbsp;Orient Cafe, havuz bar, Snack Bar, Delphin Pub,-&nbsp;Atlantis disko, vitamin bar, iskele bar, garden&nbsp;secret bar, relax bar, oda servisi, animasyon,&nbsp;mini club (4-12 yaş), emanet kasalar (odalarda),&nbsp;2 adet tenis kortu, T&uuml;rk Hamamı, sauna,&nbsp;buhar odası, fitness, masa tenisi, su topu, su&nbsp;jimnastiği, jimnastik, telefon, faks, internet,&nbsp;motorlu su sporları, tenis ekipmanları ve dersi&nbsp;(rezervasyonlu), masaj, kese, dalış okulu, video&nbsp;oyunları, estetik merkezi, alışveriş merkezi,&nbsp;kuaf&ouml;r, &ccedil;amaşır yıkama-&uuml;t&uuml;leme, doktor, bowling&nbsp;hizmetleri sunulmaktadır.</span></p>\r\n\r\n<h1>ODA &Ouml;ZELLİKLERİ</h1>\r\n\r\n<p><span style="background-color:rgb(210, 209, 208); color:rgb(0, 0, 0); font-family:verdana,geneva,sans-serif; font-size:11px">416 adet deluxe standartlı oda bulunmaktadır.&nbsp;Odalarda merkezi klima sistemi, uydu-TV,&nbsp;minibar (soft i&ccedil;ecekler), telefon, elektronik kasa&nbsp;ve f&ouml;n makinesi standart olarak mevcuttur.</span></p>\r\n\r\n<h1>AKTİVİTELER</h1>\r\n\r\n<p><strong>&Uuml;cretli Aktiviteler</strong><br />\r\nBowling , Banana , Bilardo , Dalgı&ccedil;lık Okulu , Jet Ski , Kano , Parasailing , Disco , Masaj<br />\r\n<strong>&Uuml;cretsiz Aktiviteler</strong><br />\r\nAerobic , Animasyon , Beach Voley , Dart , Masa Tenisi , Su Kayağı , Fitness , Hamam , Sauna , İnternet Wireless , Tenis Kortu.<br />\r\n&nbsp;</p>\r\n', 0, 0, 0, 0, 0), (10, 4, 7, 'Deneme Oteli', 'deneme-oteli', 'asgasgasg', 'tatil_1_sifresi_1.jpg', 'tatil_1_sifresi_2.jpg', 'asgasgsga', 'sagsagsagsag', '<h1>OTEL HAKKINDA</h1>\r\n\r\n<p>hakkında</p>\r\n\r\n<h1>KONSEPT</h1>\r\n\r\n<p>konsept</p>\r\n\r\n<h1>OTEL &Ouml;ZELLİKLERİ</h1>\r\n\r\n<p>&ouml;zellik</p>\r\n\r\n<h1>ODA &Ouml;ZELLİKLERİ</h1>\r\n\r\n<p>Oda</p>\r\n\r\n<h1>AKTİVİTELER</h1>\r\n\r\n<p>aktivite</p>\r\n', 100, 100, 100, 100, 100); Price table CREATE TABLE IF NOT EXISTS `yurtici_otel_fiyatlar` ( `yof_id` int(10) NOT NULL AUTO_INCREMENT, `yof_o_id` int(10) NOT NULL, `yof_a_id` int(10) NOT NULL, `yof_site` varchar(750) COLLATE utf8_turkish_ci NOT NULL, `yof_tarih_1` date NOT NULL, `yof_tarih_2` date NOT NULL, `yof_fiyat` varchar(20) COLLATE utf8_turkish_ci NOT NULL, `yof_fiyat_tur` int(1) NOT NULL, PRIMARY KEY (`yof_id`), KEY `of_fiyat_tur` (`yof_fiyat_tur`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci AUTO_INCREMENT=10 ; INSERT INTO `yurtici_otel_fiyatlar` (`yof_id`, `yof_o_id`, `yof_a_id`, `yof_site`, `yof_tarih_1`, `yof_tarih_2`, `yof_fiyat`, `yof_fiyat_tur`) VALUES (3, 9, 1, 'asgasg', '1111-12-29', '1111-11-11', '125', 2), (4, 9, 2, 'deneme fiyat', '2013-11-20', '2014-12-20', '100', 2), (5, 9, 1, 'qwtqwt', '2012-11-11', '2014-12-12', '1525', 2), (6, 9, 3, 'asgasgags', '2013-12-04', '2013-12-05', '153', 2), (7, 9, 6, '235235', '2013-04-12', '2013-04-19', '153', 2), (8, 9, 8, 'asgasg', '2013-04-18', '2013-04-29', '315', 2), (9, 10, 9, 'asgasg', '2013-04-11', '2013-04-18', '1521', 2); Acenta Table CREATE TABLE IF NOT EXISTS `acentalar` ( `a_id` int(10) NOT NULL AUTO_INCREMENT, `a_isim` varchar(150) COLLATE utf8_turkish_ci NOT NULL, `a_seo_isim` varchar(200) COLLATE utf8_turkish_ci NOT NULL, PRIMARY KEY (`a_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci AUTO_INCREMENT=10 ; INSERT INTO `acentalar` (`a_id`, `a_isim`, `a_seo_isim`) VALUES (1, 'Jolly Tur', 'jolly-tur'), (2, 'BKM TUR', 'bkm-tur'), (3, 'ANI TUR', 'ani-tur'), (4, 'TURSAN TURİZM', 'tursan-turizm'), (5, 'TATİL.COM', 'tatil-com'), (6, 'TEZ TOUR', 'tez-tour'), (7, 'TURON9', 'turon9'), (8, 'GEZİNOMİ', 'gezinomi'), (9, 'E TATİL', 'e-tatil'); In my web site i need this from mysql result hotel_name--->5 price from price table hotel_name--->5 price from price table 5 hotel and 5 different price from price table. Website Design http://img850.imageshack.us/img850/3172/6vu6.png A: CREATE VIEW `view_hotel_and_price_table_together` AS select `hotel`.`hotel_id` AS `hotel_id`, `hotel`.`hotel_name` AS `hotel_name`, `hotel`.`hotel_image` AS `hotel_image`, `price`.`price_id` AS `price_id`, `price`.`price` AS `price`, `price`.`start_date` AS `start_date`, `price`.`end_date` AS `end_date` from (`hotel_table` `hotel` left join `price_table` `price` ON (`hotel`.`hotel_id` = `price`.`p_hotel_id`)); That's your view. Than if you want 5 record to be shown you can use something like SELECT `hotel_name`, `price` FROM `view_hotel_and_price_table_together` ORDER BY RAND() LIMIT 5
{ "pile_set_name": "StackExchange" }
Q: How do I work with Multiple Recordsets in C++ ODBC I am trying to streamline a complex process of storing information in multiple tables and them linking them to a central table. The linking occurs using IDENTITY values generated in each table to provide the unique linking. I know I can use a combination of SET NOCOUNT ON and SELECT @@identity to get each identity, but that still requires me to call a separate SQLExecute() for each table. I have read dozens of articles saying ADO can handle multiple recordsets using an ODBC driver, so the question is how do I do it without ADO? I have already encapsulated all of the standard ODBC stuff for similar behavior to ADO. I basically just need to know what ODBC API calls will allow me to recreate ADO's NextRecorset(). I am working on a combination of MS SQL 7 and MS SQL 2005, using either the SQL Server ODBC, or SQL Native Client Drivers as appropriate. End Goal: SET NOCOUNT ON; INSERT INTO TableA (data) VALUES ('a'); SELECT @@identity AS NewID; INSERT INTO TableB (data) VALUES ('b'); SELECT @@identity AS NewID; INSERT INTO TableC (data) VALUES ('c'); SELECT @@identity AS NewID; ... RS = DB.OpenRecordset() RS.MoveFirst() A_ID = RS.GetValue("id") RS.NextRecordset() RS.MoveFirst() B_ID = RS.GetValue("id") RS.NextRecordset() RS.MoveFirst() C_ID = RS.GetValue("id") A: Use the SQLMoreResults() call as the analog to the NextRecordSet() function. However you probably don't need that if you are willing to make your executes consist of INSERT ...; SELECT @@IDENTITY Since the only result returned from this statement is the identity, you don't need to bother with the SQLMoreResults().
{ "pile_set_name": "StackExchange" }
Q: Capitalizing a lower case screen name at the beginning of a sentence When starting a sentence with a lower case pseudonym, such as a screen name of a user account on a website, should it be capitalized? Or are there different cases where it would and would not be appropriate to do so? My curiosity was sparked by this meta EL&U page where a user comments that he does not mind if his name is lower-cased or not. Are there any established standards on this practice? A: When writing professionally, the first letter in the sentence is capitalized, sole exceptions being when the capitalization could result in a misunderstanding. In such cases, the word is usually typeset differently. However, when writing in an informal context, you might want to take into consideration the preference of the user. For example, Randall Munroe prefers his username xkcd to remain lowercase; however, as you've linked, some users like nohat do not mind it being capitalized. If you are unsure, I would suggest capitalizing it and adhering to professional writing style.
{ "pile_set_name": "StackExchange" }
Q: Laravel - Disable Updated At when updating Get a problem with update using query builder on laravel 5. I've tried to disabled the updated_at but keep failing. Here is my code: $query = StockLog::where('stock_id', $id)->whereBetween('created_at', $from, $to])->update(['batch_id' => $max + 1]); I've tried 2 ways: first one at my model i set: public function setUpdatedAtAttribute($value) { /*do nothing*/ } Second one: $stocklog = new StockLog; $stocklog->timestamps = false; $query = $stocklog::where('stock_id', $id)->whereBetween('created_at', [$from, $to])->update([ 'batch_id' => $max + 1]); both of them are failed. is there anyway to disabled the updated_at? Thanks in advance A: By default, Eloquent will maintain the created_at and updated_at columns on your database table automatically. Simply add these timestamp columns to your table and Eloquent will take care of the rest. I don't really suggest removing them. But if you want use the following way. add the following to your model: public $timestamps = false; This will disable the timestamps. EDIT: it looks like you want to keep the created_at field, you can override the getUpdatedAtColumn in your model. Use the following code: public function getUpdatedAtColumn() { return null; } A: In your model, add this method: /** * @param mixed $value * @return $this */ public function setUpdatedAt($value) { return $this; } UPDATE: In Laravel 5.5: Just try to use this in your model: const CREATED_AT = null; const UPDATED_AT = null; A: The accepted answer didn't work for me, but led me in the right direction to this solution that did: class Whatever extends Model { //... const UPDATED_AT=NULL; //... Laravel 5.3
{ "pile_set_name": "StackExchange" }
Q: Call C standard library function from asm in Visual Studio I have a problem with calling C function from asm project created in visual studio (Win10 x64, Visual Studio 2015). Project consist of one asm file: .586 .model flat, stdcall option casemap:none includelib msvcrt.lib ExitProcess PROTO return:DWORD extern printf:near .data text BYTE "Text", 0 .code main PROC push offset text call printf add esp,4 invoke ExitProcess,0 main ENDP end main When I build project, linker outputs the error: Error LNK2019 unresolved external symbol _printf referenced in function _main@0 Linker output parameters: /OUT:"C:\Users\apple\Documents\SP_Lab7\Debug\SP_Lab7_Demo.exe" /MANIFEST:NO /NXCOMPAT /PDB:"C:\Users\apple\Documents\SP_Lab7\Debug\SP_Lab7_Demo.pdb" /DYNAMICBASE "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib" "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib" "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib" /MACHINE:X86 /SAFESEH:NO /INCREMENTAL:NO /PGD:"C:\Users\apple\Documents\SP_Lab7\Debug\SP_Lab7_Demo.pgd" /SUBSYSTEM:WINDOWS /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /ManifestFile:"Debug\SP_Lab7_Demo.exe.intermediate.manifest" /ERRORREPORT:PROMPT /NOLOGO /TLBID:1 If I comment call print, then everything executes normally (even Windows API function). Is there any way to call C function from asm file without creating cpp file that includes <cstdio>? Is it possible to do? A: Microsoft refactored much of the C runtime and libraries in VS 2015. Some functions are no longer exported from the C library (some are defined in a C header file). Microsoft has some compatibility libraries like legacy_stdio_definitions.lib and legacy_stdio_wide_specifiers.lib, but you can also choose to use the older Visual Studio 2013 platform toolset with the older C libraries. To change the platform toolset: pull down the Project menu; select Properties...; go to Configuration Properties/General, and change Platform Toolset to Visual Studio 2013 (v120) A: It appears that it' possible to use the Visual Studio 2015 Toolset with a few modifications. You'll need to add these libraries to your dependencies: libcmt.lib, libvcruntime.lib, libucrt.lib, legacy_stdio_definitions.lib. Alternatively you could use includelib to include these libraries in your assembly file. Specify C calling convention for your main procedure using PROC C At the end of your file (and this is important) do not use end main, use end only. Not fixing this may cause unexpected crashes. Although we can use ExitProcess to exit our application, we can also put the return code in EAX and do a ret to return. The C runtime calls our main function, and will call the shutdown code for us upon returning. The code could look like: .586 .model flat, stdcall option casemap:none includelib libcmt.lib includelib libvcruntime.lib includelib libucrt.lib includelib legacy_stdio_definitions.lib ExitProcess PROTO return:DWORD extern printf:NEAR .data text BYTE "Text", 0 .code main PROC C ; Specify "C" calling convention push offset text call printf add esp, 4 ; invoke ExitProcess,0 ; Since the C library called main (this function) ; we can set eax to 0 and use ret`to have ; the C runtime close down and return our error ; code instead of invoking ExitProcess mov eax, 0 ret main ENDP end ; Use `end` on a line by itself ; We don't want to use `end main` as that would ; make this function our program entry point ; effectively skipping by the C runtime initialization
{ "pile_set_name": "StackExchange" }
Q: How to check that all files in a file system are can be read without errors? I'm using an external hard drive with an ext4 file system to make backups. The backup software I use (faubackup) copies the file hierarchy 1:1 into a timestamp-named folder on the hard drive, and makes incremental backups in such a way that it hardlinks new copies of files whose contents have not changed to the same file in the corresponding subfolder of the previous backup. Since I recently had a backup drive die on me, I now want to make sure that all the files written can actually be read without I/O error, so I know I can rely on my backup. One way to do so would be to read the whole partition, e.g. by dd'ing it to /dev/null. However, the disk is 3TB large, and doing so would take about 7 hours (via USB 3.0). Another way would be to use e2fsck with the -c option, but this also takes ages. I'm thinking it should be possible to speed the process up by not checking the whole disk, but only the files, which is only a fraction of the whole disk size. This could be done e.g. by writing all files to a tar archive which is not written to disk, but sent to /dev/null. Here the problem is the hard linking: If I have say 10 incremental backups, the storage for that is again just a fraction of the disk, but it appears to be about 10 times larger than that. My question: Is there a way to read only the files on the disk, and only one in each set of files hard linking to the same storage space? Or is there a way to make e2fsck -c or something similar only check the used parts of the file system (allocated blocks)? A: GNU tar does not copy the content of hard linked files multiple times. Read the first answer to this question or the official documentation on this topic. You can test this by piping the output (the archive) of tar through wc: tar cf - -C <mountpoint of your disk> . | wc -c and verify the archive size in bytes (you can compare this to the result with the tar option --hard-dereference).
{ "pile_set_name": "StackExchange" }
Q: create JSON with php Sorry if this seems obvious but all the searches I am doing for this are returning complex answers and I have been struggling with this all day... I have been trying to create json data in PHP and really I want to send variables into the json data. I have not been able to do that so I followed a tutorial online and copied the code exactly yet i'm still not getting an output in my local host.. Please can somebody put me out of my misery... <?php $jsonData = new stdClass(); $people = array( array( 'name' => 'Luci', 'age' => 25, 'sex' => 'female' ), array( 'name' => 'John', 'age' => 27, 'sex' => 'male') ), array( 'name' => 'Peter', 'age' => 22,) 'sex' => 'male' ) ); $jsonData->source = "Program Knowledge"; $jsonData->published = date('Y-m-d H:s:i;'); $jsonData->status = true; $jsonData->people = $people; echo json_encode($jsonData); ?> eventually I was going to try $var = 123456; $jsonData->codeid = $var but I need to figure out just how to get it so work with data I have typed in. Many thanks..!! A: 'sex' => 'male') 'age' => 22,) Need to remove the parenthesis from these two lines, they're parsing errors
{ "pile_set_name": "StackExchange" }
Q: Return a list without using NHibernate object Suppose I have an interface. public interface IBlogRepository { IList<Blog> Blogs(int pageNo, int pageSize); int TotalPosts(); } Now I created a class to implement it and use NHibernate. using NHibernate; using NHibernate.Criterion; using NHibernate.Linq; using NHibernate.Transform; using System.Collections.Generic; using System.Linq; namespace JustBlog.Core { public class BlogRepository: IBlogRepository { // NHibernate object private readonly ISession _session; public BlogRepository(ISession session) { _session = session; } public IList<Post> Posts(int pageNo, int pageSize) { var query = _session.Query<Post>() .Where(p => p.Published) .OrderByDescending(p => p.PostedOn) .Skip(pageNo * pageSize) .Take(pageSize) .Fetch(p => p.Category); query.FetchMany(p => p.Tags).ToFuture(); return query.ToFuture().ToList(); } public int TotalPosts() { return _session.Query<Post>().Where(p => p.Published).Count(); } } The above code is from somewhere on the web for creating a blog engine. However I don't know NHibernate at all, I use Entity Framework to do my job. How can I rewrite the code without using NHiberate? A: Entity Models Assuming we have our entity models like this: public class Post { public Post() { Tags = new List<Tag>(); } public int Id{ get; set; } public string Title{ get; set; } public string ShortDescription{ get; set; } public string Description{ get; set; } public string Meta{ get; set; } public string UrlSlug{ get; set; } public bool Published{ get; set; } public DateTime PostedOn{ get; set; } public DateTime? Modified{ get; set; } public int CategoryId { get; set; } public virtual Category Category{ get; set; } public virtual IList<Tag> Tags{ get; set; } } public class Tag { public int Id { get; set; } public string Name { get; set; } public string UrlSlug { get; set; } public string Description { get; set; } public virtual IList<Post> Posts { get; set; } } public class Category { public int Id { get; set; } public string Name { get; set; } public string UrlSlug { get; set; } public string Description { get; set; } public virtual IList<Post> Posts { get; set; } } Context Our context class is pretty simple. The constructor takes in the name of the connection string in web.config and we define three DbSets: public class BlogContext : DbContext { public BlogContext() : base("BlogContextConnectionStringName") { } public DbSet<Category> Categories { get; set; } public DbSet<Post> Posts { get; set; } public DbSet<Tag> Tags { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); } } Repository The interface for our blog repository is nice and easy and doesn't change much: public interface IBlogRepository { IEnumerable<Post> Posts(int pageNo, int pageSize); int TotalPosts(); } And it's the blog repository itself where things get interesting! public class BlogRepository : IBlogRepository { // NHibernate object replace with our context private readonly BlogContext _blogContext; public BlogRepository(BlogContext blogContext) { _blogContext = blogContext; } //Function to get a list of blogs public IEnumerable<Post> Posts(int pageNo, int pageSize) { //We start with the blogs db set: var query = _blogContext.Posts //Filter by Published=true .Where(p => p.Published) //Order by date they were posted .OrderByDescending(p => p.PostedOn) //Jump through the list .Skip(pageNo * pageSize) //Get the required number of blogs .Take(pageSize) //Make sure the query include all the categories .Include(b => b.Category); //Just return what we have! return query; } //Much simpler function, should be pretty self explanatory public int TotalPosts() { return _blogContext.Posts.Where(p => p.Published).Count(); } } Next Steps OK, so now we have all that set up, and a nice connection string is set up in your web.config, what do we do with it? Well let's get some blogs! var context = new BlogContext(); var repository = new BlogRepository(context); var posts = repository.Posts(0, 10); Then we can do some stuff with those blogs: foreach(var blog in blogs) { Console.WriteLine("Blog Id {0} was posted on {1} and has {2} categories", blog.Id, blog.PostedOn, blog.Categories.Count()); } Notes I didn't implement the FetchMany/ToFuture parts as they're not needed here.
{ "pile_set_name": "StackExchange" }
Q: How can I correctly output an array of objects in the reverse order from mongodb? Comments are saved in an array of objects. How can I correctly output them in reverse order (comments from newest to oldest)? My db: {"_id":{"$oid":"5e3032f14b82d14604e7cfb7"}, "videoId":"zX6bZbsZ5sU", "message":[ {"_id":{"$oid":"5e3032f14b82d14604e7cfb8"}, "user":{"$oid":"5e2571ba388ea01bcc26bc96"},"text":"1" }, {"_id":{"$oid":"5e3032f14b82d14604e7cfb9"}, "user":{"$oid":"5e2571ba388ea01bcc26bc96"},"text":"2" }, .... ] My sheme Mongoose: const schema = new Schema({ videoId: { type: String, isRequired: true }, message: [ { user: { type: Schema.Types.ObjectId, ref: 'User' }, text: { type: String } }, ] }); My code: const userComments = await Comment.find( { videoId: req.query.videoId }, { message: { $slice: [skip * SIZE_COMMENT, SIZE_COMMENT] } } ) .sort({ message: -1 }) .populate('message.user', ['avatar', 'firstName']); but sort not working; thanks in advance! A: You can simply use $reverseArray to reverse content of an array. db.collection.aggregate([ { $addFields: { message: { $reverseArray: "$message" } } } ]) Collection Data : /* 1 */ { "_id" : ObjectId("5e3032f14b82d14604e7cfb7"), "videoId" : "zX6bZbsZ5sU", "message" : [ { "_id" : ObjectId("5e3032f14b82d14604e7cfb8"), "user" : ObjectId("5e2571ba388ea01bcc26bc96"), "text" : "1" }, { "_id" : ObjectId("5e3032f14b82d14604e7cfb9"), "user" : ObjectId("5e2571ba388ea01bcc26bc96"), "text" : "2" } ] } /* 2 */ { "_id" : ObjectId("5e309318d02e05b694b0b25f"), "videoId" : "zX6bZbsZ5sUNEWWWW", "message" : [ { "_id" : ObjectId("5e3032f14b82d14604e7cfc9"), "user" : ObjectId("5e2571ba388ea01bcc26bc87"), "text" : "Old" }, { "_id" : ObjectId("5e3032f14b82d14604e7cfd0"), "user" : ObjectId("5e2571ba388ea01bcc26bc87"), "text" : "New" } ] } Result : /* 1 */ { "_id" : ObjectId("5e3032f14b82d14604e7cfb7"), "videoId" : "zX6bZbsZ5sU", "message" : [ { "_id" : ObjectId("5e3032f14b82d14604e7cfb9"), "user" : ObjectId("5e2571ba388ea01bcc26bc96"), "text" : "2" }, { "_id" : ObjectId("5e3032f14b82d14604e7cfb8"), "user" : ObjectId("5e2571ba388ea01bcc26bc96"), "text" : "1" } ] } /* 2 */ { "_id" : ObjectId("5e309318d02e05b694b0b25f"), "videoId" : "zX6bZbsZ5sUNEWWWW", "message" : [ { "_id" : ObjectId("5e3032f14b82d14604e7cfd0"), "user" : ObjectId("5e2571ba388ea01bcc26bc87"), "text" : "New" }, { "_id" : ObjectId("5e3032f14b82d14604e7cfc9"), "user" : ObjectId("5e2571ba388ea01bcc26bc87"), "text" : "Old" } ] } Your Query : You can use native MongoDB's $lookup instead of .populate() , So try below : Comments.aggregate([ { $addFields: { message: { $reverseArray: "$message" } } }, { $lookup: { from: "User", let: { ids: "$message.user" }, pipeline: [ { $match: { $expr: { $in: ["$_id", "$$ids"] } } }, { $project: { avatar: 1, firstName: 1, _id: 0 } } ], as: "userData" } } ])
{ "pile_set_name": "StackExchange" }
Q: How do I find out how many arguments are being passed I am writing some C code on Linux. I want to loop through the *argv[] parameter being passed to main, but I don't know how to stop before getting a seg fault. i = 0; while (i < sizeof(argv)) { printf("%s\n", argv[i]); i ++; } This produces a seg fault because sizeof always returns 8. How do I get the actual number of elements in argv, or apply some kind of test to stop at the end of argv? A: The first argument of main is argc which is the number of arguments passed to your program. This is at least 1, which is the name of the executable. #include <stdio.h> int main(int argc, char *argv[]) { printf("%d\n", argc); return 0; } Invoked as: $ ./a.out 1 $ ./a.out 1 2 3 4 5 $ ./a.out 1 2 3 4 A: The first argument.. argc should already have the CLI argument count.. Any reason why that isn't used? int main(int argc, char** argv) { if(argc > 1) }
{ "pile_set_name": "StackExchange" }
Q: rails select records which have duplicates For my case i want to select all duplicates records from table for example table1 id | name | sub_name 1 | joe | j1 2 | tim | t1 3 | ben | b1 4 | joe | j2 5 | tim | t2 i vant to select [#<table1 id: 1, name: "joe", sub_name: "j1">, #<table1 id: 4, name: "joe", sub_name: "j2">, #<table1 id: 2, name: "tim", sub_name: "t1">, #<table1 id: 5, name: "tim", sub_name: "t2">] and then display joe - j1 - j2 tim - t1 - t2 Can anybody help me to do this using AR or SQL. i tried this query Table1.group(:name).having("count(*) > 1" but the result was [#<table1 id: 1, name: "joe", sub_name: "j1">, #<table1 id: 2, name: "tim", sub_name: "t1">] or result.count returns {["joe]=>2, ["tim"]=>2} A: Well I don't know if this is the most efficient way but you could: names_with_multiple_rows = Table1.group(:name).having("count(*) > 1") res = names_with_multiple_rows.inject({}) do |h, m| h[m.name] = Table1.select(:sub_name).where(name: m.name) h end Now res is a hash where the keys is the name and the values are the sub_names.
{ "pile_set_name": "StackExchange" }
Q: How does one effectively negotiate rent? I'm going to rent an apartment in a major urban area in the next few months. When I drive around the area where I want to rent I see numerous "For Rent" signs. Also when I look online there are numerous listings. Given the abundance of properties for rent... and from a short conversation with a real estate agent... I've come to realize that negotiating the amount of monthly rent is not out of the question (and perhaps common?). How does one effectively negotiate rent? I'm open to a variety of ideas including trading a longer lease length for a smaller monthy rent... or paying multiple months in advance in exchange for a lower monthly rent etc. Cheers! A: One of the best ways to "win" any negotiation is to make an offer in which the other guy "wins" too. Give them something you don't care much about in exchange for something you do care about. (Assuming the "something" is of value to them.) You've already hinted at this strategy in your question: Prepay months in advance. Longer lease. Longer notice time built into lease termination agreement. Do you have a car? Can you give up a parking space? Are you a non-smoker? Can you promise not to smoke in the apartment? (This is an expense for the landlord when you move out.) Do they allow cats and you don't have cats? Can you promise not to keep cats? (Another expense for the landlord.) Probably unlikely to succeed in urban areas where landlords are pros, but in other areas: can you offer to do work for rent reduction? E.g. you are handy and can help with maintenance, or you can mow the lawn, shovel the walk, paint, etc. If they have low occupancy, can you make a deal for referrals? A: I'm open to a variety of ideas including trading a longer lease length for a smaller monthy rent... or paying multiple months in advance in exchange for a lower monthly rent etc. These two ideas that you mention are good. Do your homework first. See a few places. Find out how much they are asking. Make a note of details such as square footage, appliances, amenities, etc. Then play them off each other. Be sure to point out that there are many places available in the area. Be courteous, but firm and be ready to walk away from a place you like if you are not happy with the deal they are willing (or not willing) to give you. A: Another negotiating technique is to ask for extra items to be included at the base rental rate. Examples of "extras" in an apartment rental might include monthly rental of a washer/dryer, monthly fees for fitness center access, or higher rent for a good location apartment (top floor/pool side/etc). Ask to get one or all of those items included in the rental price they offer you. If they say "yes": You win the extra items at no additional cost. If they say "no": Then challenge them that if they take away the washer/dryer you'll need to pay $50 less rent per month to meet your target price for rent.
{ "pile_set_name": "StackExchange" }
Q: Understanding the shape of tensorflow placeholders I am reading this code and I would like to understand about its implementation. One of the first things that I would like to know, is that what is the shape of some tensor objects (placeholders) such as x_init, xs, h_init, y_init, y_sample, etc. I wrote a line of code such as print(xs.shape) but it wont work. How can I understand the shape of these parameters (tensors)? And can I write something like the following in NumPy? The part of code that defines these tensors look like this: x_init = tf.placeholder(tf.float32, shape=(args.init_batch_size,) + obs_shape) xs = [tf.placeholder(tf.float32, shape=(args.batch_size, ) + obs_shape) for i in range(args.nr_gpu)] # if the model is class-conditional we'll set up label placeholders + # one-hot encodings 'h' to condition on if args.class_conditional: num_labels = train_data.get_num_labels() y_init = tf.placeholder(tf.int32, shape=(args.init_batch_size,)) h_init = tf.one_hot(y_init, num_labels) y_sample = np.split( np.mod(np.arange(args.batch_size * args.nr_gpu), num_labels), args.nr_gpu) h_sample = [tf.one_hot(tf.Variable( y_sample[i], trainable=False), num_labels) for i in range(args.nr_gpu)] A: The shape is assembled from different command line parameters: obs_shape is the shape of the input images, e.g., (32, 32, 3) args.init_batch_size and args.batch_size are the values from command line. It could be for example 30 and 40. Then shape of x_init is the concatenation of init_batch_size and obs_shape: (30, 32, 32, 3). Correspondingly, the shape of each item in xs is (40, 32, 32, 3). You couldn't evaluate xs.shape, because xs is a list of placeholders. You can evaluate xs[0].shape instead. y_sample and h_sample are the lists of tensors as well. The first one contains (batch_size, num_labels) tensors, the second one (num_labels, ).
{ "pile_set_name": "StackExchange" }
Q: A Borel subset of a topological space Is every Borel subset of a topological space $(X, \tau)$ either open or closed? I'm thinking that if $B \in \mathcal B(X)$, then there are many possibilities: $B$ is open for $\tau$, or it is the complement of some open set $B$ in $\tau$, and so closed, or $B = \bigcup_{n=1}^{\infty} B_n$ where each $B_n$ is open, and so open, or Some trivial case in which $B$ is obviously open/closed, or $B = \bigcap_{n=1}^{\infty} B_n$ where these are a mix of closed and open sets. Even if, ideally, all of the $B_n$'s were open, this does not necessarily give an open set, because only finite intersections yield open sets. Thus, my conclusion is no. But could you construct some counter example for this? Thank you. I encountered this confusion when trying to prove that every continuous function is Borel-measurable. I wanted to separate the proof into two cases (open, closed), but then I realized this. A: (1) You are right in believing that the answer is no. For example, in $\mathbf R$, we have the Borel set $$ B = (0,1] = \bigcap_n \left(0,\frac{n+1}n\right) $$ which is neither open nor closed. (2) The possibilities that you list, are not all. When we denote set of the open sets by $B_0(\def\R{\mathbf R}\R)$ and define inductively $$ B_n(\R) = \left\{\bigcap_k A_k\mid A_k \in B_{n-1}(\R) \text{ or } \R\setminus A_k \in B_{n-1}(\R) \right\} $$ then $B_{n-1}(\R) \subsetneq B_n(\R)$ for each $n$, and $\bigcup_n B_n(\R) \ne \textsf{Bor}(\R)$ (you have to continue the induction until $\omega_1$).
{ "pile_set_name": "StackExchange" }
Q: Control order of script executions in test_package Is it possible to control the order in which test_package executes testing scripts? I would like to start by executing some code that creates some objects shared by all individual tests. Therefore, this script needs to be executed first, before the actual test-blabla.R scripts. I could try something like test-AAA.R or test-000.R, but I am not sure if the dir function used by testthat to list the scripts in a package, returns the same (alphabetical?) order of files on all platforms. A: ?test_dir says Test files start with ‘test’ and are executed in alphabetical order (but they shouldn't have dependencies). Helper files start with ‘helper’ and loaded before any tests are run. So, use helper files. i.e. create a file with a name that begins with "helper" and put in it the code that you need to run before running all the tests.
{ "pile_set_name": "StackExchange" }
Q: Why does the universal cover of $GL^+_n$ not admit finite-dimensional representations? Let $GL^+_n \subset \mathbb{R}^{n \times n}$ be the subgroup of real matrices with positive determinant and $\widetilde{GL}^+_n$ be its universal cover. Why does $\widetilde{GL}^+_n$ not admit finite-dimensional representations? I would be happy with a proof or a reference. This question is relevant in spin geometry. Normally, one uses $Spin_n$, which is the universal cover of $SO_n$ (if $n \geq 3$), and a finite-dimensional representation $\rho:Spin_n \to GL(V)$ to construct the spinor bundle of a Riemannian spin manifold $(M,g)$ with spin structure $\Theta^g: Spin^g M \to SO^g M$ via $\Sigma^g M := Spin^g \times _{\rho} V$. In texts like [1], the authors work with a topological spin structure $\widetilde{GL}^+ M \to GL^+ M$ up to the point where one has to construct the spinor bundle. I like this approach, which is why I would like to better understand why this part of the construction fails. Unfortunately, I do not know much about representation theory besides what is mentioned in [1]. [1] Bär, Gauduchon, Moroianu: Generlized cylinders in Semi-Riemannian and Spin Geometry EDIT: One should require the representations to be faithful. A: By [1, Lem. II.5.23], any finite-dimensional representation $\tilde \rho: \widetilde{GL}_n^+ \to GL(V)$, $n>2$, factors through $GL^+_n$, i.e. there exists $\rho:GL^+_n \to Aut(V)$ such that $\rho \circ \vartheta = \tilde \rho$, where $\vartheta:\widetilde{GL}^+_n \to GL^+_n$ is the two-fold cover. Consequently, $\ker \tilde \rho \supset \ker \vartheta \cong Z_2 $ and $\tilde \rho$ cannot be faithful. [1] Lawson/Michelsohn: Spin Geometry
{ "pile_set_name": "StackExchange" }
Q: Average slope of a curve (right side of the equation) intuition Okay, I can somehow understand why average slope of a curve is defined in such a fashion: Let $f$ be a continuous function on an interval $[a,b]$. Then, we define its average over $[a,b]$ to be the number $$ f_{\operatorname{avg}} := {1 \over b-a} \int_a^b f(t) dt $$ Let $y = F(x)$ be a curve. Fix the starting point $x_0$ and the ending point $x_1=x_0+\Delta x$. Then, the slope at a point $z$ is the derivative $F'(z)$. Thus, the "average slope'' should mean \begin{equation*} (F')_{\operatorname{avg}} = {1 \over x_1 - x_0}\int_{x_0}^{x_1} F'(t) dt = {F(x_1) - F(x_0) \over x_1-x_0}. \end{equation*} To summarize: "Avg. slope = Sum all slopes of all tangent lines over an interval $[a,b]$ and divide it by the number of slopes over that same interval." But right side of the equation somehow bothers me. I don't get intuitevely how average slope (sum of all slopes/number of slopes) equals slope of a function $F(x)$ between two endpoints $x_0$ and $x_1$. A: The right side is the slope of the line drawn between $(x_0,F(x_0))$ and $(x_1,F(x_1))$. I would see that as the definition of average slope. Averaging an infinite number of local slopes is more problematic. The right side only depends on two values of the function.
{ "pile_set_name": "StackExchange" }
Q: Change on column based on any previous values in another column I have a dataframe like so: foo <- c(rep(FALSE, 5), TRUE, rep(FALSE, 4)) rank_order <- seq(11,20) df <- data.frame(rank_order = as.numeric(rank_order), foo = foo) What I'd like to do is add one to every value of rank_order following a row where df$foo == TRUE. That means rank_order should look like this: rank_order_target <- c(11, 12, 13, 14, 15, 17, 18, 19, 20, 21) It's easy enough to change one value of rank_order, with lag looking at one previous value of foo (like below), but how do I look at all previous values of foo? df %>% mutate(rank_order_new = case_when(lag(foo, default = FALSE) == TRUE ~ rank_order + 1, TRUE ~ rank_order)) rank_order foo rank_order_new 1 11 FALSE 11 2 12 FALSE 12 3 13 FALSE 13 4 14 FALSE 14 5 15 FALSE 15 6 16 TRUE 16 7 17 FALSE 18 8 18 FALSE 18 9 19 FALSE 19 10 20 FALSE 20 Either a base solution, or something tidyverse would be helpful. A: We can use cumsum library(dplyr) df %>% mutate(new = rank_order + cumsum(foo))
{ "pile_set_name": "StackExchange" }
Q: How to divide paper up into smaller pages in ConTeXt? I need to create some cards, of various sizes, cut from larger letter (8.5" x 11") pages. These are for putting in different sized pocket charts for displaying information in a classroom. All are fairly simple, with header (just like on regular pages) plus some large, vertically and horizontally centered text. Here are some sample layouts: These cards measure 8.5" x 5: _____________________ | Header | | | <--page 1 | Centered text | | | |---------------------| | Header | | | <--page 2, but would be printed on same paper | Centered text | | | |_____________________| These cards measure 11"x4" in landscape mode and the bottom 0.5" is discarded: __________________________ | Header | | Centered text | |--------------------------| | Header | | Centered text | |--------------------------| |__________________________| Is there a way to have ConTeXt setup the pages this way? A simple \pagebreak command would send documents to the next "page" while still being on the same physical page when printed, and headers appear on top like normal. Cuttings lines aren't needed, as I can measure on a paper cutter to get the cuts right. A: You could use ConTeXt's imposition mechanism. The examples have to be typeset using context --arrange. \setuparranging[2TOP] \definepapersize [card] [height=5in,width=8.5in] \setuppapersize [card] [letter] \definemakeup [custom] [align=middle,headerstate=start] \setupheadertexts[Header][] \showframe \starttext \startmakeup[custom] Centered text \stopmakeup \startmakeup[custom] Centered text \stopmakeup \stoptext For the second layout just replace in the above \definepapersize [card] [height=4in,width=11in] \setuppapersize [card] [letter,landscape]
{ "pile_set_name": "StackExchange" }
Q: Decomposition of $sl_2(\mathbb{C})$ Let $L = sl_2(\mathbb{C})$. We call $L = H_0 \oplus H_1 \oplus H_2$ an $orthogonal \ decomposition$ if all components $H_i$ of decomposition are Cartan subalgebras and pairwise orthogonal with respect to the Killing form. Now, suppose that $H_0$ is a Cartan subalgebra consisting of the diagonal matrices and $H_1$ is another Cartan subalgebra orthogonal to $H_0$ via the Killing Form. One can check easily that $H_1$ has a basis of the form: $H_1 = \Big < \begin{pmatrix} 0 & 1 \\ a & 0 \end{pmatrix} \Big >_\mathbb{C}$ for some $a \neq 0$. Thus, $L = H_0 \oplus \Big < \begin{pmatrix} 0 & 1 \\ a & 0 \end{pmatrix} \Big >_\mathbb{C}\oplus \Big < \begin{pmatrix} 0 & 1 \\ b & 0 \end{pmatrix} \Big >_\mathbb{C}$ for some $a, b \neq 0$. Can we prove that either $a$ or $b$ (from above) must be $1$ in order to have the orthogonal decomposition? Or they don't have to be. If the answer is negative, can we still show that for each $a \neq 0$, there exists an automorphism $\phi \in Aut(L)$ such that $\phi(H_0) = H_0$ and $\phi(\begin{pmatrix} 0 & 1 \\ a & 0 \end{pmatrix}) = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}$? Note that the Killing form can be given by $K(A, B) = 4Tr(AB)$ for all $A, B \in sl_2(\mathbb{C})$. A: The orthogonal complement of $H_0$ in $\mathfrak sl_2$ with respect to the killing form is $$\{\begin{pmatrix} 0 & a \\ b & 0 \end{pmatrix} : a, b \in \mathbb{C} \}$$ and as you mentioned if you want to decompose the two dimensional space $H_0^{\perp}$ into a direct sum of Cartan subalgebras $H_1 \oplus H_2$, then you're forced to have $H_1 = \langle \begin{pmatrix} 0 & 1 \\ a & 0 \end{pmatrix} \rangle, H_2 = \langle \begin{pmatrix} 0 & 1 \\ b & 0 \end{pmatrix} \rangle$ for distinct, nonzero $a, b$. If you want $H_1, H_2$ to be orthogonal, then you just need the trace $\begin{pmatrix} 0 & 1 \\ a & 0 \end{pmatrix} \begin{pmatrix} 0 & 1 \\ b & 0 \end{pmatrix} = \begin{pmatrix}b & 0 \\ 0 & a \end{pmatrix}$ to be zero. So neither $a$ nor $b$ has to be one; you just need $a = -b$. For your question about the automorphism, I think the answer is no. I believe every Lie algebra automorphism of $\mathfrak{sl}_2$ is the differential of an automorphism of algebraic groups of $\textrm{SL}_2$. Every automorphism $\phi$ of $\textrm{SL}_2$ is know to be inner, say $x \mapsto gxg^{-1}$ for some $g \in \textrm{SL}_2$. The differential $d\phi$ of such an automorphism is given by the same formula: $X \mapsto gXg^{-1}$. In order for $d\phi$ to fix $H_0$, $\phi$ has to fix the standard torus in $\textrm{SL}_2$, which means $g$ needs to be in that torus: so $g = \begin{pmatrix} c \\ & \frac{1}{c} \end{pmatrix}$. From here you can see that what you want is impossible.
{ "pile_set_name": "StackExchange" }
Q: How to send message to JMS server from one machine and receive that from another machine in JBoss 7 I am trying to send message(TextMessage) to JMS server from my laptop, then I am trying to receive that message from another laptop. I am using JBoss AS 7.1. My both laptops are connected in same network. When I am doing that I am getting exception. I searched for this in google and some is saying that in JBoss 7.1 JNDI will not get connections from remote IP's and they are saying that we have to use HornetQ. Can any one please help in this issue. A: Looks like you have two queues, one on each machine. They only have the same name, but are not connected in any way. You could make the sender machine use the remote queue directly, but it's advisable to use (like you have) two queues instead, one on each node, and then configure a bridge to move the messages from one to the other. In this way, sending as well as receiving messages will work within your local transactions, which is what you'll normally want. In order to configure the bridge, HornetQ offers two options: A generic JMS bridge, and a core bridge. The former is generic, as it can bridge between JMS queues of any JMS provider. But the HornetQ docs recommend core bridges when using HornetQ on both sides, as they are faster and more robust. The JBoss docs (the section "JMS Bridge"), describes the setup for a JMS-Bridge using the CLI. The HornetQ docs for core bridges describes the stand alone setup (outside of the JBoss server); converting that to CLI, you'll get (replace the parts in curly brackets with your values): /subsystem=messaging/hornetq-server=default/bridge={bridge-name}:add(queue-name="{queue-name}", forwarding-address="{remote-hostname}", static-connectors=["http-acceptor"]) To see a brief description of all parameters, use this command: /subsystem=messaging/hornetq-server=default/bridge=x:read-resource-description
{ "pile_set_name": "StackExchange" }
Q: How to showing value on dropdown list form auto select value from database i have a from to edit/ update data . on colomn input like name ,email ,date i dont have a problem because this value can e displayed at this colomn like this : <div class="item form-group"> <label class="control-label col-md-3 col-sm-3 col-xs-12" for="nama">NAMA <span class="required">*</span> </label> <div class="col-md-6 col-sm-6 col-xs-12"> <input id="nama" type="text" class="form-control @error('nama') is-invalid @enderror" name="nama" value="{{$pns->users->nama}}" required autocomplete="nama"> @error('nama') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> this value on this input is value="{{$pns->users->nama}}" and its still working , but how i can do this on this input ? this input is select dropdown list like this : <div class="form-group"> <label class="control-label col-md-3 col-sm-3 col-xs-12">Agama <span class="required">*</span></label> <div class="col-md-6 col-sm-9 col-xs-12"> <select name="agama_id" id="agama_id" class="form-control"> @foreach($agama as $masters => $agamas ) <option value="{{ $masters }}">{{ $agamas }}</option> @endforeach </select> </div> </div> where i can user this value like {{$pns->users->nama}} ??? if i open this update form , its will choose automaticlly like this db ?? someone have solution ? A: Try this. <select name="agama_id" id="agama_id" class="form-control"> @foreach($agama as $masters => $agamas ) <option value="{{ $masters }}" @if ($pns->users->agama_id == $masters ) selected @endif>{{ $agamas }}</option> @endforeach </select>
{ "pile_set_name": "StackExchange" }
Q: hard code custom field for custom post type in wordpress I have created a custom post type in wordpress called videos. When the admin adds a video he also needs to provide a youtube-id. This can be done by selecting the appropriate custom field from the drop-down list and then entering the ID. I was wondering though, isn't there a way to always display that custom field when you are adding or editing a video? (And optionally, could you even make it a required field?) A: I'll just answer my own question after 8 years :) For people who live on another planet: just use the ACF plugin
{ "pile_set_name": "StackExchange" }
Q: Handling Roo generated AspectJ files in Eclipse I have generated a sample roo project using command prompt and then imported it to the eclipse.But i found that most of the important files are in aj extension.How can i change these files into java files.I want to do this in eclipse. A: If you want the .aj files to show up in the Project Explorer: Click on the down arrow on the top right corner of the Project Explorer panel. Choose Customize View... In the Filters tab, uncheck Hide generated Spring Roo ITDs (I found this question searching for how to do this, so I wrote it here) A: First of all, you do not have to convert the .aj files to java. They are Roo generated aspects which does the magic behind Roo. You should not modify or delete Roo generated .aj files. If you want to override the behavior of them, you should "Push In" refactor the methods to the necessary java files or you can simply create methods with the same method signature in the related java file. Roo will automatically modify the .aj file and remove the overridden method from the .aj file. Remember, you need to have the Roo shell running in order for this to happen or it would happen the next time you start the Roo shell. To use the "Push In" refactoring feature, you can use AJDT for eclipse, which is often the preferred plugin for AspectJ related development in Eclipse. Cheers. A: .aj files are not Java files. They are AspectJ files. These can be removed and everyhting can be moved into Java files but you won't be able to continue using Roo to handle the project changes. There are plugins for Eclipse to handle those files from the IDE. I've mostly used the SpringSource Tool Suite which is a packaged version of Eclipse that has (among other things) the proper tools to work with Roo.
{ "pile_set_name": "StackExchange" }
Q: Error: expected specifier-qualifier-list before ‘TR’ I have a problem defining my structure inside the union on Bison I made a structure typedef enum {Binary_Op,Uni_Op,Variable, Const} Tag_Type; typedef struct tree { Tag_Type Tag; union { struct { char op; struct tree *left, *right; }bin_op; struct { char op; struct tree *arg; /* negative or positive */ }uni_op; char var; int const_val; }u; }TREE_REC, *TR; %} %union { int y_int; TR y_tree; } %type <y_tree> expr term factor assign %token <y_int> CONST %token <y_int> VAR %% but inside the union TR has an error. I don't understand why!! any help? A: You need to define struct tree and TR in a header file that you #include before you #include "y.tab.h". The error message is telling you that you're trying to use TR before the compiler has seen a definition for it. A: I'm a bit confused with your typedef struct tree {...} TREE_REC, *TR. I would have rather written : typedef struct tree {...} TREE_REC; //Alias on struct tree typedef TREE_REC * TR; //Definition of the pointer to a struct tree The , in your typedef is disturbing me. Can you test my solution, or just clarify the syntax of your typedef?
{ "pile_set_name": "StackExchange" }
Q: How to sort a Map[string]int by its values? Given this code block map[string]int {"hello":10, "foo":20, "bar":20} I would like to print out foo, 20 bar, 20 hello, 10 In the order of highest to lowest Thanks! A: Found the answer on Golang-nuts by Andrew Gerrand You can implement the sort interface by writing the len/less/swap functions func rankByWordCount(wordFrequencies map[string]int) PairList{ pl := make(PairList, len(wordFrequencies)) i := 0 for k, v := range wordFrequencies { pl[i] = Pair{k, v} i++ } sort.Sort(sort.Reverse(pl)) return pl } type Pair struct { Key string Value int } type PairList []Pair func (p PairList) Len() int { return len(p) } func (p PairList) Less(i, j int) bool { return p[i].Value < p[j].Value } func (p PairList) Swap(i, j int){ p[i], p[j] = p[j], p[i] } For the original post, please find it here https://groups.google.com/forum/#!topic/golang-nuts/FT7cjmcL7gw A: There's a new sort.Slice function in go 1.8, so now this is simpler. package main import ( "fmt" "sort" ) func main() { m := map[string]int{ "something": 10, "yo": 20, "blah": 20, } type kv struct { Key string Value int } var ss []kv for k, v := range m { ss = append(ss, kv{k, v}) } sort.Slice(ss, func(i, j int) bool { return ss[i].Value > ss[j].Value }) for _, kv := range ss { fmt.Printf("%s, %d\n", kv.Key, kv.Value) } } https://play.golang.org/p/y1_WBENH4N A: For example: package main import ( "fmt" "sort" ) func main() { m := map[string]int{"hello": 10, "foo": 20, "bar": 20} n := map[int][]string{} var a []int for k, v := range m { n[v] = append(n[v], k) } for k := range n { a = append(a, k) } sort.Sort(sort.Reverse(sort.IntSlice(a))) for _, k := range a { for _, s := range n[k] { fmt.Printf("%s, %d\n", s, k) } } } Playground Output: foo, 20 bar, 20 hello, 10
{ "pile_set_name": "StackExchange" }
Q: How to make smooth change of css property while scrolling? I have a task - my navigation block has background property background: rgba(0,0,0, 0); I need to smooth change its opacity from 0 to 1 while scrolling, its no problem, but the end of animation (i mean the moment when opacity of background will reach 1) is bottom border of some block so this is my HTML code <header> <nav>...</nav> </header> header has a flexible height. nav has a height of 100px. So i need my nav`s background opacity to reach 1 when scrollTop value will be: $('header').height() - $(nav).height(); https://jsfiddle.net/zzvns9hy/7/ A: You can do something like HTML <header> <nav></nav> </header> CSS nav { width:100px; height:100px; } SCRIPT $(window).scroll(function() { // what is the position of nav from the top of the document var NavTop = Math.floor( $(document).scrollTop() - $('nav').offset().top ); // From 0 to 1, how much is nav scrolled var NavScroll = NavTop / $('nav').height(); $('nav').css('background-color','rgba(255,0,0,'+NavScroll+')'); }); http://jsfiddle.net/an50e93p/
{ "pile_set_name": "StackExchange" }
Q: Null reference in a foreach over "Table.Rows" In the line foreach (DataRow Row in Table.Rows), I'm getting a NullReferenceException. The program is in an emulator in C#. When I debug it and it crashes, it highlights the word foreach in yellow. I've pasted my whole code below. using System; using System.Collections.Generic; using System.Data; using Reality.Storage; using System.Threading; namespace Reality.Game.Moderation { public static class ModerationBanManager { private static List<uint> mCharacterBlacklist; private static List<string> mRemoteAddressBlacklist; private static Thread mWorkerThread; private static object mSyncRoot; public static void Initialize(SqlDatabaseClient MySqlClient) { mCharacterBlacklist = new List<uint>(); mRemoteAddressBlacklist = new List<string>(); mSyncRoot = new object(); mWorkerThread = new Thread(new ThreadStart(ProcessThread)); mWorkerThread.Name = "ModerationBanManager"; mWorkerThread.Priority = ThreadPriority.Lowest; mWorkerThread.Start(); ReloadCache(MySqlClient); } public static void ProcessThread() { try { while (Program.Alive) { Thread.Sleep(600000); using (SqlDatabaseClient MySqlClient = SqlDatabaseManager.GetClient()) { ReloadCache(MySqlClient); } } } catch (ThreadAbortException) { } catch (ThreadInterruptedException) { } } public static void ReloadCache(SqlDatabaseClient MySqlClient) { lock (mSyncRoot) { mCharacterBlacklist.Clear(); mRemoteAddressBlacklist.Clear(); MySqlClient.SetParameter("timestamp", UnixTimestamp.GetCurrent()); DataTable Table = MySqlClient.ExecuteQueryTable("SELECT * FROM bans WHERE timestamp_expire > @timestamp"); foreach (DataRow Row in Table.Rows) { uint UserId = (uint)Row["user_id"]; string RemoteAddr = (string)Row["remote_address"]; if (UserId > 0 && !mCharacterBlacklist.Contains(UserId)) { mCharacterBlacklist.Add(UserId); } if (RemoteAddr.Length > 0 && !mRemoteAddressBlacklist.Contains(RemoteAddr)) { mRemoteAddressBlacklist.Add(RemoteAddr); } } } } public static bool IsRemoteAddressBlacklisted(string RemoteAddressString) { lock (mSyncRoot) { return mRemoteAddressBlacklist.Contains(RemoteAddressString); } } public static bool IsUserIdBlacklisted(uint UserId) { lock (mSyncRoot) { return mCharacterBlacklist.Contains(UserId); } } public static void BanUser(SqlDatabaseClient MySqlClient, uint UserId, string MessageText, uint ModeratorId) { MySqlClient.SetParameter("userid", UserId); MySqlClient.SetParameter("reason", MessageText); MySqlClient.SetParameter("timestamp", UnixTimestamp.GetCurrent()); MySqlClient.SetParameter("timestampex", UnixTimestamp.GetCurrent()); MySqlClient.SetParameter("moderator", ModeratorId); MySqlClient.ExecuteNonQuery("INSERT INTO bans (user_id,reason_text,timestamp_created,timestamp_expire,moderator_id) VALUES (@userid,@reason,@timestamp,@timestampex,@moderator)"); lock (mSyncRoot) { mCharacterBlacklist.Add(UserId); } } } } A: If it's really being thrown at this line: foreach (DataRow Row in Table.Rows) Then Table or Table.Rows is null. If it is being thrown from inside of your foreach loop: foreach (DataRow Row in Table.Rows) { //aka in here } Then it most likely means that one of your rows is null. To find which one add this at the beginning of your loop and place a break point inside of the if statement. foreach (DataRow Row in Table.Rows) { if(Row == null) { //breakpoint here! } } You can also just examine Table.Rows while debugging, but if there are 1000s of rows this is not a realistic option. A: If you have NullReferenceException in that exact line, this means that either the Table variable or the Rows property is null. There are almost no other options. Please put a breakpoint there and check which one of them is null - and then investigate and correct that.
{ "pile_set_name": "StackExchange" }
Q: SAP UI5 embed manifest.json right I just wrote the description file for my UI5 application. Now I have these questions: Where and how can I embed the manifest.json in my project correctly? How can I test if it's working fine? (correctly embedded) Is the "start_url": "" similar to initialPage of the index.html? Many thanks for your guidance, Chris A: Usually, the manifest.json file (aka. "Application Descriptor") is put into the same folder as where the Component.js file is located. The component will look for the file name "manifest.json" in the same folder. If the descriptor is located somewhere else or has a different file name, assign the relative URL of the file to the manifestUrl in the component factory function like this, which is recommended to do so anyway because it ... loads the descriptor file before creating the component (same as manifestFirst) allowing us to preload dependencies and model data to improve the initial loading time. makes specifying the name of the component redundant. You can either pass the name of the component or the URL of the descriptor file to load [the component] via the descriptor. To see if the file is correctly embedded, run the app and see if e.g. the rootView is loaded, models (for example ResourceModel for i18n) are set to the component instance, custom resources assigned to sap.ui5/resources are loaded, etc. etc.. → Make sure to include (or in case of manifestFirst/ manifestUrl, don't be tempted to remove) manifest declaration in the component metadata. The "start_url" is purely advisory and meant for the web standard rather than for UI5. It's telling the browser where to look for the initial page when the user starts the web app. To learn more about the descriptor file, take a look at the developer guide such as "Descriptor for Applications" or as a summary, here.
{ "pile_set_name": "StackExchange" }
Q: Entity Attempting to update incorrect table / multiple instances of IEntityChangeTracker issue This is probably a stupid question but here I go anyways. Some facts. Im using entity 6.0.0.0 according to my refs. Im hitting an azure sql db. The project is based of a mvc default template thingo. So I'm attempting to add to table via the following code. Please note only 1 path has been attempted each time not all 3 or a combination at once. public User(UserModel userModel) { using (var db = new SqlDogContext()) { // Path 1 this seem like there is a better way but throws an exception anyways var sillyModel = new UserModel() { Id = userModel.Id }; db.UserLibarys.Add(new UserLib {User = sillyModel, Libary = RssLibObject}); db.SaveChanges(); db.UserLibarys.Add(new UserLib {User = sillyModel, Libary = KodiLibObject}); db.SaveChanges(); db.UserLibarys.Add(new UserLib {User = sillyModel, Libary = SoundCloudLibObject }); db.SaveChanges(); db.UserLibarys.Add(new UserLib {User = sillyModel, Libary = SpotifyBridgeObject }); db.SaveChanges(); // Path 2 I guess this would be ok var sillyModel = new UserModel() { Id = userModel.Id }; db.UserLibarys.Add(new UserLib { User = sillyModel, Libary = RssLibObject }); db.UserLibarys.Add(new UserLib { User = sillyModel, Libary = KodiLibObject }); db.UserLibarys.Add(new UserLib { User = sillyModel, Libary = SoundCloudLibObject }); db.UserLibarys.Add(new UserLib { User = sillyModel, Libary = SpotifyBridgeObject }); db.SaveChanges(); // Path 3 - What i want to use.. db.UserLibarys.Add(new UserLib { User = userModel, Libary = RssLibObject }); db.UserLibarys.Add(new UserLib { User = userModel, Libary = KodiLibObject }); db.UserLibarys.Add(new UserLib { User = userModel, Libary = SoundCloudLibObject }); db.UserLibarys.Add(new UserLib { User = userModel, Libary = SpotifyBridgeObject }); db.SaveChanges(); } } And I'm getting the following exception for path 1. {"Violation of PRIMARY KEY constraint 'PK_dbo.UserModels'. Cannot insert duplicate key in object 'dbo.UserModels'. The duplicate key value is (009d1c33-a3cf-49db-8243-ff8a447eff16). \r\nThe statement has been terminated."} And I'm getting the following exception for path 2. An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll but was not handled in user code Using this which I found somewhere on stackoverflow. try { // Your code... // Could also be before try if you know the exception occurs in SaveChanges db.SaveChanges(); } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } I get the following message The User field is required. This makes very little sense to me because as I see it I'm providing it. And I'm getting the following exception for path 3. Additional information: An entity object cannot be referenced by multiple instances of IEntityChangeTracker. This is confusing to me because it looks like its updating the wrong table. Here Are my models public class UserLib { [Key] public int LibId { get; set; } public bool UserEnabled { get; set; } [Required] public virtual Lib Libary { get; set; } [Required] public virtual UserModel User { get; set; } } public class UserModel { [Key, ForeignKey("ApplicationUser")] public string Id { get; set; } public virtual UserLib Libary { get; set; } public virtual ApplicationUser ApplicationUser { get; set; } } public class Lib { public string Name { get; set; } public string Logo { get; set; } [Key] public int LibId { get; set; } public virtual UserLib UserLib { get; set; } } public class ApplicationUser : IdentityUser { public virtual UserModel MyUserModel { get; set; } // plus some other stuff in here that seems non relavent } Here is where the usermodel is created using (var db = new SqlDogContext()) { db.UserModels.Add( new UserModel() { Id = currentId } ); db.SaveChanges(); query = from b in db.UserModels where b.Id == currentId select b; } _CurrentUser = new User(query.First()); The end goal is to have one user for one UserModel One UserModel for Many UserLibaries And For UserLibaries to Have a foreign key to the library data base. So I have probably made a rookie mistake but can anyone see my issue :). A: You are trying to set the primary key: var sillyModel = new UserModel() { Id = userModel.Id }; and then store it multiple times which you can not do. Let entity framework set the primary keys. Also note that you do not have to keep calling SaveChanges() after each operation. You can do all of your inserts and then call it one time.
{ "pile_set_name": "StackExchange" }
Q: Permanent redirect from one domain to another but same host I had domain name which expired today and I have registered new domain with same name but different extension. New domain is in the same host where was old domain... just from http://example.com become http://example.net Now I have added in .htaccess this which I took from another question here on SO but when I go to old domain doesn't redirect me. Is this is because they are on the same hosting account? Options +FollowSymLinks RewriteEngine On RewriteCond %{SCRIPT_FILENAME} !-d RewriteCond %{SCRIPT_FILENAME} !-f RewriteBase / RewriteCond %{HTTP_HOST} !^example\.com$ [NC] RewriteRule ^(.*)$ http://example.net [R=301,L] New domain is working without any problems and is loading correctly if I go directly. A: If you don't own example.com, you have no control over where it is hosted now. Read up on how DNS works https://en.wikipedia.org/wiki/Domain_Name_System
{ "pile_set_name": "StackExchange" }
Q: How to implement drag-drop directive for Ionic? //long-press.directive.d.ts import { ElementRef, EventEmitter, OnDestroy, OnInit, NgZone } from '@angular/core'; import { Gesture } from 'ionic-angular/gestures/gesture'; export declare class LongPressDirective implements OnInit, OnDestroy { zone: NgZone; interval: number; onPressStart: EventEmitter<any>; onPressing: EventEmitter<any>; onPressEnd: EventEmitter<any>; el: HTMLElement; pressGesture: Gesture; int: any; constructor(zone: NgZone, el: ElementRef); ngOnInit(): void; ngOnDestroy(): void; } //long-press.drective.js "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var gesture_1 = require("ionic-angular/gestures/gesture"); var LongPressDirective = (function () { function LongPressDirective(zone, el) { this.zone = zone; this.onPressStart = new core_1.EventEmitter(); this.onPressing = new core_1.EventEmitter(); this.onPressEnd = new core_1.EventEmitter(); this.el = el.nativeElement; } LongPressDirective.prototype.ngOnInit = function () { var _this = this; if (!this.interval) this.interval = 500; if (this.interval < 40) { throw new Error('A limit of 40ms is imposed so you don\'t destroy device performance. If you need less than a 40ms interval, please file an issue explaining your use case.'); } this.pressGesture = new gesture_1.Gesture(this.el); this.pressGesture.listen(); this.pressGesture.on('press', function (e) { _this.onPressStart.emit(e); _this.zone.run(function () { _this.int = setInterval(function () { _this.onPressing.emit(); }, _this.interval); }); }); this.pressGesture.on('pressup', function (e) { _this.zone.run(function () { clearInterval(_this.int); }); _this.onPressEnd.emit(); }); }; LongPressDirective.prototype.ngOnDestroy = function () { var _this = this; this.zone.run(function () { clearInterval(_this.int); }); this.onPressEnd.emit(); this.pressGesture.destroy(); }; return LongPressDirective; }()); LongPressDirective.decorators = [ { type: core_1.Directive, args: [{ selector: '[ion-long-press]' },] }, ]; /** @nocollapse */ LongPressDirective.ctorParameters = function () { return [ { type: core_1.NgZone, }, { type: core_1.ElementRef, }, ]; }; LongPressDirective.propDecorators = { 'interval': [{ type: core_1.Input },], 'onPressStart': [{ type: core_1.Output },], 'onPressing': [{ type: core_1.Output },], 'onPressEnd': [{ type: core_1.Output },], }; exports.LongPressDirective = LongPressDirective; //# sourceMappingURL=long-press.directive.js.map This is implementation of 'press', 'press-up' event. This directive intends to build upon the existing Hammer.JS press event that Ionic uses for long pressing, by giving you interval emission. https://www.npmjs.com/package/ionic-long-press I want to add 'drag'-'drop' event. I am beginner of angular. Expert's help is needed. Thanks. A: I solved the problem using this plugin. https://github.com/AbineshSrishti/ionic2-selection-card-drag
{ "pile_set_name": "StackExchange" }
Q: score increase the chance of apperance Hello I'm developing a game that each time a user blows a block the users get 1 point and the point get added to an overall score while the game is running. the game consists of 4 standard views what i want to be done is that the more the chance increase the more a background appear on the views. in another way the higher the score the more the chance of a background to be bind to the view when the user reach's 50 it starts to bind it with the background and when the user reach's 200 the chance of binding becomes 100% this.Bcolor=random.nextInt(4 - 1 + 1) + 1; // generate a random color between 1 and 3 if(FallAnimationActivity.score % 100 == 0) { // here where i want to apply the chance alogrithm. FallAnimationActivity.showcolorbuttons(); switch (Bcolor) { case 1: this.setBackgroundColor(Color.BLUE); break; case 2: this.setBackgroundColor(Color.RED); break; case 3: this.setBackgroundColor(Color.GREEN); break; case 4: this.setBackgroundColor(Color.BLACK); break; } } else{ this.setBcolor(0); } FallAnimationActivity.score is the user score that keeps increasing while he pops the blocks that appears. Thank you. A: You can use an algorithm that generates a number between 1 and 200. if the number is smaller than the score, return true, otherwise, return false.
{ "pile_set_name": "StackExchange" }
Q: getaddrinfo ENOTFOUND when using tedious in node.js I'm trying to connect to a local SQL Express server using Tedious but keep getting failed Error: getaddrinfo ENOTFOUND Am I using the wrong address here? var Connection = require('tedious').Connection; var config = { userName: 'sa', password: 'mypassword', server: 'LOCALHOST\\SQLEXPRESS', }; var connection = new Connection(config); connection.on('connect', function(err) { // If no error, then good to go... if(err) { console.log(err); return; } executeStatement(); } ); A: "Microsoft style strings of hostname\instancename are not supported." - pekim I posted the same issue on github and here is the full answer: https://github.com/pekim/tedious/issues/118
{ "pile_set_name": "StackExchange" }
Q: How to find a time is one hour before and within my custom time in iOS I need to start download exactly one hour before or within my custom time. For example I should start to download at 7 AM or with 8 AM (8 AM is my custom time). How I can achieve this. the following is my code, AppDelegate * iDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; iDelegate.mStartTime = [[NSUserDefaults standardUserDefaults] objectForKey:START_TIME]; int stHr = [[[iDelegate.mStartTime componentsSeparatedByString:@":"] objectAtIndex:0] intValue]; int stMin = [[[iDelegate.mStartTime componentsSeparatedByString:@":"] objectAtIndex:1] intValue]; int formStTime = (stHr*60)+stMin; NSDate *today = [[[NSDate alloc] init]autorelease]; NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]autorelease]; NSDateComponents *offsetComponents = [[[NSDateComponents alloc] init]autorelease]; [offsetComponents setHour:+1]; NSDate *modifiedDate = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0]; NSDateComponents * timecomponents = [[NSCalendar currentCalendar] components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:modifiedDate]; NSInteger currentHour = [timecomponents hour]; NSInteger currtMin = [timecomponents minute]; int nowTime = (currentHour*60)+currtMin; if (nowTime <= formStTime || nowTime >= formStTime) { // start download } But I should not download if the current time is 8 AM or after 8 AM . What is the mistake in my code ? Please suggest. Thanks. A: I have not considered in detail all your code's logic, but this struck to me: if (nowTime <= formStTime || nowTime >= formStTime) this condition will be always true. This explains why your code is not working as you wish since it should always do the downloading, even after 8AM. You are after a condition link this: if (nowTime >= minimumTime || nowTime < maximumTime) However, I have not clear from your question how you define minimum and maximumTime so cannot advise further. If formStTime is your minimumTime and we assume that maximumTime is just one hour later, you could have: if (nowTime >= formStTime || nowTime < formStTime + 60) (If I read correctly your code.) EDIT: after your clarification in the comments, the condition to start the download would be: if (nowTime < formStTime) //-- start download To handle the second part of your requirements (stopping the download at the given maximum time) you will need a different logic altogether. One way of doing it would be starting a NSTimer when you start a download that will fire at the right time; then, you would check if the download is still going on and stop it. A NSTimer is just one of multiple possibilities you have (you could also use displatch_after), but the basic idea will not change. E.g.: if (nowTime < formStTime) { //--= start download self.timer = [NSTimer scheduledTimerWithTimeInterval:(formStTime - nowTime)*60 //-- seconds target:self selector:@selector(timeExpired:) userInfo:nil repeats:NO]; } then in the handler function: - (void)timeExpired:(NSTimer*)timer { if (downloadStillOngoing) //-- stop the download } When your download is done, you should call [self.timer invalidate], also. However, you will need to fill a number of gaps in my sketch implementation to get to a working solution. If you need more help about stopping the download, you will need to provide more information about how you are doing the download and possibly ask a new question.
{ "pile_set_name": "StackExchange" }
Q: Trying to save vtk files with tvtk made from NumPy arrays I'm trying to use tvtk (the package included with Enthought's Canopy) to turn some arrays into .vtk data that I can toss over to VisIt (mayavi complains on my OS (Mac OS X). I found what looked like the solution here (Exporting a 3D numpy to a VTK file for viewing in Paraview/Mayavi) but I'm not recovering the output that the author of the answer does and was wondering if anyone could tell me what I'm doing wrong. So I enter the commands in the Canopy notebook, import numpy as np from enthought.tvtk.api import tvtk, write_data data = np.random.random((10,10,10)) grid = tvtk.ImageData(spacing=(10, 5, -10), origin=(100, 350, 200), dimensions=data.shape) grid.point_data.scalars = np.ravel([], order='F') grid.point_data.scalars.name = 'Test Data' # Writes legacy ".vtk" format if filename ends with "vtk", otherwise # this will write data using the newer xml-based format. write_data(grid, '/Users/Epictetus/Documents/Dropbox/Work/vtktest.vtk') which does create a vtk file, but unlike the output the author of the previous answer suggests, I just get a blank output, # vtk DataFile Version 3.0 vtk output ASCII DATASET STRUCTURED_POINTS DIMENSIONS 10 10 10 SPACING 10 5 -10 ORIGIN 100 350 200 Is it obvious what I'm doing wrong? File I/O has never been my forte... Cheers! -user2275987 A: Change the line grid.point_data.scalars = np.ravel([], order='F') to grid.point_data.scalars = data.ravel(order='F') Your grid doesn't have any data, and hence nothing is saved to the vtk file! :-)
{ "pile_set_name": "StackExchange" }
Q: What cracked Raphael's shell? In TMNT(2014), there is a point near the climax where Raphael hesitates saving Leonardo because his shell is cracked and tells Donatello to duct tape it. However, it's never shown in the movie when his shell is actually cracked. Even early in the movie, his shell has duct tape on it. So when does Raphael have his shell cracked and what actually cracks it? A: Although Raphael does have duct tape on his shell throughout the movie, the crack that Donatello is referring to was received in the fight with Shredder just moments before. While April and Vern attempted to free the other turtles, Raphael tried to fight Shredder on his own and was less than successful. He ended up face-down on the concrete with Cyber-Shredder forcefully stepping on his back shell. Not only does Raphael nearly scream in pain during the scene, but there are also notable cracking noises heard. In addition, certain versions of the film even note "cracking noises" in the subtitle text. Afterwards, Shredder is seen walking off with Raphael lying on the floor defeated. Here's a clip of the fight. The cracking occurs around the 1:30 mark:
{ "pile_set_name": "StackExchange" }