_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d9401
train
I believe passing such parameter to IFrame should be done on the page on server. Not with javascript. According to full scenario this is what should have worked but it is not. I believe the managedbean scope is lost and that is why the id is not set on different page. To make this work probably the scope of managed bean should be session not request or view because you go to different page. A: So, after some digging into BI Publisher, found out that parameter can just be passed through url and to iframe. In other words, url should look somewhat like this: "content:port?accessmode&credentials&parameterid".
unknown
d9402
train
As Luis pointed out in comment moving => right after (snapshot) will solve the issue. Just to add use some kind of IDE. VSCode is recommended IDE for React development) but you can use any other IDE and setup eslint, prettier and autoformatonsave options so that you don't have to spend too much time in fixing these type of issues. Here is great tutorial to setup VSCode with all extensions.
unknown
d9403
train
The easiest way to do that is by accessing the menu item. Using AXUIElementCopyAttributeValue works best with the provided constants: // get menu bar var menuBarPtr: CFTypeRef? _ = AXUIElementCopyAttributeValue(safariElement, kAXMenuBarRole as CFString, &menuBarPtr) guard let menuBarElement = menuBarPtr as! AXUIElement? else { fatalError() } Accessibility Inspector shows me, what items are child of the menu bar: so lets get the children using kAXChildrenAttribute: // get menu bar items var menuBarItemsPtr: CFTypeRef? _ = AXUIElementCopyAttributeValue(menuBarElement, kAXChildrenAttribute as CFString, &menuBarItemsPtr) guard let menuBarItemsElement = menuBarItemsPtr as AnyObject as! [AXUIElement]? else { fatalError() } And so on all the way down to the menu item. Items also have an unique identifier that can look like _NS:1008. I'm not sure how to access them directly but by using AXUIElementPerformAction I can simply simulate pressing the menu item (action will be kAXPressAction). I can use kAXRoleAttribute to identify the type of the item and where it occurs in the Accessibility hierarchy (see "Role:") As I'm still a beginner at Swift, that was a quite challenging task as this is also not documented very well. Thanks a lot to Dexter who also helped me to understand this topic: kAXErrorAttributeUnsupported when querying Books.app A: In your case you don't need necessarily need to use AXUI accessibility API. It's arguably simpler to send key strokes. You can go back in Safari history to previous page with CMD[. As an added bonus Safari does not need to be in foreground anymore. let pid: pid_t = win.getSafariPid(); let leftBracket: UInt16 = 0x21 let src = CGEventSource(stateID: CGEventSourceStateID.hidSystemState) let keyDownEvent = CGEvent(keyboardEventSource: src, virtualKey: leftBracket, keyDown: true) keyDownEvent?.flags = CGEventFlags.maskCommand let keyUpEvent = CGEvent(keyboardEventSource: src, virtualKey: leftBracket, keyDown: false) keyDownEvent?.postToPid(pid) keyUpEvent?.postToPid(pid) Your app running on Mojave and newer MacOS versions will need the System Preferences -> Security & Privacy -> Accessibility permisions granted to be eligible for sending keystrokes to other apps. The keyboard codes can be looked up: here & here visually
unknown
d9404
train
Instead of Array#filter, you could use Array#find and take the object directly without later having a look up for the index. If found just add both wanted properties price and total. If you like not to mutate the original data, you could take a copy of the object for pushing. a.push({ ...c }); var array = [{ id: "1", price: 100, total: 200 }, { id: "1", price: 100, total: 200 }, { id: "2", price: 10, total: 200 }], result = array.reduce((a, c) => { let found = a.find(el => el.id === c.id); if (found) { found.price += c.price; found.total += c.total; } else { a.push(c); } return a; }, []); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; } A: All you have to do is add the totals as you did the price var obj = [{ id: "1", price: 100, total: 200 }, { id: "1", price: 100, total: 200 }, { id: "2", price: 10, total: 200 }] let newobj = obj.reduce((a, c) => { let filtered = a.filter(el => el.id === c.id); if (filtered.length > 0) { a[a.indexOf(filtered[0])].price += +c.price; a[a.indexOf(filtered[0])].total += +c.total; /* <-- new */ } else { a.push(c); } return a; }, []); console.log(newobj); A: You could do like this with help of spread operator var obj = [{ id: "1", price: 100, total: 200 },{ id: "1", price: 100, total: 200 },{ id: "2", price: 10, total: 200}] let newobj = Object.values(obj.reduce((acc,i) => { acc[i.id] = acc[i.id] ? {...acc[i.id],price:acc[i.id]['price']+i.price,total:acc[i.id]['total']+i.total} : i; return acc; }, {})); console.log(newobj)
unknown
d9405
train
Try This out LinearLayout busStopLinearLayout = (LinearLayout) findViewById(R.id.busStopLinearLayout); for(int i=0; i<closestStop.size(); i++){ TextView text = new TextView(this); text.setText("123"); text.setTextSize(12); text.setGravity(Gravity.LEFT); text.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); busStopLinearLayout.addView(text); }
unknown
d9406
train
\\Spotify\\Sidifyindex\\indexchecker.txt"); The file says "Z:\Spotify\Sidify test out\01 VVS.m4a" getline(infile, VMin); infile >> VMin; infile.close(); //clear drive letter VMin.erase(0, 1); //add new drive letter VMin = "A" + VMin; //copy file dir string outpath; outpath = VMin; //get new file name outpath.erase(0, 30); outpath = "A:\\Spotify\\Sidify test out\\" + outpath; //convert to const char* const char * c = VMin.c_str(); const char * d = outpath.c_str(); //rename int result; char oldname[] = "VMin.c_str()"; char newname[] = "outpath.c_str()"; result = rename(oldname, newname); if (result == 0) puts("File successfully renamed"); else perror("Error renaming file"); cout << VMin << endl; cout << outpath << endl; I'm getting "Error remaining file: no such file or directory" Output is correct "A:\Spotify\Sidify test out\01 VVS.m4a" and "A:\Spotify\Sidify test out\VVS.m4a" I assume that the issue is hidden somewhere in the rename part A: You wrote: char oldname[] = "VMin.c_str()"; char newname[] = "outpath.c_str()"; but you probably meant to do: char oldname* = VMin.c_str(); char newname* = outpath.c_str(); The first variant will look for a file which is called "VMin.c_str()" which does not exist and thus you are getting this error. You accidentally have put C++ code into quotes. Quotes are only for verbatim strings, like messages and fixed filenames. But your filenames are determined programmatically. You can use the const char * c and d you are calculating above and pass these to rename().
unknown
d9407
train
Try the following, String hostname = "myhostname";// example String port = "1234"; //example String url = "https://$hostname:$port/as/token.oauth2"; String body = "{'grant_type' : '$client_credentials' }" + "'scope' : '$accounts'" + //... etc etc "'Corresponding Response': { 'access_token': 'JWt CODE', 'expires_in': '86400', 'token_type': 'bearer', 'scope': 'payments' }"+ "}"; var res = await http.post(Uri.encodeFull(url), headers: { "Accept": "application/json", "Content-Type" : "application/x-www-form-urlencoded" }, body: body);
unknown
d9408
train
Ok, so one solution a coleague gave me for this was to comment out the jquery lines that position the calendar when it is displayed.
unknown
d9409
train
The other uninitialised variables are the missing (NA) values in the vector of t. Remember that the BUGS language makes no distinction between data and parameters, and that supplying something as data with the value NA is equivalent to not supplying it as data.
unknown
d9410
train
You should go with Composition. I don't think Inheritance makes sense because these are completely different type of entities and really one cannot inherit from the other. What fields will they inherit? And who inherits from whom? The BLL will need to pass the list of 'fields' to get to the DSL. Either as parameters to the DSL methods or in some other way. The DSL methods just receive some list of fields as parameters and work with them. I think that is a feasible solution. Also, you should create Interfaces at each Layer and program against them instead of using the type itself. So for e.g, in the sample code that you wrote, change DBL and WSB to IDBL and IWSB. This will help you test better and allow for loose coupling in the code. public class DSL { private IDBL _dbLayer; private IWSB _wsBuffer; .... } A: In general, inheritance should be used when you have an 'Is-A' relationship. Since you cannot say BLL 'Is-A' DSL or DSL 'Is-A' DBL, then I would be looking at composition over inheritance. This has the side effect of making testing each logical layer easier because you can stub or mock each dependency. Typically, in any exposed API, the server side (so DSL in terms of BLL -> DSL), would need to expose objects to do its work. You are right in pointing out that DSL should not know about BLL objects. So the challenge is to write a clean API for the DSL that is exposed to BLL for querying data. I would suggest looking at both the Repository and Specification patterns from DDD. These help to solve some of the issues that you are bringing up. A: Composition. Because of everything that dtryon and desigeek have said and also because in your case Inheritance looks unnatural + it will make all your layers tightly coupled and will hardly limit making of any amends to source code. I believe it could be helpful to take a look at prefer-composition-over-inheritance SO-topic.
unknown
d9411
train
INSERT INTO TargetTable(Col1, Col2, Col3) SELECT Col1, Col2, Col3 FROM SourceTable A: insert into table(column1, columns, etc) select columns from sourcetable You can omit column list in insert if columns returned by select matches table definition. Column names in select are ignored, but recommended for readability. Select into is possible too, but it creates new table. It is sometimes useful for selecting into temporary table, but be aware of tempdb locking by select into. A: SELECT col1, col2, ... INTO dbo.newtable FROM (SELECT ...query...) AS x;
unknown
d9412
train
Solved. There was another similar statement further down which was over riding this one! How stupid of me but easy to miss! A: use mysql_error to try and find what is wrong, then post that into here so we can help if you need it. (Would comment but to low rep) A: From my experience in the past, mysql_query() doesn't necessarily substitute variables before executing sql. Try writing in this format. Also use mysql_error to check if there are any issues with your code execution: $sql = "UPDATE my_users SET lastlogin=NOW() WHERE id=".$_SESSION["id"]; mysql_query($sql) or die(mysql_error()); If there is no error, then there are few possibilities as to why the laslogin entry is not happening: * *$_SESSION["id"] does not hold any value and no value is being passed to mysql. *There is no id matching with $_SESSION["id"]. To debug: * *Also try updating some other columns. *You might also want to check if you are using correct extensions like PDO.. Also found that, earlier version of mysql doesn't support updating datetime column with now(). In that case try resetting column type to TIMESTAMP. Refer this for details: https://bugs.mysql.com/bug.php?id=27645
unknown
d9413
train
As I understand you have to apply filter conditionally on specific property or all properties based on title. You could do something like below. <li class="list__item" ng-init="poster.filter = (poster.title =='The grand tour' ? {filter: posterTitle }: posterTitle" ng-repeat="poster in posters | filter: poster.filter"> <i ng-if="poster.title =='The grand tour'" class="fa fa-rocket list__fa" aria-hidden="true"></i>. {{poster.title}} </li>
unknown
d9414
train
Based on the question it sounds like you would like to calculate the distance between all pairs of points. Scipy has built in functionality to do this. My suggestion is to first write a function that calcuates distance. Or use an exisitng one like the one in geopy mentioned in another answer. def get_distance(point1, point2): R = 6370 lat1 = radians(point1[0]) #insert value lon1 = radians(point1[1]) lat2 = radians(point2[0]) lon2 = radians(point2[1]) dlon = lon2 - lon1 dlat = lat2- lat1 a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 c = 2 * atan2(sqrt(a), sqrt(1-a)) distance = R * c return distance Then you can pass this function into scipy.spatial.distance.cdist all_points = df[[latitude_column, longitude_column]].values dm = scipy.spatial.distance.cdist(all_points, all_points, get_distance) As a bonus you can convert the distance matrix to a data frame if you wish to add the index to each point: pd.DataFrame(dm, index=df.index, columns=df.index) NOTE: I realized I am assuming, possibly incorrectly that you are using pandas A: If you don't mind importing a few libraries, this can be done very simply. With pandas, you can read your text file into a dataframe, which makes working with tabular data like this super easy. import pandas as pd df = pd.read_csv('YOURFILENAME.txt', delimiter=' ', header=None, names=('latitude', 'longitude')) Then you can use the geopy library to calculate the distance. A: Another solution is using the haversine equation with numpy to read in the data and calculate the distances. Any of the previous answers will also work using the other libraries. import numpy as np #read in the file, check the data structure using data.shape() data = np.genfromtxt(fname) #Create the function of the haversine equation with numpy def haversine(Olat,Olon, Dlat,Dlon): radius = 6371. # km d_lat = np.radians(Dlat - Olat) d_lon = np.radians(Dlon - Olon) a = (np.sin(d_lat / 2.) * np.sin(d_lat / 2.) + np.cos(np.radians(Olat)) * np.cos(np.radians(Dlat)) * np.sin(d_lon / 2.) * np.sin(d_lon / 2.)) c = 2. * np.arctan2(np.sqrt(a), np.sqrt(1. - a)) d = radius * c return d #Call function with your data from some specified point haversine(10,-110,data[:,1],data[:,0]) In this case, you can pass a single number for Olat,Olon and an array for Dlat,Dlon or vice versa and it will return an array of distances. For example: haversine(20,-110,np.arange(0,50,5),-120) OUTPUT array([2476.17141062, 1988.11393057, 1544.75756103, 1196.89168113, 1044.73497113, 1167.50120561, 1499.09922502, 1934.97816445, 2419.40097936, 2928.35437829])
unknown
d9415
train
Solved by Hi-Angel: the problem is that you have two constructors with a default values. The call datatype() at the line 8 is ambiguous: which one should be chosen? As far as I know, you couldn't resolve this by anything with an exception of just removing one of a default values. Disclaimer: this was extracted from the question and posted here on the OP's behalf.
unknown
d9416
train
I was able to find the answer , just for future reference if someone else get's stuck in this situation ## @inputs: [frame1 = applymapping1,frame2 = applymapping2,frame3 = applymapping3,frame4 = applymapping4 ]
unknown
d9417
train
db.Employee.aggregate([{ $lookup: { from: "Salary", localField: "POSITION", foreignField: "POSITION", as: "MOnthlySalary"}}, {$unwind:"$MOnthlySalary"}, {$match:{}}, {$project: {"EMPLOYEE_NO":1,"LNAME":1,"FNAME":1,"SALARY":1, "avgSalary": {$divide: ["$MOnthlySalary.SALARY", 12]} }}]) Change is $MOnthlySalary.SALARY Output: /* 1 */ { "_id" : ObjectId("5efa0fffc8a4b73cb0b8e320"), "EMPLOYEE_NO" : "1000", "LNAME" : "Wyatt", "FNAME" : " Stefan", "avgSalary" : 12500.0 } /* 2 */ { "_id" : ObjectId("5efa0fffc8a4b73cb0b8e321"), "EMPLOYEE_NO" : "1029", "LNAME" : "Martin", "FNAME" : "Edward", "avgSalary" : 5833.33333333333 } /* 3 */ { "_id" : ObjectId("5efa0fffc8a4b73cb0b8e322"), "EMPLOYEE_NO" : "1089", "LNAME" : "Stewart", "FNAME" : "Macy", "avgSalary" : 2500.0 } You can use $round to round the avgSalary.
unknown
d9418
train
I don't think there's anything you can do as far as changing the signed version parameter. My guess is that the implementation to generate SAS via Storage Resource Provider API makes use of Storage REST API version 2015-04-05 (signed version parameter) and if you look at request body parameters, you will notice that there's no parameter to specify the signed version parameter in the request. One thing you could do is change your upload implementation and upload your large blob in chunks where the size of each chunk is less than or equal to 64 MB. FWIW, the block size limit was changed from 64 MB to 100 MB in Storage Service version 2016-05-31: https://learn.microsoft.com/en-us/rest/api/storageservices/version-2016-05-31.
unknown
d9419
train
This is a javascript version var elements = document.getElementsByTagName('input'); for(var i = 0; i< elements.length; i++) { if (elements[i].type == "checkbox") { elements[i].checked = !elements[i].checked; } } if you have jQuery use this $("#CoverageList").click(function() { var checked_status = this.checked; $('#actions').find("input").each(function() { $(this).prop("checked", checked_status); }); });
unknown
d9420
train
Try it with $("#wrapper").animate({"marginLeft":"50%"}, 1000); A: $('#wrapper').animate({right: (parseInt($(this).css('right'))-200)+"px"}, 1000);
unknown
d9421
train
No, C doesn't have anything like that. If you can use C++, there's std::list. You'll have to write the structure yourself in C. A: As others have said, there is no standard library support for linked lists in C. That means you either get to roll your own (like most people have done at one or more times in their C coding career), or you look at other libraries for support. For most uses, you will find that an 'intrusive' implementation is appropriate. You modify your existing structure to include a pointer to the next item in the list (and, if you're doing a doubly linked list, the previous item). typedef struct TheStruct TheStruct; struct TheStruct { ...the real data... TheStruct *next; //TheStruct *prev; }; Your list now consists of a simple pointer to the head item: TheStruct *head = 0; TheStruct *allocated_node = new_TheStruct(value1, value2, ...); assert(allocated_node->next == 0); // Insert new allocated node at head of list allocated_node->next; head = allocated_node; You have to worry about threading issues if you've got threads access the same list, and so on and so forth. Because this code is so simple, this is how it is most frequently handled. Deleting a node from a list is trickier, but you can write a function to do it. People have dressed up this basic scheme with macros of varying degrees of complexity so that the code manipulating different types of lists can use the same macros. The Linux kernel uses a macro-based set of linked lists for managing its linked list data structures. The alternative to the 'intrusive' implementation (which is so-called because it requires a change to the structure to include the list pointers) is to have some generic list mechanism: typedef struct GenericList GenericList; struct GenericList { void *data; GenericList *next; //GenericList *prev; }; Now you have the ability to put (pointers to) unmodified structures into the list. You lose some type safety; there is nothing to stop you adding random different structure types to a list that should be homogeneous. You also have to allocate memory for the GenericList structures separately from the pointed at data. * *One advantage of this is that a single data item can be on multiple separate lists simultaneously. * One disadvantage of this is that a single data item can accidentally be on multiple lists, or multiple times in a single list, simultaneously. You also have to make sure you understand the ownership properties for the data, so that the data is released properly (not leaked, not multiply-freed, not accessed after being freed). Managing the memory for the list itself is child's play by comparison. With the GenericList mechanism, you will likely have a library of functions that manage the list operations for you. Again, searching should reveal implementations of such lists. A: C does not (as yet) provide any standard container structures. You'll have to roll your own. A: It doesn't exist by default, but it can be made quite easily. Basically a linked list is a header pointer that points to 1st element, and an ending file pointing to null. The elements are actually nodes, containing the object and a pointer to the next node. So making a basic one is quite easy, though in C it might be painful as no classes, only structs. A: There are no Lists in the standard C library. A very good C library you can use is PBL - The Program Base Library here. Its interface is Java like. You can download it from here
unknown
d9422
train
For %%e in (!end!) Do set numel=!strel:~0,%%e! The trick is to use a for loop parameter, because the parameter is expanded before the delayed expansion will be executed. A: Thanks to the various contributors, the code snippet simplified to: FOR /f "delims=:" %%i IN ('FINDSTR /b /l /n /c:%_ndelm% %_infil%') do ( set "end=%%i" IF !end! GEQ %_atpos% GOTO fetchlines ) which improved readability and performance. The answer to the Question posed is the accepted answer from @Jeb.
unknown
d9423
train
let healthKitStore:HKHealthStore = HKHealthStore() func authorizeHealthKit(completion: ((_ success:Bool, _ error:NSError?) -> Void)!) { //check app is running on iPhone not other devices(iPad does not have health app) if !HKHealthStore.isHealthDataAvailable() { let error = NSError(domain: "DomainName.HealthKitTest", code: 2, userInfo: [NSLocalizedDescriptionKey:"HealthKit is not available in this Device"]) if completion != nil { completion(false, error) } return; } healthKitStore.requestAuthorization(toShare: healthKitTypeToWrite() as? Set<HKSampleType>, read: nil) { (success, error) -> Void in if completion != nil { print("Success: \(success)") print("Error: \(error)") completion?(success, error as NSError?) } } } func healthKitTypeToWrite() -> NSSet { let typesToWrite = NSSet(objects: HKQuantityType.quantityType(forIdentifier: .dietaryFatTotal), HKQuantityType.quantityType(forIdentifier: .dietaryFatSaturated), HKQuantityType.quantityType(forIdentifier: .dietaryCarbohydrates), HKQuantityType.quantityType(forIdentifier: .dietarySugar), HKQuantityType.quantityType(forIdentifier: .dietaryProtein), HKQuantityType.quantityType(forIdentifier: .dietarySodium)) return typesToWrite } And make sure you add 'NSHealthUpdateUsageDescription' to your info.plist and description saying why you need access to your app. Hope this will help you. A: Adding NSHealthUpdateUsageDescription in my info.plist fixed the issue for me.
unknown
d9424
train
I've fixed the problem. A case that happens once in a blue moon left a null value within a field that was within a linq query. What I don't know, however, is why this would make the app unusable for everyone. One instance makes the app wig out for everyone.....
unknown
d9425
train
I faced the similar problem. The jar was locked because the server was running using that jar. Terminating the server worked.
unknown
d9426
train
I get your question right, you have x and y as window space (and already converted to normalized device space [-1,1]), but z in eye space, and want to recosntruct the world space position. I can't have access to other (I can't use near, far, left, right, ...) because projection matrix is not restricted to perspective or orthogonal. Well, actually, there is not much besides an orthogonal or projective mapping which can be achieved by matrix multiplication in homogenous space. However, the projection matrix is sufficient, as long as it is invertible (In theory, a projection matrix could transform all points to a plane, line or a single point. In that case, some information is lost and it will never be able to reconstruct the original data. But that would be a very untypical case). So what you can get from the projection matrix and your 2D position is actually a ray in eye space. And you can intersect this with the z=depth plane to get the point back. So what you have to do is calculate the two points vec4 p = inverse(uProjMatrix) * vec4 (ndc_x, ndc_y, -1, 1); vec4 q = inverse(uProjMatrix) * vec4 (ndc_x, ndc_y, 1, 1); which will mark two points on the ray in eye space. Do not forget to divide p and q by the respective w component to get the 3D coordinates. Now, you simply need to intersect this with your z=depth plane and get the eye space x and y. Finally, you can use the inverse of the uModelView matrix to project that point back to object space. However, you said that you want world space. But that is impossible. You would need the view matrix to do that, but you have not listed that as a given. All you have is the compisition of the model and view matrix, and you need to know at least one of these to reconstruct the world space position. The cameraPosition is not enoguh. You also need the orientation.
unknown
d9427
train
NSString *DocPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; filePath=[DocPath stringByAppendingPathComponent:@"AlarmClock.plist"]; if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { NSString *path=[[NSBundle mainBundle] pathForResource:@"AlarmClock" ofType:@"plist"]; NSLog(@"file path: %@",filePath); NSDictionary *info=[NSDictionary dictionaryWithContentsOfFile:path]; [info writeToFile:filePath atomically:YES]; } //***Try this... A: I tryed the code on an other mac and there it works It's the same project. can anyone explain me why the plist is created on one mac but not on the other? on the IPhone also no plist is written? I guess in both cases this is cause the array I write to the plist is empty: NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *plistPath = [rootPath stringByAppendingPathComponent:@"list.plist"]; NSMutableArray *currentArray = [[NSMutableArray alloc] initWithContentsOfFile:plistPath]; NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys: [selectet valueForKey:NAME], @"name", nil]; NSLog(@" DIC. : %@", dictionary); [currentArray addObject:[dictionary copy]]; NSLog(@" %@", currentArray); [currentArray writeToFile:plistPath atomically:YES]; [currentArray release]; the dictionary has the entry but currentArray is empty.... And still it works on one mac. but not on the other and on the IPhone. Edit: For some reason it worked again. To be sure I deleted the plist from the document folder and cleared all targets. And now the Problem as before I can only write the plist when i write the dictionary to it but then i can only save the last one. And reading the plist won't work either. Can anyone Tell me why this happens and how I can solve it? Edit 2: I found the Problem: since X-Code won't create the plist when I write the array with the dictionary to the plist.When I wrote the dictionary to the plist so X-Code creates the plist but with a dictionary Root so I cant write the array to it and I also can't read it in an Array..... I created a plist in the Resources folder with a Array Root and copy it when it not exist to document folder and now it works..... isn't it amazing how such easy things can give you such an headache
unknown
d9428
train
if you want to skip the spot instance all you need to do this is figure out which one is spot instance. You need to use describe_instances api and then using if-else condition, request_id is empty its a spot instance, if not then its not a spot instance import boto3 ec2 = boto3.resource('ec2') instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]) #add filter of your own choice for instance in instances: if instance.spot_instance_request_id: # logic to skip termination ( spot instance ) else: # logic to terminate ( not spot instance ) You can refer a similar question on this -> https://stackoverflow.com/a/45604396/13126651 docs for describe_instances
unknown
d9429
train
Add the below statement instead of connect to db \c mydb; The reorder statements of execution should be CREATE DATABASE mydb; \c mydb; CREATE USER myusername WITH PASSWORD 'mypassword'; GRANT ALL PRIVILEGES ON DATABASE mydb TO myusername; CREATE TABLE administrator ( id integer NOT NULL, admin_name character varying(150), password character varying(255), active boolean, "timestamp" timestamp without time zone, email character varying(255) ); ALTER TABLE administrator OWNER TO myusername;
unknown
d9430
train
Just add keyboardShouldPersistTaps={'handled'} to your ScrollView <ScrollView keyboardShouldPersistTaps={'handled'}> ...... .............. </ScrollView>
unknown
d9431
train
For this you need to first create a model that can parse this kind of json for you. you can use a pretty neat plugin that I have been sing called json to kotlin class. Steps to install: * *Go to file->settings->plugins *search for json to kotlin and install *now just like you make a new file there will be a new option paste your json and give it a name and now it automatically generates a model for you. *Also I will recommend you to watch some tutorials on youtube, my favorite content creator is Philip Lackener he has a very good tutorial on roomdb I am also new to android development so i get it. I recommend you to go through a beginner playlist it will really help you get the basics. you also need to see basics of roomdb because what you are asking is really basics of roomdb.
unknown
d9432
train
From the C++ 20 (11.6.3 Abstract classes) *...[Note: A function declaration cannot provide both a pure-specifier and a definition — end note] [Example: struct C { virtual void f() = 0 { }; // ill-formed }; — end example]
unknown
d9433
train
Here are my example which is working: links.txt is looking like in this example http://www.site1.com http://www.site2.com http://www.site2.com/page1 no space after each line and no break at the end of file <?php $LF = 'links.txt'; $Rfp = fopen($LF, 'r'); while(!feof($Rfp)) { $links = fgets($Rfp); echo "<br>"; echo "<font color=\"red\">Load URL: $links </font>"; $tags = get_meta_tags($links); echo "<br>"; if ($tags['description'] == "") echo "No META Description Found"; else echo "<br>"; echo "<b>Description</b> - "; echo $tags['description']; echo "<br>"; if ($tags['keywords'] == "") echo "No META Keywords Found"; else echo "<br>"; echo "<b>Keywords</b> - "; echo $tags['keywords']; echo "<br>"; } fclose($Rfp); ?> the result look well and no errors A: The answer you need is right in the warning output you included...note the space after the URL: Warning: get_meta_tags(http://www.example.com ) [function.get-meta-tags] If you add: $links = trim($links); Your code will start working. A: php_network_getaddresses: getaddrinfo failed: No such host is known Apparently, PHP is unable to load the page. Perhaps the links don't have the proper format? A quick test shows that this happens when I try get_meta_tags('http://domain.com http://another-domain.com');, perhaps there is something wrong with the newlines? (Windows vs Unix line-endings?)
unknown
d9434
train
To get the list of all objects, you must use Model.objects.all() So make these changes in your view def showallwines(request): wines = ListWines.objects.all() # changed # changed context name to wines since it is list of wines not names. return render(request, 'main.html', { 'wines': wines } ) main.html You have to use the context name wines since we are passing the context wines from the view {% for wine in wines %} <option>{{ wine.name }}</option> {% endfor %} A: views.py Insted of ListWines.objects use ListWines.objects.all() and update context name with "showallwines" this. def showallwines(request): wines = ListWines.objects.all() return render(request, 'main.html', { 'showallwines':wines } )
unknown
d9435
train
I think you should look into jQuery as your default javascript library, it's used by many web professionals and is very good. There you will find the Accordion control, which I think will suite this need very well. Good luck!
unknown
d9436
train
Initial question: val columns = df_cols .where("id = 2") .select("list_of_colums") .rdd.map(r => r(0).asInstanceOf[Seq[String]]).collect()(0) val df_data_result = df_data.select(columns(0), columns.tail: _*) +-------+-------+ | col1| col2| +-------+-------+ |col1_r1|col2_r1| |col1_r2|col2_r2| +-------+-------+ Updated question: 1) We may just use 2 lists: static columns + dynamic ones 2) I think that "rdd" is ok in this code. I don't know how to update to "Dataframe" only, unfortunately. val staticColumns = Seq[String]("group", "industry_id") val dynamicColumns = df_cols .where("id = 2") .select("list_of_colums") .rdd.map(r => r(0).asInstanceOf[Seq[String]]).collect()(0) val columns: Seq[String] = staticColumns ++ dynamicColumns val df_data_result = df_data.select(columns(0), columns.tail: _*) +-----+-----------+-------+-------+ |group|industry_id| col1| col2| +-----+-----------+-------+-------+ | G1| I1|col1_r1|col2_r1| | G1| I2|col1_r2|col2_r2| +-----+-----------+-------+-------+
unknown
d9437
train
You may start with the Unix "High-level process and redirection management" functions, e.g., create_process prog args new_stdin new_stdout new_stderr is a generic function that will create a process that runs a program, and it allows you to redirect the channels. The created process will run asynchronously, so you can either peek it with waitpid's WNOHANG flag, or just block until it ends (probably the latter shouldn't work for you). Probably, the following interface should suffice your needs: module Monitor : sig val start : string -> t val terminate : t -> unit val on_finish : t -> (int -> unit) -> unit ... end or you can just simplify it to val monitor : string -> (int -> 'a) -> 'a if you don't want to have to manage monitor instances. Alternatively, you can take a look at the Lwt high-level process management library. It might save you quite a few keystrokes. There is also an alternative async unix library from Janestreet, that you may try.
unknown
d9438
train
I think the issue is that you are trying to use the entire text as the key to the dictionary. So, if the text "A" is entered into the text input then it works as "A" is a key in my_dictionary. If the text "AS" is entered into the text box, this will fail as there is no key "AS" in my_dictionary. What you will want to do, therefore, is loop over each of the characters in the entered string and add the Morse value of that letter to your definition string. You will also want to make sure that the letter is uppercase (unless it is guaranteed that the input will be upper case). This is done using the string .upper() method in the following example. Something like the following should do what you want. definition = str() # Create a blank string to add the Morse code to # Go through each letter and add the Morse definition of the letter to definition for letter in entered_text: definition += my_dict[letter.upper()] # The upper makes sure the letter is a capital so that there will be a match in my_dict
unknown
d9439
train
You can put references to the labels in an array and access them with that. I put five labels on a form (leaving their names as the defaults) and used this code as an example: private void SetLabelsText() { // Put references to the labels in an array Label[] labelsArray = { label1, label2, label3, label4, label5 }; for (int i = 0; i < labelsArray.Count(); i++) { labelsArray[i].Text = "I am label " + (i + 1).ToString(); } } private void Form1_Load(object sender, EventArgs e) { SetLabelsText(); } A: To answer your comment to my Comment. Since FindControl takes a string as an input you would just create the string with the component name you are looking for. Be aware that you have to use the FindControl Method of the container that your labels are in. From Link(emphasis mine): Use FindControl to access a control from a function in a code-behind page, to access a control that is inside another container, or in other circumstances where the target control is not directly accessible to the caller. This method will find a control only if the control is directly contained by the specified container; that is, the method does not search throughout a hierarchy of controls within controls. For information about how to find a control when you do not know its immediate container, see How to: Access Server Controls by ID. so something like this should work for you. ((Label) this.FindControl("lblQuestion" + (i+1))).Text = reader["answer" + (i+1)].ToString();
unknown
d9440
train
I just do: val bytes = listOf(0xa1, 0x2e, 0x38, 0xd4, 0x89, 0xc3) .map { it.toByte() } .toByteArray() A: as an option you can create simple function fun byteArrayOfInts(vararg ints: Int) = ByteArray(ints.size) { pos -> ints[pos].toByte() } and use it val arr = byteArrayOfInts(0xA1, 0x2E, 0x38, 0xD4, 0x89, 0xC3) A: If all your bytes were less than or equal to 0x7F, you could put them directly: byteArrayOf(0x2E, 0x38) If you need to use bytes greater than 0x7F, you can use unsigned literals to make a UByteArray and then convert it back into a ByteArray: ubyteArrayOf(0xA1U, 0x2EU, 0x38U, 0xD4U, 0x89U, 0xC3U).toByteArray() I think it's a lot better than appending .toByte() at every element, and there's no need to define a custom function as well. However, Kotlin's unsigned types are an experimental feature, so you may have some trouble with warnings. A: The issue is that bytes in Kotlin are signed, which means they can only represent values in the [-128, 127] range. You can test this by creating a ByteArray like this: val limits = byteArrayOf(-0x81, -0x80, -0x79, 0x00, 0x79, 0x80) Only the first and last values will produce an error, because they are out of the valid range by 1. This is the same behaviour as in Java, and the solution will probably be to use a larger number type if your values don't fit in a Byte (or offset them by 128, etc). Side note: if you print the contents of the array you've created with toInt calls, you'll see that your values larger than 127 have flipped over to negative numbers: val bytes = byteArrayOf(0xA1.toByte(), 0x2E.toByte(), 0x38.toByte(), 0xD4.toByte(), 0x89.toByte(), 0xC3.toByte()) println(bytes.joinToString()) // -95, 46, 56, -44, -119, -61
unknown
d9441
train
In version 3 of Svelte you can assign a new value to the variable directly without using set. You can name the default to something other than ChatBox so that the outer variable isn't shadowed, and then assign directly to it. let ChatBox; async function loadChatBox() { const { default: Component } = await import("./ChatBox.svelte"); ChatBox = Component; }
unknown
d9442
train
For the potential benefit of other people, this question was answered on the theano-users mailing list: https://groups.google.com/forum/#!topic/theano-users/6P5KxLph2I8 The recommended solution, by Pierre Luc Carrier, was: mask = input_reshaped.argmax(axis=3).astype("float32") * -2 + 1 return input_reshaped.max(axis=3) * mask
unknown
d9443
train
Notice that std::enable_if<..., int>::type in your parameter list is an non-type template argument: template<typename ContainerType, typename std::enable_if<std::is_same<ContainerType, Eigen::MatrixXd>::value, int>::type = 0> class graph { void graph_func() const; }; You need to pass the value of that type (In here we just named it _) to the parameter list: template <typename ContainerType, typename std::enable_if<std::is_same<ContainerType, Eigen::MatrixXd>::value, int>::type _> void graph<ContainerType, _>::graph_func() const { // definition } See live demo.
unknown
d9444
train
You can just use the + operator to concatenate lists: ListOne = ['jumps', 'over', 'the'] ListTwo = ['The', 'quick', 'brown', 'fox'] + ListOne + ['lazy', 'dog!'] ListTwo will be: ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!'] A: Another alternative is to use slicing assignment: >>> ListOne = ['jumps', 'over', 'the'] >>> ListTwo = ['The', 'quick', 'brown', 'fox', 'lazy', 'dog!'] >>> ListTwo[4:4] = ListOne >>> ListTwo ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!'] A: >>> ListOne = ['jumps', 'over', 'the'] >>> from itertools import chain >>> [x for x in chain(['The', 'quick', 'brown', 'fox'], ListOne, ['lazy', 'dog!'])] ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!'] A: Why not concatenate? >>> ListTwo = ['The', 'quick', 'brown', 'fox'] >>> ListOne = ['jumps', 'over', 'the'] >>> ListTwo + ListOne ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the'] >>> ListTwo + ListOne + ['lazy', 'dog!'] ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']
unknown
d9445
train
Try jEdit - they have auto-indentation, and works on most OSes. http://www.jedit.org/ A: "Any" IDE will do it for you. So which one are you using ? Vim : gg , = , G Netbeans : "Select the lines you want to reformat (indenting), then hit Alt+Shift+F. Only the selected lines will be reformatted." Notepad++ : Check out this link posted here A: Eclipse has a configurable source code formatter that can be triggered automatically on Save and manually with Ctrl+Shift+F (customizable shortcut) for most if not all editor plugins (i.e., most if not all languages). Of those that I use, only PHP Development Tools has configuration limits there. You really should name the programming/markup language(s) that you are using. A: AStyle (C/C++/Java/C#) command line tool. I use it within any IDE by invoking external command with shortcut. http://astyle.sourceforge.net/
unknown
d9446
train
qqp() doesn't count the number of points outside the confidence envelope but it computes the information that's needed to get this count. You can simply modify the code (car:::qqPlot.default) if you change: outerpoints <- sum(ord.x > upper | ord.x < lower) print(outerpoints) if (length(outerpoints) > -1) outerpoints else invisible(NULL) the output show the number of points outside the confidence envelope.
unknown
d9447
train
I've used this before, the image must be of a PNG type, and it should be background is empty. Or using it in another way, like this: InkResponse( icon: Image.asset("assets/icons/library.png",width: 30,height: 30,), onTap: (){ }, ),
unknown
d9448
train
All the other classes you import from caller.java (from another project outP) should eventually be placed on the WEB-INF/lib You can use eclipse or MAVEN to do that.
unknown
d9449
train
The following code ended up working: class RepostsController < ApplicationController def index @reposts = Repost.all end def create @repost= Repost.new("comment_id" => params[:comment_id],"user_id" => params[:user_id]) @content = @repost.comments.content if @repost.save #flash[:success] = "Post created!" redirect_to root_url else render 'activities' end end end <%= link_to image_tag('purple_star.png', :size => "16x16", :align => "right"), {:controller => 'reposts', :action => 'create', :comment_id => @comment, :user_id => @comment.user}, :title=> "Pass it on!", :method=>'post' %> Thanks for the time and assistance everyone!
unknown
d9450
train
Assume your table has id="mytable": This is how you get all the trs: 1. var trs = document.getElementById("mytable").rows; or 2. var trs = document.getElementById("mytable").getElementsByTagName("tr"); Now do this: while(trs.length>0) trs[0].parentNode.removeChild(trs[0]); If you don't have id for your table and you have only one table on the page, do this: var trs = document.getElementsByTagName("table")[0].rows; It would be hard to remove a specific tr if you don't give it an id. If you want to remove certain kind of trs, give them a class attribute and remove only those trs with this class attribute. A: You could try something like this with jQuery: $(function(){ $('tr, td').remove(); }); Or if — for whatever reason — you'd like to remove all contents of a table: $('table').empty(); A: Once you have identified the <tr> you wish to remove (you haven't provided enough context to your question to suggest (without making lots of assumptions) how you might do that): tr_element.parentNode.removeChild(tr_element) A: try something like this <html> <head> <style> </style> <script src="http://code.jquery.com/jquery-latest.js"></script> </head> <body> <table> <tr> <td>test</td><td>test</td><td>test</td> </tr> <tr> <td>test</td><td>test</td><td>test</td> </tr> </table> <button>Empty</button> <script> $("button").click(function () { $("table").empty(); }); </script> </body> </html>
unknown
d9451
train
Add an “=“ at the beginning of your Criteria and an asterisk at its end Range("Item").AutoFilter , Field:=1, Criteria1:="=" & CStr(Range("A1").Value) & "*" See I omit ”ActiveSheet” since it’s implicitly assumed But you’d better always explicitly qualify your ranges up to workbook and worksheet references like: With WorkBooks("MyWorkbookName").WorkSheets("MySheetName") .Range("Item").AutoFilter , Field:=1, Criteria1:="=" & CStr(.Range("A1").Value) & "*" End With
unknown
d9452
train
Here's how i did it: Exec(ExpandConstant('{dotnet40}\InstallUtil.exe'), ServiceLocation, '', SW_HIDE, ewWaitUntilTerminated, ResultCode); Apparently, Inno setup has the following constants for referencing the .NET folder on your system: * *{dotnet11} *{dotnet20} *{dotnet2032} *{dotnet2064} *{dotnet40} *{dotnet4032} *{dotnet4064} More information available here. A: You can use Exec( ExpandConstant('{sys}\sc.exe'), ExpandConstant('create "MyService" binPath= {app}\MyService.exe start= auto DisplayName= "My Service" obj= LocalSystem'), '', SW_HIDE, ewWaitUntilTerminated, ResultCode ) to create a service. See "sc.exe" on how to start, stop, check service status, delete service, etc. A: You don't need installutil.exe and probably you don't even have rights to redistribute it. Here is the way I'm doing it in my application: using System; using System.Collections.Generic; using System.Configuration.Install; using System.IO; using System.Linq; using System.Reflection; using System.ServiceProcess; using System.Text; static void Main(string[] args) { if (System.Environment.UserInteractive) { string parameter = string.Concat(args); switch (parameter) { case "--install": ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location }); break; case "--uninstall": ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location }); break; } } else { ServiceBase.Run(new WindowsService()); } } Basically you can have your service to install/uninstall on its own by using ManagedInstallerClass as shown in my example. Then it's just matter of adding into your InnoSetup script something like this: [Run] Filename: "{app}\MYSERVICE.EXE"; Parameters: "--install" [UninstallRun] Filename: "{app}\MYSERVICE.EXE"; Parameters: "--uninstall" A: If you want to avoid reboots when the user upgrades then you need to stop the service before copying the exe and start again after. There are some script functions to do this at Service - Functions to Start, Stop, Install, Remove a Service A: have a look at topshelf http://topshelf-project.com/ * *it lets you develop your service as a console application *adds a start/stop service as an API to your service... *... that you can call from InnoSetup [Run] Filename: "{app}\myservice.exe"; Parameters: "stop" ; Flags : waituntilterminated Filename: "{app}\myservice.exe"; Parameters: "uninstall" ; Flags : waituntilterminated Filename: "{app}\myservice.exe"; Parameters: "install -description ""myservice""" ; Flags : waituntilterminated
unknown
d9453
train
This issue should go away when you enable the null-safety feature. The analyzer's code flow analysis has been much improved for NNBD to fix this and similar cases. (You can verify this in DartPad with null-safety enabled.) In the meantime, you also could just remove the superfluous else: String f(int x, int y) { switch (x) { case 0: if (y > 10) { return 'StringA'; } return 'StringB'; default: return 'Anything'; } } or remove the superfluous default case: String f(int x, int y) { switch (x) { case 0: if (y > 10) { return 'StringA'; } else { return 'StringB'; } } return 'Anything'; }
unknown
d9454
train
You can checkout all limits wrt Azure Service Bus from here: https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-quotas
unknown
d9455
train
the third argument is of type REFIID which in turn is defined as a *IID where an IID is defined as a GUID. So the third argument should be a pointer to a GUID object. The documentation you linked is incorrect. I suspect it was written for C. In C++, REFIID and REFCLSID are defined as IID references in Windows headers, like so: #ifdef __cplusplus #define REFIID const IID & #else #define REFIID const IID * __MIDL_CONST #endif #ifdef __cplusplus #define REFCLSID const IID & #else #define REFCLSID const IID * __MIDL_CONST #endif
unknown
d9456
train
What you can do for solving the vertical constraint issue is to give Equal constraints to your button1 and button2 and give a fixed vertical constraint to the something view and from your second button to the bottom of the superview. So this way you won`t need to give a fixed height to any of them and the distance between them and other elements (something and bottom of superview) will be standard. I hope this helps! A: Ok, I think I made it. Here is what I did : * *I set all my constraints in the storyboard, with the Retina 4" form-factor. *Constraints for the something view : fixed height & width, fixed top space and leading space. This view is absolutely fixed. *Constraints for button 1 : fixed vertical space to something view, fixed leading space, fixed width. 2 height constraints : 30 <= height <= 50. *Constraints for button 2 : fixed vertical space to button 1, fixed leading space, fixed width. Also 2 height constraints : 30 <= height <= 50. And fixed bottom space to bottom layout. All constraints have a maximum priority of 1000, except the last one (fixed bottom space to bottom layout), which is set at 900 ! That way, the buttons keep a height >=30 and move up, but get shrinked vertically because the other constraints are more important. Thanks a lot to @VasiliyDeych and @P.Sami for their advice. It helped a lot. A: You're going to need to show us how your constraints are set up. Constraints are a set of rules that the views must follow. If there is no rule saying the button must shrink with the parent view, it will not happen. Based on your example, if I understood it correctly, you would want a set of constraints like this (defined in VFL for ease): [yourParentView addVisualConstraints:@"V:|[something(100@75)]-(10@100)-[button1(<=50,>=30@100)]-(10@100)-[button2(button1@100)]-(>=300@50)-|" forViews:NSDictionaryOfVariableBindings(something,button1,button2)]; All constraints here are vertical (V:), the numbers in parentheses represent a number of points, followed by @ and the desired priority of maintaining that number of points. The | symbols represent the top and bottom edges of the superview. So ]-(>=300@50)-| is saying, I'd like to keep 300 or more pixels between button2 and the bottom of the superview, but I care about it with a priority of 50. button1(<=50,>=30@100) means I really care that this button is between 30 and 50 pixels in height, with a priority of 100. button2(button1) means I want button2 to be the same height as button1. I also really care about keeping that 10-point distance between my elements. And I somewhat care that something (which is flush to the superview's top edge, hence |[) is going to stay at 100 points tall. Does this not work for what you are intending to do?
unknown
d9457
train
It might be easier to use the OpenDirectory for the windows boxes but thats not the question. You can use OpenLDAP as backend for your Macs. But the OpenLDAP has to implement the schema of the OpenDirectory (which in itself uses OpenLDAP as backend). Those schema-files are lokated in different places depending on the MacOSVersion you are using. you have to place those files inside the OpenLDAPs schema folder and restart the ldap. After that you can extend the users to make use of that Information. But you will have to adapt the mapping of Information on the Mac-clients so that all relevant information from the LDAP ends up in the right places. Not an easy task. I'd think twice wheter it makes sense for a handfull or two of macBoxes. We've implemented for 150 Macs and it was a pain to get everything right. And AFAIK there is no easy way of bringing an OpenLDAP and an OpenDirectoy in synch eith one another due to the schema extension apple used. Depending on the frontend you use you might be able to implement a mechanism that adds a user to two LDAPs when the are created but what about changing passwords? Or changing a users name? you will have to do a lot of manual adaptions to make that possible. So In my opinion not an easy task especially when you have to catch up on some LDAP stuff and the LDAP documentation of Apple is rather sparse... A: Your question title says "Import OpenLDAP directory into OSX Open Directory". Which you certainly can. LDAP is a wire protocol. Check out PORTABLE HOME DIRECTORIES WITH OPENLDAP You then ask "is it possible to be able to sync Open Directory with the OpenLDAP server". Yes, there are many IDM products out there that will allow sync two LDAP directories. NetIQ IDM, http://forgerock.com/, and many others. But, probably more than you want to deal with. (I think they are best for 1000+ Users) A: Use below listed function and export that schema to LDIF format. ldapmodify If possible then use ldap admin tool phpldapadmin,ldap admin etc Export whole shema or branch in ldif and .xml(dsml) type. Then Inport it to desired directory server by using admin tool else commandline function ldapadd
unknown
d9458
train
Why DIY? If you only need to determine drive speed and not really interested in learning how to flush I/O buffers from .NET, you may just use DiskSpd utility from http://research.microsoft.com/barc/Sequential_IO/. It has random/sequential modes with and without buffer flushing. The page also has some I/O related research reports you might find useful. A: const int FILE_FLAG_NO_BUFFERING = 0x20000000; return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,64 * 1024, (FileOptions)FILE_FLAG_NO_BUFFERING | FileOptions.Asynchronous & FileOptions.SequentialScan); A: Constantin: Thanks! That link has a command-line EXE which does the testing I was looking for. I also found a link off that page to a more interesting article (in Word and PDF) on this page: Sequential File Programming Patterns and Performance with .NET In this article, it talks about Un-buffered File Performance (iow, no read/write caching -- just raw disk performance.) Quoted directly from the article: There is no simple way to disable FileStream buffering in the V2 .NET framework. One must invoke the Windows file system directly to obtain an un-buffered file handle and then ‘wrap’ the result in a FileStream as follows in C#: [DllImport("kernel32", SetLastError=true)] static extern unsafe SafeFileHandle CreateFile( string FileName, // file name uint DesiredAccess, // access mode uint ShareMode, // share mode IntPtr SecurityAttributes, // Security Attr uint CreationDisposition, // how to create uint FlagsAndAttributes, // file attributes SafeFileHandle hTemplate // template file ); SafeFileHandle handle = CreateFile(FileName, FileAccess.Read, FileShare.None, IntPtr.Zero, FileMode.Open, FILE_FLAG_NO_BUFFERING, null); FileStream stream = new FileStream(handle, FileAccess.Read, true, 4096); Calling CreateFile() with the FILE_FLAG_NO_BUFFERING flag tells the file system to bypass all software memory caching for the file. The ‘true’ value passed as the third argument to the FileStream constructor indicates that the stream should take ownership of the file handle, meaning that the file handle will automatically be closed when the stream is closed. After this hocus-pocus, the un-buffered file stream is read and written in the same way as any other. A: Response of Fix was almost right and better than PInvoke. But it has bugs and doesn't works... To open up File w/o caching one needs to do following: const FileOptions FileFlagNoBuffering = (FileOptions)0x20000000; FileStream file = new FileStream(fileName, fileMode, fileAccess, fileShare, blockSize, FileFlagNoBuffering | FileOptions.WriteThrough | fileOptions); Few rules: * *blockSize must be hard drive cluster size aligned (4096 most of the time) *file position change must be cluster size aligned *you can't read/write less than blockSize or block not aligned to it's size And don't forget - there is also HDD Cache (which slower and smaller than OS cache) which you can't turn off by that (but sometimes FileOptions.WriteThrough helps for not caching writes). With those options you have no reason for flushing, but make sure you've properly tested that this approach won't slow things down in case your implementation of cache is slower. A: I found this article and it seems that this is a complicated program because you also have to flush other caches.
unknown
d9459
train
I don't have a direct answer to your question, other than to ask you why are you trying to do it this way. The best practice is to move your static files to S3 or ideally, CloudFront (or another non-AWS solution). Use django-storages-redux (https://github.com/jschneier/django-storages) to use static files from S3 for production. Google 'django s3 static' and you will find several blogs explaining the process. The documentation is here. A: collectstatic command would have collected all your static file to STATIC_ROOT which you had set as "/PATH/TO/myapp/static/static-only. So I suspect that you pointed your static files to the wrong directory in the config file. Try "/static/": "myapp/static/static-only"
unknown
d9460
train
You want to parse them into some kind of time-duration object. A simple way, looking at that data, would be to check wheter " or / occurs, if " parse as seconds, / parse as fraction of seconds. I don't really understand what else you could mean. For an example you'd need to specify a language--also, there might be a parser out there already. A: Shutter speed is encoded in the EXIF metadata as an SRATIONAL, 32-bits for the numerator and 32-bits for the denominator. Sample code that retrieves it, using System.Drawing: var bmp = new Bitmap(@"c:\temp\canon-ixus.jpg"); if (bmp.PropertyIdList.Contains(37377)) { byte[] spencoded = bmp.GetPropertyItem(37377).Value; int numerator = BitConverter.ToInt32(spencoded, 0); int denominator = BitConverter.ToInt32(spencoded, 4); Console.WriteLine("Shutter speed = {0}/{1}", numerator, denominator); } Output: Shutter speed = 553859/65536, sample image retrieved here. A: It seems there are three types of string you will encounter: * *String with double quotes " for seconds *String with leading 1/ *String with no special characters I propose you simply test for these conditions and parse the value accordingly using floats: string[] InputSpeeds = new[] { "279\"", "30\"", "5\"", "3.2\"", "1.6\"", "1.3\"", "1\"", "1/1.3", "1/1.6", "1/2", "1/2.5", "1/3", "1/4", "1/5", "1/8", "1/13", "1/8000", "1/16000" }; List<float> OutputSpeeds = new List<float>(); foreach (string s in InputSpeeds) { float ConvertedSpeed; if (s.Contains("\"")) { float.TryParse(s.Replace("\"", String.Empty), out ConvertedSpeed); OutputSpeeds.Add(ConvertedSpeed); } else if (s.Contains("1/")) { float.TryParse(s.Remove(0, 2), out ConvertedSpeed); if (ConvertedSpeed == 0) { OutputSpeeds.Add(0F); } else { OutputSpeeds.Add(1 / ConvertedSpeed); } } else { float.TryParse(s, out ConvertedSpeed); OutputSpeeds.Add(ConvertedSpeed); } } If you want TimeSpans simply change the List<float> to List<TimeSpan> and instead of adding the float to the list, use TimeSpan.FromSeconds(ConvertedSpeed);
unknown
d9461
train
Electron has it's own embedded version of Node that's distinct from whatever Node version you have installed on your system. atom -v displays Node version in Electron, while apm -v probably just displays the Node version you've installed. This is why native Node modules have to be rebuilt to target the specific version of Electron they're used in.
unknown
d9462
train
Where $1 is id and passed via params. SQL does not allow to parametrize object names like column names. In most cases you get a syntax error right away if you try this kind of nonsense. Unfortunately, the ORDER BY clause does not necessarily expect a column name, but allows expressions including a constant (typed) value (which can be parameterized). If you pass 'id' to this prepared query, this is what happens: SELECT * FROM transactions ORDER BY 'id'::text DESC LIMIT 100; ORDER BY <constant value> is just noise and has no effect on the result. Turn on the server logs to check what the database actually receives. To parameterize column names like you seem to have in mind, you need dynamic SQL, i.e. first concatenate the query string and then execute it.
unknown
d9463
train
Certainly. The company I work for has done this in the past. If you know you might want to do this in the future, in your first version store a flag to NSUserDefaults indicating that the user has had the paid version. Then, on your In-App version check this flag and provide the content immediately. If you already have a version released, you may have to look for something that you are already storing, e.g. the user has a highscore greater than zero to indicate that the user has already purchased the app. (There will be a small number of users that may have downloaded the app but not opened it and these users may be charged twice). A: Yeah, it is. Before you Update your app with FREE version, you add all users that have paid for it serial number "PAID"(or something), and everything else is just conditional statements(if-else). Congrats!
unknown
d9464
train
You could try * *Deactivating any antivirus or firewall; *Check ports in use by netstat command *Changing play.bat debug port (at play's folder root) and save it Hope it helps
unknown
d9465
train
First there should be no declaration of unsigned visible due to conflicts between packages std_logic_arith and numeric_std. Use one or the other (numeric_std is part of the VHDL standard). Second the element type of VTIN is std_logic or std_ulogic depending on the VHDL revision which isn't compatible with the array type/subtype std_logic_vector. That means type conversion isn't legal. Next a concurrent signal assignment is elaborated into a process which implies a driver for the longest static prefix (here cont). Having VTIN'LENGTH processes with generate 'X's, the values will be resolved, the driver outputs are shorted. Instead of a generate statement use a process with a variable used to count '1's in a sequential loop statement with a for iteration scheme. The variable is used because the value of signal cont isn't updated until the process suspends. You assign the variable value to cont after the loop statement. After the process suspends, the value of cont will be available to use in the assignment to VTOUT. std_logic_arith can added a std_logic value to a std_logic_vector as can numeric_std in -2008 (otherwise unsigned(""& VTIN(i)) converts std_logic to unsigned. You could also implement a subprogram. library IEEE; use IEEE.STD_LOGIC_1164.ALL; -- use ieee.std_logic_arith.all; use IEEE.NUMERIC_STD.ALL; entity proj2_1 is GENERIC (N: INTEGER := 8); -- SIZE OF THE VECTOR Port ( VTIN : in STD_LOGIC_VECTOR (N-1 downto 0); VTOUT : out STD_LOGIC_VECTOR (N-1 downto 0); cont: buffer unsigned (N-1 downto 0) ); end entity proj2_1; architecture behavioral of proj2_1 is begin -- gen: FOR i IN VTIN' RANGE GENERATE -- BEGIN -- cont <= cont + ( unsigned (VTIN(i))); -- END GENERATE; SEQUENTIAL_LOOP_NOT_GENERATE_STATEMENT: process (VTIN) variable ones: unsigned(VTOUT'RANGE); begin ones := (others => '0'); -- zero for i in VTIN'RANGE loop ones := ones + unsigned'("" & VTIN(i)); end loop; VTOUT <= std_logic_vector (cont + ones); end process; end architecture behavioral; A generate statement is a concurrent statement which elaborates to a block statement for every value of the generate parameter containing the concurrent statement which has a process statement equivalent. A process statement has a driver for each signal assigned in it's sequence of statements. One driver versus lots of drivers. With package numeric std you could also declare the variable (here ones) as an integer (natural). numeric_std supports the addition of natural range integers to unsigned values. Notice there's nothing that defines an initial value for port cont which has a mode of buffer, essentially an output that be read internally. The default initial value will be (others => 'U')from the left most value of the enumerated type std_ulogic. Either the original intent is wrong (count all the 1's from a std_logic_vector" or more likely you actually one the population count of '1's in VTIN. The latter requires a change: architecture behavioral of proj2_1 is begin SEQUENTIAL_LOOP_NOT_GENERATE_STATEMENT: process (VTIN) variable ones: unsigned(VTOUT'RANGE); begin ones := (others => '0'); -- zero for i in VTIN'RANGE loop ones := ones + unsigned'("" & VTIN(i)); end loop; -- VTOUT <= std_logic_vector (cont + ones); VTOUT <= std_logic_vector (ones); cont <= ones; end process; end architecture behavioral; that doesn't reflect the original code but doesn't accumulate across new values of VTIN and is synthesis eligible. The integer variable version of the population count of '1's could look like architecture integer_variable of proj2_1 is begin SEQUENTIAL_LOOP_NOT_GENERATE_STATEMENT: process (VTIN) variable ones: natural; begin ones := 0; for i in VTIN'RANGE loop if TO_BIT(VTIN(i)) = '1' then ones := ones + 1; end if; end loop; VTOUT <= std_logic_vector (to_unsigned(ones, VTOUT'length)); cont <= to_unsigned(ones, VTOUT'length); -- and both outputs don't make sense end process; end architecture integer_variable; where adding an integer value doesn't propagate meta values from VTIN during addition.
unknown
d9466
train
Well one can explain if there is a difference and i don't think there is. Look at the code below all that CopyFromLocal does is extends Put with no additional functionality. public static class CopyFromLocal extends Put { public static final String NAME = "copyFromLocal"; public static final String USAGE = Put.USAGE; public static final String DESCRIPTION = "Identical to the -put command."; } https://github.com/apache/hadoop/blob/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/shell/CopyCommands.java
unknown
d9467
train
yes. for a new project, you have to manually set up on the cloud build page by "Connect repository". then you can use gcp cli comamnd set the trigger, gcloud beta builds triggers create github
unknown
d9468
train
I am assuming that each foid represents a gallery: SELECT foid, uid, date, (CASE WHEN pic1 IS NULL THEN 0 ELSE 1 END + CASE WHEN pic2 IS NULL THEN 0 ELSE 1 END + CASE WHEN pic3 IS NULL THEN 0 ELSE 1 END ) AS pic_count FROM foto WHERE uid = $id ORDER BY foid DESC Incidentally, this isn't a particularly sensible way to structure your schema. You really should split the pics out as a separate table: foto: foid | uid | date ----------------------- 104 | 5 | 2010-01-01 105 | 14 | 2009-04-08 106 | 48 | 2010-08-09 pic: foid | pic ------------ 104 | 1.jpg 104 | 2.jpg 104 | 3.jpg 105 | 8.jpg 106 | x.jpg 106 | y.jpg Now, galleries can have more than three pics and querying is simpler: SELECT foid, uid, date, COUNT(*) FROM foto JOIN pic USING (foid) WHERE uid = $id ORDER BY foid DESC GROUP BY foid, uid, date EDIT: You can split an existing database thus (just guessing at stuff like column types): CREATE TABLE picture (foid INT, pic VARCHAR(255)); INSERT INTO picture (foid, pic) SELECT foid, pic1 as pic FROM foto WHERE pic IS NOT NULL UNION SELECT foid, pic2 as pic FROM foto WHERE pic IS NOT NULL UNION SELECT foid, pic3 as pic FROM foto WHERE pic IS NOT NULL ; ALTER TABLE foto DROP COLUMN pic1, DROP COLUMN pic2, DROP COLUMN pic3 ; Obviously, one should exercise considerable care when dropping columns, and make a backup before you start!
unknown
d9469
train
It seems for me as a bug in Internet Explorer. In the official Document Object Model HTML standard I could found the following description about the namedItem method intensively used by jqGrid: This method retrieves a Node using a name. With [HTML 4.01] documents, it first searches for a Node with a matching id attribute. If it doesn't find one, it then searches for a Node with a matching name attribute, but only on those elements that are allowed a name attribute. With [XHTML 1.0] documents, this method only searches for Nodes with a matching id attribute. This method is case insensitive in HTML documents and case sensitive in XHTML documents. So the namedItem method should works case sensitive in XHTML documents. On the other side like you can test in the demo, which use only pure DOM without jQuery or jqGrid, the method work case insensitive in Internet Explorer. The HTML code of the demo is following: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>http://stackoverflow.com/questions/7230179/how-to-allow-to-use-case-sensitive-row-ids-in-jqgrid/7236985#7236985</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <table id="t"> <tbody> <tr id="x"><td>1</td></tr> <tr id="X"><td>2</td></tr> </tbody> </table> <script type="text/javascript"> 'use strict'; var mytable = document.getElementById("t"), tr1 = mytable.rows.namedItem("x"), tr2 = mytable.rows.namedItem("X"), tr3 = document.getElementById("x"), tr4 = document.getElementById("X"); alert("getElementById works " + (tr3.id === tr4.id ? "case insensitive (BUG!!!)": "case sensitive") + "\nnamedItem works " + (tr1.id === tr2.id ? "case insensitive (BUG!!!)": "case sensitive")); </script> </body> </html> The Internet Explorer shows that namedItem("X") returns the row with the id="x" instead of the row having id="X". The same bug not exist in all other (non-Microsoft) web browsers where I tested it. I can't suggest you currently no workaround. You should just organize you program so that you will not use case sensitive ids inside of tables (and with jqGrid). UPDATED: Just a little more additional information. I made an official support request to Microsoft about the described subject. Microsoft confirmed that it was a bug in Internet Explorer, but the bug will be not fixed in the current Internet Explorer versions, but it will be probably fixed in IE10. As a workaround :-) it was suggested not to use ids which distinguish only in case. So just not use the ids which can reproduce the bug. So we have at the end results as I supposed before in my previously comments. Nevertheless, because the response confirmed that it was a bug, the request to Microsoft was for free for me (:-)).
unknown
d9470
train
You can use this plugin to get a list of all fonts of your device: cordova-plugin-fonts Then you can show to the user a list, let them select one and after that you change the css of your site by javascript. I'm not sure, but it could be, that you have to rerender the page after changing the font. A: Seems something you could easily do with javascript/css. Just ship your fonts in the app, to make sure they are available on any platform, and add a listener to your select which changes a css class to the body. This is the html code if you are using jQuery or Zepto syntax. <select name="changeFont" id="font-selector" onchange='$("body").attr("data-font", $("#font-selector").val())'> <option value="default">Default</option> <option value="arial">Arial</option> <option value="comic-sans">Comic Sans</option> </select> then in css .mytext { font-family: helvetica, sans-serif; } [data-font=arial] .mytext { font-family: arial, sans-serif; } [data-font=comic-sans] .mytext { font-family: "comic sans", sans-serif; } For this to work, just make sure that you have correctly added your fonts. To make this right you could use FontSquirrel webfont generator to convert any font to a web font and generate the needed css for you. I should add that I did not test this, so let me know if you find it's not working. Or, if your app is designed to work only when the user has internet connection then there's an even quicker way to add a lot of fonts. There's a jQuery plugin that will do exactly that.
unknown
d9471
train
Android KTX now has an extension function for converting drawable to bitmap val bitmap = ContextCompat.getDrawable(context, R.drawable.ic_user_location_pin)?.toBitmap() if (bitmap != null) { markerOptions.icon(BitmapDescriptorFactory.fromBitmap(bitmap)) } A: public static Bitmap convertDrawableResToBitmap(@DrawableRes int drawableId, Integer width, Integer height) { Drawable d = getResources().getDrawable(drawableId); if (d instanceof BitmapDrawable) { return ((BitmapDrawable) d).getBitmap(); } if (d instanceof GradientDrawable) { GradientDrawable g = (GradientDrawable) d; int w = d.getIntrinsicWidth() > 0 ? d.getIntrinsicWidth() : width; int h = d.getIntrinsicHeight() > 0 ? d.getIntrinsicHeight() : height; Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); g.setBounds(0, 0, w, h); g.setStroke(1, Color.BLACK); g.setFilterBitmap(true); g.draw(canvas); return bitmap; } Bitmap bit = BitmapFactory.decodeResource(getResources(), drawableId); return bit.copy(Bitmap.Config.ARGB_8888, true); } //------------------------ Bitmap b = convertDrawableResToBitmap(R.drawable.myDraw , 50, 50); A: Since you want to load a Drawable, not a Bitmap, use this: Drawable d = getResources().getDrawable(R.drawable.your_drawable, your_app_theme); To turn it into a Bitmap: public static Bitmap drawableToBitmap (Drawable drawable) { if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable)drawable).getBitmap(); } Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } Taken from: How to convert a Drawable to a Bitmap? A: it is a drawable, not a bitmap. You should use getDrawable instead A: You may have put .xml into directory:.../drawable-24, and try to put it into .../drawable instead. it works for me, hope this can help someone.
unknown
d9472
train
There are multiple ways to solve it using Gauava or lambda expressions. Hope this implementation solve your problem. package com; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class TestDemo { public static void main(String[] args) { List < HockeyPlayer > players = new ArrayList < HockeyPlayer > (); HockeyPlayer obj1 = new HockeyPlayer(); obj1.goalsScored = 22; players.add(obj1); HockeyPlayer obj2 = new HockeyPlayer(); obj2.goalsScored = 11; players.add(obj2); HockeyPlayer obj3 = new HockeyPlayer(); obj3.goalsScored = 111; players.add(obj3); HockeyPlayer obj4 = new HockeyPlayer(); obj4.goalsScored = 3; players.add(obj4); Collections.sort(players, new Comparator < HockeyPlayer > () { @Override public int compare(HockeyPlayer player1, HockeyPlayer player2) { return player1.goalsScored - player2.goalsScored; } }); for (int i = 0; i < players.size(); i++) { System.out.println(players.get(i).goalsScored); } HockeyPlayer array[] = new HockeyPlayer[players.size()]; players.toArray(array); // contains reference for (int i = 0; i < array.length; i++) { System.out.println(array[i].goalsScored); } } } class HockeyPlayer { public int goalsScored; }
unknown
d9473
train
Add unique to phone number column in sqlite database and you will not get same contact twice. @Override public void onCreate(SQLiteDatabase db) { String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_PH_NO + " TEXT UNIQUE," + KEY_IMAGE + " TEXT" + ")"; db.execSQL(CREATE_CONTACTS_TABLE); }
unknown
d9474
train
Could fit your need: As IDs must be unique on context page, that selector is better $("#tabs > ul").animate({ marginLeft: '+=' + marginleft }, { step: function (fx) { if(someCondition) $(this).stop(true); } }, '10000', 'swing'); Or for more global condition, use @billyonecan's answer A: If I understand the question correctly, you can use the conditional operator: $($("#tabs > ul"), $(this).parent()).animate({ marginLeft: (condition ? 'value if true' : 'value if false') }, '10000', 'swing');
unknown
d9475
train
You are looking for translation.override context manager: language = user.get_language() with translation.override(language): # Translate your message here.
unknown
d9476
train
make sure your NSURLConnection's delegate is set and responds to the connection:didFailWithError: method. A connection always calls either this method or connectionDidFinishLoading: upon connection completion. your timeout is received in connection:didFailWithError: so here you can display that connection has timed out
unknown
d9477
train
let(:post) {create(:post)} # ... post :create let is a fancy way of defining a method on the current RSpec example. post is now a method that accepts 0 arguments, thus the message wrong number of arguments (2 for 0). Try naming your Post object something else.
unknown
d9478
train
It can be easily done using jQuery. Have two divs, one at the top and another at the bottom. Now, when you have a large screen size, give the html of the navbar to the above div and to the bottom one if the screen size is small. Here's what it would look like: if (screenSize > 1280px) $(#topnav).html('Your navbar HTML here'); else $(#bottomnav).html('Your navbar HTML here'); where topnav and bottomnav are the two divs. The only thing you now need to figure out is how to get the screen size. Here's how it can be done: $(window).resize(function(){ var screenSize = $(window).width(); }); Now just insert your HTML in there and it should work. A: You have to use 'pull' to put your element in the left and top and 'push' to put it on the right and bottom. So you're using these classes in the wrong way. invert the two and it will work !
unknown
d9479
train
If the target application is another java application, then you should be able to get a reference to the component hierarchy and traverse it until you find the text field & label in question. Assuming it's not a java application, then I don't believe it's possible to do this - at least directly. Robot just provides mouse / keyboard input, but you could use it combined with other classes in the toolkit to at least partially solve your problem. Use the Robot methods keyPress & keyRelease to input CTRL-A. Then CTRL-C. Once the text is in the clipboard, you could read it using Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor) You might be able to use the same approach for a text label, assuming it is selectable. This question is talking about using java.awt.Robot to alter text in another program (MS excel), but it might provide you some additional ideas for tackling the problem: How can I select text in another application with java.awt.robot (example: shift+home)
unknown
d9480
train
Note: np.nan is float type and pd.NaT is of datetime null type. Problem with your code is that null values have been filled with np.nan I got the same error while doing the following thing.... df['date'] = np.where((df['date2'].notnull()) & (df['date3'].notnull()),df['date2']-df['date3'],np.nan) problem here is date difference of date2 and date3 is of datetime type but the type of "np.nan" is float/int. For saving it to df['date'], datatype should be same. In datetime type the null date is "pd.NaT". So when I replace the above code with below. It worked for me. You can try the same.. df['date'] = np.where((df['date2'].notnull()) & (df['date3'].notnull()),df['date2']-df['date3'],pd.NaT) So you can replace the nulls present in your data with pd.NaT instead of np.nan you can use below thing as well... df['date'].replace(np.NaN, pd.NaT) or df['date'].fillna(pd.NaT) Hope it is helpful for you :)
unknown
d9481
train
I think it will work try this : \b([A-Z]){2} result SU, SU, FA, AC
unknown
d9482
train
You can do black box testing by verifying the exit code and the output of the program to the standard output stream and standard error stream. You can do white box testing by keeping a reference to your application and asserting on the state of your application after giving it various command line inputs. For example: MyApp app = new MyApp(); StringWriter sw = new StringWriter(); CommandLine cmd = new CommandLine(app); cmd.setOut(new PrintWriter(sw)); // black box testing int exitCode = cmd.execute("-x", "-y=123"); assertEquals(0, exitCode); assertEquals("Your output is abc...", sw.toString()); // white box testing assertEquals("expectedValue1", app.getState1()); assertEquals("expectedValue2", app.getState2()); Update: the picocli user manual now has a separate section about Testing.
unknown
d9483
train
Ok, nobody answered it, and I figured it out. There are two "practical" solutions, first one is using the Quaternions. You can define a 3d rectangle as a view and then rotate it using quaternions. After that you can sweep on the resulting rectangle, and use the reverse transforms to get the map coordinates. The other solution, which seems faster to me, is using Euler's rotation matrices. Just pay attention to use ArcTan2 instead of ArcTan function, because you need 2*PI coverage. That's all I wanted!
unknown
d9484
train
You can use the Firewall > Traffic Shaper > Wizards option to do this. I don't recommend dedicating even bandwidth to each user since they don't use the connection at the same time constantly wherein if a user is idle then you are wasting bandwidth at their idle time. Managing priorities on protocols and applications while penalizing abusers is enough.
unknown
d9485
train
Yes, this is normal. If you want to insert with a specific ID number you have to specify that number on your insert statement. The idea of auto increment is for the value to continually increase. A: This is normal, though for some database engines you might receive 2, but usually it will be 6. In MSSQL it is possible to specify a value for an autoinc field with particular setting. Not sure what it is in mysql. A: That's the expected behavior. Autoincrement primary keys are designed to be unique and continually increasing - so they are not assigned again. If you TRUNCATE a table the autoincrement value is being reset while it stays as it is if you delete all rows with an DELETE query - that's a subtle but sometimes important difference. As webdestroya suggested, the only possibility to reuse old and deleted autoincrement values is to set them specifically on the INSERT statement.
unknown
d9486
train
Nice way to do this is to compare URL Host which can be done using the following approach func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { let exceptedHosts: [String] = [ "facebook.com", "m.facebook.com" ] if let host = navigationAction.request.url?.host { if exceptedHosts.contains(host) { decisionHandler(.cancel) return } } decisionHandler(.allow) } This will prevent any url with facebook.com or m.facebook.com from being opened, add any hosts to the array to except them from being opened. Please don't forget to set delegate in viewDidLoad webview.navigationDelegate = self
unknown
d9487
train
Please post your layout XML R.layout.fragment_sixth. Probably you're referring to a wrong id, which causes de NullPointerException. To get each "Breakfast", "Lunch" and "Dinner" separately, you can simply iterate through the last three <div> tags inside the HTML element with id MainContent_divDailySpecials (I did find that id looking at the website DOM structure through Chrome Developer Tools inspector). So, as a start, simply grab that element with Document document = Jsoup.connect(url).get(); Element parentDiv = document.getElementById("MainContent_divDailySpecials"); and from there on you can iterate backwards to get the last three children of that div. (Please keep in mind that if, in any point in time, the structure of that page changes your code will break). A: Looking at the error log you attached .. java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at com.lamdevs.tritonbites.fragments.SixthFragment$JSOUP.onPostExecute(SixthFragment.java:82) It talks about a NullPointerException on a TextView in SixthFragment Line 82 i.e. textview.setText(MENU); The textview is initialized (textview = (TextView) rootView.findViewById(R.id.textView10);) which looks okay. So, make sure you have a TextView with id textView10 in your layout fragment_sixth.
unknown
d9488
train
If you want a factory to not tell you when it builds a new protocol, you can just set its noisy to False. See http://twistedmatrix.com/trac/browser/tags/releases/twisted-11.0.0/twisted/internet/protocol.py#L35 -- I am not sure if this is what you were asking.
unknown
d9489
train
I found the problem... Excel exported the text with Windows encoding, so it looked correct even in TextMate on my mac. When I reopen with UTF8 encoding the problem was visible in the translations file. To resolve I used EditPadPro on a PC to convert to UTF8. Phew. A: Maybe you could try adding this inside your <head> tag? <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> A: I use Coda but I think textmate has to offer some option like Text->Encoding->Unicode UTF-8, activate it and then your file will be encoded properly and then save it. Anyway if you are going to put some forms and you are not sure the people is using the correct encoding mode you'll have the same problem. Use something like this: <?php $not_utf8 = "An invalid string"; //Put here the bad text for testing $not_utf8 = mb_convert_encoding($not_utf8, 'UTF-8', mb_detect_encoding($not_utf8)); echo htmlspecialchars($not_utf8, ENT_QUOTES, 'UTF-8'); //The output should be ok, see the source code generated and search for the correct html entities for these special chars ?> Hope this help you! Luis. A: The page encoding is UTF8, and I've added: Probably not. Make sure that the php file is actually saved with utf-8 encoding.
unknown
d9490
train
select v1.Vendor_ID, v1.Descr, v1.source, v1.Name, v1.Parent_Vendor_ID, case when v2.Vendor_ID is null then 'NO' else 'YES' end as Parent_Vendor_ID_Exist from vendor v1 left join vendor v2 on v1.Parent_Vendor_ID = v2.Vendor_ID A: SELECT v1.Vendor_ID , v1.Descr , v1.source , v1.Name , v1.Parent_Vendor_ID , nvl2(v2.vendor_id,'Yes','No') as parent_exist FROM VENDOR v1 LEFT OUTER JOIN vendor v2 ON (v1.parent_vandor_id = v2.vendor_id); A: Try this.. SELECT Vendor_ID, Descr, source, Name, Parent_Vendor_ID, CASE WHEN EXISTS( SELECT Vendor_ID FROM VENDOR v2 WHERE v1.Parent_Vendor_ID = v2.Vendor_ID) THEN 'Yes' ELSE 'No' END as "Parent_Vendor_ID Exist" FROM VENDOR v1; let me know if this works.
unknown
d9491
train
A large number of classes is not going to affect the performance of the application. Some good practices in Android, however, include placing values like integers, item IDs, and request codes into a Resources xml file. You will also see a lot of Callback classes as inner interfaces of the Object they relate to: public class MyObject { private Callback callback; private Object returnObject; public void setCallback(Callback callback) { this.callback = callback; } public void doSomething() { //do something - could be an anync task or other that assigns returnObject callback.invoke(returnObject); } public interface Callback { public void invoke(Object obj); } } Then you can use this as follows: MyObject obj = new MyObject(); obj.setCallback(new MyObject.Callback() { @Override public void invoke(Object obj) { Log.i("Callback", obj.toString()); } }); obj.doSomething();
unknown
d9492
train
I would find the bounding box of hole and then inspect the sides. find the one that is not linear but curved instead and set that as circle border. Then fit circle to that side only. For more info see: * *fitting ellipses *Finding holes in 2d point sets A: If you can scale the coordinates in order to draw the point into an image, here is a solution: * *Draw the points into an image *Compute the distance map using all the points as a source point. *Then, each pixel will contain the distance to the closets point. So the pixel with the highest value will be the center of the largest circle, and the pixel value will be the circle radius. *Find the closest points to the circle center. *Find the circle passing by all theses points (Hough?). The solution might not be unique.
unknown
d9493
train
The T in WrapperImpl<T> can be constrained on any subtype of Base, not just Base itself. Functionality in put should be able to safely access v.derived_property if T : Base is simply changed to a T : Derived. This is the source of trouble when an OtherDerived is passed to put after the (Wrapper<Base>)derived_wrapper cast, in trying to access the nonexistent derived_property.
unknown
d9494
train
I believe the only thing you can do in this case is to use the users/lookup or users/show endpoints to check whether those user IDs return a Not Found error (or similar) in order to filter them out from your result set. Note that the Twitter Developer Policy and Agreement explicitly states that if content has been removed from Twitter (if e.g. a user is deleted or suspended) you cannot display that it in app, or store that data, and must take steps to remove it from your system as soon as possible.
unknown
d9495
train
There isn't really, they're not 100% correct/valid usage in HTML4 of course....but they don't cause problems either, so they're still a great way to solve the "I need an attribute for this" problem. If it helps, I've used these while supporting IE6 and have had zero issues thus far, and I can't recall a single SO question reporting any either. A: Internet Explorer and Microsoft has added several custom attributes that are not valid HTML4. Browsers don't check the element attributes against a specification, you can name an attribute roryscoolinfo="hello" if you like (though you shouldn't). The Dojo Toolkit adds its custom dojo* attributes. It's fine to use data- today, with a HTML5 doctype.
unknown
d9496
train
this might help $obj = new SimpleXMLElement($xml); $rtn = array(); $cnt = 0; foreach($obj->xpath('///OSes/*/*') as $rec) { foreach ($rec as $rec_obj) { if (!isset($rtn[$cnt])) { $rtn[$cnt] = array(); } foreach ($rec_obj as $name=>$val) { $rtn[$cnt][(string)$name] = (string)$val; } ++$cnt; } } A: By modifying the xpath as others suggested as well, I came to this conclusion. It works with one helper function to re-format each xpath result node and uses array_reduce to iterate over the result. It then returns the converted result (Demo): $xml = new SimpleXMLElement($xmlstr); $elements = array_reduce( $xml->xpath('//OSes/*/*'), function($v, $w) { $w = array_values((array) $w); // convert result to array foreach($w as &$d) $d = (array) $d; // convert inner elements to array return array_merge($v, $w); // merge with existing }, array() // empty elements at start ); Output: Array ( [0] => Array ( [id] => centos5-32 [name] => CentOS 5 - 32 bit [version] => 5 [architecture] => 32 [os] => centos ) [1] => Array ( [id] => centos5-64 [name] => CentOS 5 - 64 bit [version] => 5 [architecture] => 64 [os] => centos ) [2] => Array ( [id] => centos6-32 [name] => CentOS 6 - 32 bit [version] => 6 [architecture] => 32 [os] => centos ) [3] => Array ( [id] => centos6-64 [name] => CentOS 6 - 64 bit [version] => 6 [architecture] => 64 [os] => centos ) [4] => Array ( [id] => ubuntu10-32 [name] => Ubuntu 10 - 32 bit [version] => 10 [architecture] => 32 [os] => ubuntu ) [5] => Array ( [id] => ubuntu10-64 [name] => Ubuntu 10 - 64 bit [version] => 10 [architecture] => 64 [os] => ubuntu ) ) I also opted for converting the original xpath result into an array of two levels, each time within the current level a key already exists, move the current entry to a new entry (Demo): try { $xml = new SimpleXMLElement($xmlstr); $elements = array(); $curr = NULL; foreach($xml->xpath('//id | //name | //version | //architecture | //os') as $record) { $key = $record->getName(); $value = (string) $record; if (!$curr || array_key_exists($key, $curr)) { unset($curr); $curr = array(); $elements[] = &$curr; } $curr[$key] = $value; } unset($curr); } catch(Exception $e) { echo $e->getMessage(); } Result is like this then: Array ( [0] => Array ( [id] => centos5-32 [name] => CentOS 5 - 32 bit [version] => 5 [architecture] => 32 [os] => centos ) [1] => Array ( [id] => centos5-64 [name] => CentOS 5 - 64 bit [version] => 5 [architecture] => 64 [os] => centos ) [2] => Array ( [id] => centos6-32 [name] => CentOS 6 - 32 bit [version] => 6 [architecture] => 32 [os] => centos ) [3] => Array ( [id] => centos6-64 [name] => CentOS 6 - 64 bit [version] => 6 [architecture] => 64 [os] => centos ) [4] => Array ( [id] => ubuntu10-32 [name] => Ubuntu 10 - 32 bit [version] => 10 [architecture] => 32 [os] => ubuntu ) [5] => Array ( [id] => ubuntu10-64 [name] => Ubuntu 10 - 64 bit [version] => 10 [architecture] => 64 [os] => ubuntu ) ) A: Try this: // flatten: function arrayval1($any) { return array_values((array)$any); } function arrayval2($any) { return (array)$any; } // xml objects with xml objects: $oses = $xml->xpath('//OSes/*/*'); // an array of xml objects: $oses = array_map('arrayval1', $oses); // merge to a flat array: $oses = call_user_func_array('array_merge', $oses); // xml objects -> arrays $oses = array_map('arrayval2', $oses); print_r($oses); My result: Array ( [0] => Array ( [id] => centos5-32 [name] => CentOS 5 - 32 bit [version] => 5 [architecture] => 32 [os] => centos ) [1] => Array ( [id] => centos5-64 [name] => CentOS 5 - 64 bit [version] => 5 [architecture] => 64 [os] => centos ) [2] => Array ( [id] => centos6-32 [name] => CentOS 6 - 32 bit [version] => 6 [architecture] => 32 [os] => centos ) [3] => Array ( [id] => centos6-64 [name] => CentOS 6 - 64 bit [version] => 6 [architecture] => 64 [os] => centos ) [4] => Array ( [id] => ubuntu10-32 [name] => Ubuntu 10 - 32 bit [version] => 10 [architecture] => 32 [os] => ubuntu ) [5] => Array ( [id] => ubuntu10-64 [name] => Ubuntu 10 - 64 bit [version] => 10 [architecture] => 64 [os] => ubuntu ) ) If you're using PHP >= 5.3 (ofcourse you are, why whouldn't you) you can omit the nasty tmp function definitions and use cool anonymous functions for the mapping: // an array of xml objects: $oses = array_map(function($os) { return array_values((array)$os); }, $oses);
unknown
d9497
train
Try removing the " before you echo the id and adding it at the end: <img src="inventory_images/<?php echo $id; ?>" /> (otherwise your image link is inventory_images/"54 for example)
unknown
d9498
train
I would say the best way to do it would be to cut your dependencies so that they can reference as external jars. This way when you make potentially breaking changes you don't necessarily have to fix the affected areas straight away. Since they depend on a previously built jar it allows you to properly isolate your coding. If you use something like Maven to manage your dependencies you will also benefit from the ability to more easily keep track of the different versions of your jars. A: If the subprojects are sufficiently autonomous, I would advise setting them up as separate maven projects with separate VCS repos. This will give you the modularity you need paired with a working dependency management.
unknown
d9499
train
Finaly I used a function score with a script score using a 1 - (1/x) function in script_score GET _search { "query": { "function_score": { "query": { "match": { "postgresql.log.message": "alter" } }, "script_score" : { "script" : { "params": { "max_score": 5 }, "source": "params.max_score * (1 - 1 / _score)" } } } } } This way, I will have a score between 0 and nearly 5 (max_score). You can try it here with the word alter (score 3.9150627) or alter table pgbench_branches add primary key (bid) (score 4.8539715). You can adapt the 1 - (1/x) function to approach the asymptote faster. A: have u tried using Function score query ? Here is the link for the same https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html
unknown
d9500
train
I don't have touch screen to test but maybe this will work: int count; private void InkCanvas_PointerEntered(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e) { count++; } private void InkCanvas_PointerExited(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e) { count--; } If it doesn't help. Try to use PinterPressed and PointerReleased. You may grab point Id from event args and handle them.
unknown