_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d17401
val
You can just call the DOM (not jQuery) form.submit() method, like this: $("form")[0].submit(); Or if it's by ID: document.getElementById('myForm').submit(); //or $("#myForm").get(0).submit(); This bypasses the jQuery event handlers and prevents them from running, instead it directly submits the <form>.
unknown
d17402
val
You should use the key label instead of name label: '' + keys[n] + '', value: '' + dtData[keys[n]].length + '',
unknown
d17403
val
what about this approach. not sure if {' '} in you code is necessary. this aligns with space between and looks better for the ui instead of giving a random space to separate the items. and also apply the rest oft he styles to your liking, for example make font bold, etc. <FlatList data={transaction_details} ItemSeparatorComponent={this.FlatListItemSeparator} renderItem={({ item }) => { return ( <View> <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}> <Text>{item.narration}</Text> <Text>{item.amount}</Text> </View> <Text>{item.date}</Text> </View> ) }} keyExtractor={(item) => item.id.toString()} />
unknown
d17404
val
Since you tagged your question with MATLAB... >> x = [1,2,3,4,5]; % define array >> cumsum(x, 'reverse') % cumulative sum in reverse order ans = 15 14 12 9 5 A: int[] arr = {1, 2, 3, 4, 5}; for (int i = 0; i < arr.length; i++) { int sum = 0; for (int j = i; j < arr.length; j++) { sum += arr[j]; } System.out.println(sum); } Something like this?
unknown
d17405
val
First element Second Element Well its true that you are getting similar elements for that given xpath but you also have to go through their siblings/parents etc for different scenarios. Here is the xpath I tried that identified the individual elements that you were looking for, are depicted above. //div[@class='iradio_square-green']/input[@id='trip_0_date_0_flight_0_fare_0']/following-sibling::ins For others radio buttons you just have to change the flight number. Hope this helps... :)
unknown
d17406
val
The primary reason for its existence is the introduction of anonymous types in C#. You can construct types on the fly that don't have a name. How would you specify their name? The answer: You can't. You just tell the compiler to infer them for you: var user = users.Where(u=> u.Name == "Mehrdad") .Select(u => new { u.Name, u.Password }); A: It's mostly present for LINQ, when you may use an anonymous type as the projection: var query = from person in employees where person.Salary > 10000m select new { FullName=person.Name, person.Department }; Here the type of query can't be declared explicitly, because the anonymous type has no name. (In real world cases the anonymous type often includes values from multiple objects, so there's no one named class which contains all the properties.) It's also practically useful when you're initializing a variable using a potentially long type name (usually due to generics) and just calling a constructor - it increases the information density (reduces redundancy). There's the same amount of information in these two lines: List<Func<string, int>> functions = new List<Func<string, int>>(); var functions = new List<Function<string, int>>(); but the second one expresses it in a more compact way. Of course this can be abused, e.g. var nonObviousType = 999999999; but when it's obvious what the type's variable is, I believe it can significantly increase readability. A: It's a shorthand way of declaring a var. Although "int i = new int()" isn't too much to type, when you start getting to longer types, you end up with a lot of lines that look like: SomeReallyLong.TypeName.WithNameSpaces.AndEverything myVar = new SomeReallyLong.TypeName.WithNameSpaces.AndEverything(); It eventually occurred to someone that the compiler already knew what type you were declaring thanks to the information you were using to initialize the var, so it wouldn't be too much to ask to just have the compiler do the right thing here. A: * *Linq expressions don't return a predefined type, so you need a 'generic' variable declaration keyword to capture that and other places where anonymous types are used. *Used carefully, it can make refactoring easier by decoupling a method's return type from the variable that captures it. *Having to put the same name on the same line twice for the same statement is really kind of silly. It's a pain to type something like this: . ReallyLongTypeName<SomeOtherLongTypeName> MyVariable = new ReallyLongTypeName<SomeOtherLongTypeName>(); A: Here are a couple of advantages * *Less typing with no loss of functionality *Increases the type safety of your code. A foreach loop using an iteration variable which is typed to var will catch silently casts that are introduced with explicit types *Makes it so you don't have to write the same name twice in a variable declaration. *Some features, such as declaring a strongly typed anonymous type local variable, require the use of var Shameless self promotion. I wrote a blog entry on this subject awhile back that dived into when I thought the use of var was appropriate and contains relative information to this topic. * *http://beta.blogs.msdn.com/jaredpar/archive/2008/09/09/when-to-use-type-inference.aspx A: In short: * *minimize the need for typing the variable type twice *essential in supporting anonymous types, e.g. as returned by LINQ queries A: The real need for the var keyword was to support anonymous types in C# 3.0--which in turn were required to properly support LiNQ (Language Integrated Querying). Without using var you could never do something like this: var person = new { Name = "Peter", Age=4}; Which means that you couldn't execute execute the following linq query because you wouldn't know how to assign it to a variable: [var/sometype] dogsFixedQuery = from myDog in kennel select new {dogName = myDog.FirstName + " " + myDog.OwnerLastName, myDog.IsNeutered, dogLocation = kennel.Address}; The utility of anonymous types will be more apparent if you start to create more complex linq queries with multiple levels of returns and joins. The fact that you can use var in other ways to avoid typing out something like IEnumerable<Dictionary<List<string>,IOrderedCollection<DateTime>> myBadDesign = getBadDesignController().BadDesignResults("shoppingCart"); is just a side-effect/bonus in case you're a lazy typer =) There are cons for readability if you start calling vars in disparate locations but if you're using var for a strong type and the compiler can determine the type of your variable than any reader should be able to determine it as well.
unknown
d17407
val
To solve this problem you just need to create your segue from your viewController1 to your viewController2 and not from a button. This way you can trigger prepareForSegue programatically using the "performSegue" method that will call prepareForSegue anyway.
unknown
d17408
val
This isn't exactly an answer, but here's a discussion of other people who have run into the same thing: https://github.com/vuejs/vue-router/issues/2932 It doesn't sound like there is a resolution, but since it appears harmless, (except for the message in the console), I'm going to not worry about it at the moment.
unknown
d17409
val
The polygon2patch function certainly seems useful, but maybe for only drawing two rectangles, you could also use just two patch commands, and simply set the inner rectangle, i.e. the hole, to white foreground color, like so: outer = [0 0; 2 0; 2 1; 0 1]; inner = [0.4 0.2; 1.6 0.2; 1.6 0.8; 0.4 0.8]; patch(outer(:, 1), outer(:, 2), 'c'); patch(inner(:, 1), inner(:, 2), 'w'); axis equal; This will produce such an output: Hope that helps!
unknown
d17410
val
There is no infinite loop in your code above. It's quite possible that it is being called from an infinite loop. To find this, place a breakpoint in the method, continue a few times (to ensure you're in the loop rather than just the normal calls) and then look at the stack trace on the side. This should give you a pretty clear idea of where the looping is coming from. You are probably calling reloadData from within one of your datasource or delegate methods.
unknown
d17411
val
I think you need to provide the destination folder as a key and value, something like this(below) var upload = multer({ dest: 'uploads/' }) You can check out the full multer documentations here https://expressjs.com/en/resources/middleware/multer.html
unknown
d17412
val
This was all due to my dumb naming scheme... I named the module kernel... Which is obviously already in use by the kernel...... So don't do that...
unknown
d17413
val
You can make your constructor internal and expose your internals to your tests using InternalsVisibleTo: [assembly: InternalsVisibleTo("YourNamespace.YourTests")] See: https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx
unknown
d17414
val
By defaults an IDE will use a layout manager to position components on the frame. When you drag the panel you are manually setting the location of the panel and overriding the location determined by the layout manager. However, when you resize the frame the layout manager code is again executed and the panel is set back to its original position. You need to change your code so that the parent panel of the panel you drag uses a "null layout". However, when you do this you are now responsible for setting the size and location of the panel.
unknown
d17415
val
Try this $output .="<td ><strong><a href='users.php?username=" . $row['companyname']."'>". $row['companyname']."</a></strong></td>"; That should give you <a href='users.php?username=John'>John</a>
unknown
d17416
val
Since nobody has answered it I might as well post what worked for me. I was able to start the blog manually with npm start it was just the service ghost start that reported [OK] but didn't actually start it. First I was able to find the error in /var/log/nginx/errors.log 2016/02/08 21:18:27 [error] 601#0: *2086 connect() failed (111: Connection refused) while connecting to upstream, client: xx.xx.xx.xx, server: my-ghost-blog.com, request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:xxxx/favicon.ico", host: "mydomain.com", referrer: "http://example.com/path-to-post/" I had to recursively change the owner of /ghost directory like this: chown -R ghost:ghost ghost/* I executed it from /var/www thanks to @BrettDeWoody for his post
unknown
d17417
val
I think I've come up with a solution to your problem - it works in my environment but then I've had to guess how your code probably looks. public static class ViewPageExtensions { public static MvcHtmlString GetIdFor<TViewModel, TProperty>(ViewPage<TViewModel> viewPage, Expression<Func<TViewModel, TProperty>> expression) { return viewPage.Html.IdFor(expression); } public static MvcHtmlString FocusScript<TViewModel>(this ViewPage<TViewModel> viewPage) { if (viewPage.ViewData["FieldToFocus"] == null) return MvcHtmlString.Empty; object expression = viewPage.ViewData["FieldToFocus"]; Type expressionType = expression.GetType(); // expressionType = Expression<Func<TViewModel, TProperty>> Type functionType = expressionType.GetGenericArguments()[0]; // functionType = Func<TViewModel, TProperty> Type[] functionGenericArguments = functionType.GetGenericArguments(); // functionGenericArguments = [TViewModel, TProperty] System.Reflection.MethodInfo method = typeof(ViewPageExtensions).GetMethod("GetIdFor").MakeGenericMethod(functionGenericArguments); // method = GetIdFor<TViewModel, TProperty> MvcHtmlString id = (MvcHtmlString)method.Invoke(null, new[] { viewPage, expression }); // Call GetIdFor<TViewModel, TProperty>(viewPage, expression); return MvcHtmlString.Create( @"<script type=""text/javascript"" language=""javascript""> $(document).ready(function() { setTimeout(function() { $('#" + id + @"').focus(); }, 500); }); </script>"); } } Perhaps there's a more elegant way to do, but I think what it boils down to is you're trying to cast an object (ie return type of ViewData["FieldToFocus"]) to the correct expression tree Expression<Func<TViewModel, TProperty>> but like you've said you don't know what TProperty should be. Also to make this work I had to add another static method to GetIdFor because at the moment I'm not too sure how to invoke an extension method. Its just a wrapper to call the IdFor extension method. You could make it less verbose (but probably less readable). object expression = viewPage.ViewData["FieldToFocus"]; MethodInfo method = typeof(ViewPageExtensions).GetMethod("GetIdFor") .MakeGenericMethod(expression.GetType().GetGenericArguments()[0].GetGenericArguments()); MvcHtmlString id = (MvcHtmlString)method.Invoke(null, new[] { viewPage, expression }); One final thought, would the output of HtmlHelper.IdFor ever differ from ExpressionHelper.GetExpressionText? I don't fully understand IdFor, and wonder if it will always give you a string that matches the property name. ViewData["FieldToFocus"] = ExpressionHelper.GetExpressionText(fieldExpression); A: It's as simple as using a LambdaExpression. No need to go the Expression<Func<TModel, TProperty>> way. public static class HtmlExtensions { public static string IdFor( this HtmlHelper htmlHelper, LambdaExpression expression ) { var id = ExpressionHelper.GetExpressionText(expression); return htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldId(id); } public static MvcHtmlString FocusScript( this HtmlHelper htmlHelper ) { if (htmlHelper.ViewData["FieldToFocus"] != null) { return MvcHtmlString.Create( @"<script type=""text/javascript""> $(document).ready(function() { setTimeout(function() { $('#" + htmlHelper.IdFor((LambdaExpression)htmlHelper.ViewData["FieldToFocus"]) + @"').focus(); }, 500); }); </script>"); } else { return MvcHtmlString.Empty; } } } then in your controller: public ActionResult Index() { FocusOnField((MyModel m) => m.IntProperty); return View(new MyModel()); } and in your view: @model MyModel @Html.FocusScript() This being said I am leaving without comment the fact that a controller action is setting a focus. A: You can take advantage of your out of the box Metadata to provide you the property Id etc.. And then in your Extensions: public static MvcHtmlString FocusFieldFor<TModel, TValue>( this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) { var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData); var fullPropertyName = html.ViewData.TemplateInfo.GetFullHtmlFieldId(metadata.PropertyName); var jsonData = @"<script type=""text/javascript""> $(document).ready(function() { setTimeout(function() { $('#" + fullPropertyName + @"').focus(); }, 500); }); </script>"; return MvcHtmlString.Create(jsonData); } A: Maybe I'm missing something, but since you're passing in the field name to your FocusOnField function, could you not also just pass the string of the field name as well which will be the default ID in the view then set a ViewData value? Then your javascript could do something like... <script type="text/javascript"> onload = focusonme; function focusonme() { var element = document.getElementById(@ViewData["FieldToFocus"]); element.focus(); } </script> Maybe this isn't exactly what you're after, but the JS will definitely work this way...
unknown
d17418
val
When I have compiled from source, after running "cmake" I had to: * *cd into "python" folder (you shloud see the folder in the path you ran the "cmake") and run "pip install -e ." *or, you will need to run make install.
unknown
d17419
val
You can access the grid reference in useEffect block when all it's content is rendered: useEffect(()=> { const grid = ref.current.wrapper.current; //--> grid reference const header = grid.querySelector(".gridjs-head"); //--> grid header const itemContainer = document.createElement("div"); //--> new item container header.appendChild(itemContainer); ReactDOM.render(<Input />, itemContainer); //--> render new item inside header }, []); You will need to use css to get the desired position inside the element. Working example: https://stackblitz.com/edit/react-r5gsvw A: Or just use a CSS solution for that component you want. e.g. <div style={{ position: 'relative'}}> <Grid .... /> <MySearchComponent style={{ position: 'absolute', top: 0, right: 0 }} /> </div>
unknown
d17420
val
What about the simple: SELECT * FROM user_details d INNER JOIN user_type t ON t.us_ty_id = d.us_ty_id INNER JOIN user_master m ON m.usr_ma_id = t.usr_ma_id;
unknown
d17421
val
You need to use PackageManager's GET_PERMISSIONS flag. Check this question. A: Use the following code in your activity: I created StringBuffer appNameAndPermissions = new StringBuffer(); to append all the apps and permisssions info. It's working fine. I tested it already. If you have any issues, please let me know. StringBuffer appNameAndPermissions = new StringBuffer(); PackageManager pm = getPackageManager(); List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA); for (ApplicationInfo applicationInfo : packages) { Log.d("test", "App: " + applicationInfo.name + " Package: " + applicationInfo.packageName); try { PackageInfo packageInfo = pm.getPackageInfo(applicationInfo.packageName, PackageManager.GET_PERMISSIONS); appNameAndPermissions.append(packageInfo.packageName+"*******:\n"); //Get Permissions String[] requestedPermissions = packageInfo.requestedPermissions; if(requestedPermissions != null) { for (int i = 0; i < requestedPermissions.length; i++) { Log.d("test", requestedPermissions[i]); appNameAndPermissions.append(requestedPermissions[i]+"\n"); } appNameAndPermissions.append("\n"); } catch (NameNotFoundException e) { e.printStackTrace(); } Use the following permission in your AndroidManifest.xml file: <uses-permission android:name="android.permission.GET_TASKS"/> A: Zhocker To uninstall any app use below code Intent i = new Intent(Intent.ACTION_DELETE); i.setData(Uri.parse("package:com.package name")); startActivity(i); And to get permissions use getInstalledPackages(int) with the flag GET_PERMISSIONS A: * *For App's permission go to Manifest file ans see. 2.for uninstall the app follow the below points:- a. go to setting b. then Open Application c. then open Manage Application d. then choose the app which you want to Uninstall e. then click on Uninstall and Uninstall the app.
unknown
d17422
val
You will need to use - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 30; } - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UIView *v = [[UIView alloc] init]; [v setBackgroundColor:[UIColor blackColor]]; return [v autorelease]; } This was free-handed so forgive any typos, etc.. UPDATE: This only works for 'grouped' tables. Is your table grouped, or normal? A: Yes. Customize the HeaderInSection using the method in UITableViewDelegate Protocol: - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section As it returns a UIView, you can set it to anything you like or just [UIView setBackgroundColor:UIColor];
unknown
d17423
val
actionListener="#{bean[confMethod(param1, param2)]}" This syntax is indeed invalid. You're basically expecting that the confMethod is a static function which returns the name of the dynamic method based on the given two arguments. The correct syntax is as below: actionListener="#{bean[confMethod](param1, param2)}"
unknown
d17424
val
Found the anwser myself; the error occurs if the value-fields in the radion button collection is left blank. So make sure your value-fields has some kind of value entered, when appropiate.
unknown
d17425
val
Thanks @jordanm for answering in the comments. I'm expanding into a more detailed answer. The client documentation contains a section called "Service Resource" that I had not noticed before. Highlighted the service resource in the table of contents: Clicking this heading shows me the methods and properties of an EC2 resource instance. A: Hope this answer is useful to some even though its late. Use these two links accordingly Consider the 1st one as the Main reference. This is the link provided in the other answer https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#service-resource Main reference The 2nd one provides a more detailed view on the methods and attributes available for a particular resource like instance,image,VPC etc https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html ^this is almost the same link -- all options below the service-resource provide detailed info on that particular resource such as instance,image etc., common resources
unknown
d17426
val
maximum = 10 a, b, c, d = 1, maximum, maximum, 1 while a <= maximum: print('*'*a + ' '*(maximum-a) + ' '*2 + '*'*b + ' '*(maximum-b) + ' '*2 + ' '*(maximum-c) + '*'*c + ' '*2 + '*'*d + ' '*(maximum-d)) a += 1 d += 1 b -= 1 c -= 1 A: Thanks to @AzBakuFarid the main idea is to print every line of shapes from the top to the last together. @AzBakuFarid code had a very little mistake that you can see the corrected one below : maximum = 10 a, b, c, d = 1, maximum, maximum, 1 while a <= maximum: print('*'*a + ' '*(maximum-a) + ' '*2 + '*'*b + ' '*(maximum-b) + ' '*2 + ' '*(maximum-c) + '*'*c + ' '*2 + ' '*(maximum-d) + '*'*d) a += 1 d += 1 b -= 1 c -= 1 As u wanted to be with for-loops I came up with this : longest = int(input()) asterisk_a = 1 spaces_a = longest - 1 asterisk_b = longest spaces_b = 0 asterisk_c = longest spaces_c = 0 asterisk_d = 1 spaces_d = longest - 1 for i in range(0,longest): print(asterisk_a * '*' + spaces_a * ' ' + ' ' + asterisk_b * '*' + spaces_b * ' ' + ' ' + spaces_c * ' ' + asterisk_c * '*' + ' ' + spaces_d * ' ' + asterisk_d * '*') asterisk_a += 1 spaces_a -= 1 asterisk_b -= 1 spaces_b += 1 asterisk_c -= 1 spaces_c += 1 asterisk_d += 1 spaces_d -= 1 In the first line you should give the number of asterisks in the longest case. I tried to use meaningful variable names for better understanding.
unknown
d17427
val
The error is indicating that the url entry in your app.yaml is not valid. Try this url: /udacityassignment2 And as Tim pointed, the mapping should be app = webapp2.WSGIApplication([ ('/udacityassignment2', MainHandler) ], debug=True) A: You can make the URL entry as below to give you more flexibility when creating your url routing table - url: .* script: main.app
unknown
d17428
val
You are getting this exception because the session that has been used to fetch the User entity has been closed (more probably it must have been destroyed somewhere in the code). If you need to fetch the Cars collection you will have to make sure that you have the same session open when you try to access the Cars property in the User entity. I have also fallen once in this pitfall. I don't think that exceptions itself causes any performance issues.
unknown
d17429
val
In order to you get the fair estimation of your trained model on the validation dataset you need to set the test_itr and test_batch_size in a meaningful manner. So, test_itr should be set to: Val_data / test_batch_Size Where, Val_data is the size of your validation dataset and test_batch_Size is validation batch size value set in batch_size for the Validation phase.
unknown
d17430
val
values[i+1] goes out of bounds for the last value, so you need to change your for loop condition for(int i = 0; i < values.size() - 1; ++i){ // ^^^ A: 1.Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them. Exit the program when a terminating 'I' is entered. int a, b = 0; // anything that isn't a int terminate the input e.g. 2 3 | while (cin >> a >> b) cout << a << " " << b << "\n"; 2.Change the program to write out the smaller value is: followed by the smaller of the nwnbers and the larger value is: followed by the larger value. int a, b; const string smaller = "smaller value is: "; const string larger = "larger value is: "; while (cin >> a >> b) { if (a < b) cout << smaller << a << larger << b << endl; else cout << smaller << b << larger << a << endl; } if (cin.fail()) { cin.clear(); char ch; if (!(cin >> ch && ch == '|')) throw runtime_error(string {"Bad termination"}); }
unknown
d17431
val
I added the spring-cloud-starter-zuul dependency and the application started <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId> </dependency>
unknown
d17432
val
Yes.
unknown
d17433
val
I guess you need to select promo price if it's available otherwise you need normal price. So you should select columns using IF statement after LEFT JOIN. this query may help : SELECT if(td_prom.ID, td_prom.ID, td_norm.ID) as ID, th.doc_num, if(td_prom.price, td_prom.price, td_norm.price) as price, if(td_prom.item, td_prom.item, td_norm.item) as item, th.promo FROM t_header th LEFT JOIN t_detail as td_norm ON th.doc_num = td_norm.doc_num AND th.promo = 0 LEFT JOIN t_detail as td_prom ON th.doc_num = td_prom.doc_num AND th.promo = 1 GROUP BY item A: As I can see in you desired result, you don't want items to be shown twice. Next to this I assume you have an items table in your database. Then I came up with this query. First part is to extract items in promo. Second part add only those items which are not in promo, but exclude items that have a promo on them. SELECT d.id, d.doc_num, d.item, d.price, h.promo FROM items AS i INNER JOIN detail AS d ON i.id = d.id INNER JOIN header AS h ON h.doc_num = d.doc_num AND h.promo = 1 UNION ALL SELECT nopromo.* FROM (SELECT d.id, d.doc_num, d.item, d.price, h.promo FROM items AS i INNER JOIN detail AS d ON i.id = d.id INNER JOIN header AS h ON h.doc_num = d.doc_num AND h.promo = 0) AS nopromo LEFT OUTER JOIN (SELECT d.id, d.doc_num, d.item, d.price, h.promo FROM item AS i INNER JOIN detail AS d ON i.id = d.id INNER JOIN header AS h ON h.doc_num = d.doc_num AND h.promo = 1) AS ipromo ON nopromo.item = ipromo.item WHERE ipromo.id IS NULL ORDER BY item Result +---+--------+-----+------+------+ |id |doc_num |item |price |promo | +---+--------+-----+------+------+ |1 |0001 |2 |100 |0 | |5 |0002 |3 |120 |1 | |6 |0002 |4 |99 |1 | |4 |0001 |5 |105 |0 | |7 |0002 |7 |165 |1 | +---+--------+-----+------+------+
unknown
d17434
val
Company (a single company can appear multiple times) Column B: Account Manager (a single name can be associated with multiple Companies) Column C: concatenates Account Managers into single line using formula =IF(A2=A1,C1&", " & B2,B2) Every time new data is added, the entire sheet is sorted A-Z by Company. The goal of the concatenation is to have ALL Account Managers associated with that particular company in one cell so that that cell can be referenced in the table mentioned above, which appears on a separate sheet in this workbook; however, if that AM has made multiple sales for the same company, the formula still adds it to the final list, which can result in a list of "Bob, Joe, Bob, Tom, Bob" when I want to see "Bob, Joe, Tom". The formula I use in the table to reference this list of AMs for each company is =LOOKUP(A5,'7.1.16 data'!A:A,'7.1.16 data'!C:C) A: Just add a SEARCH query in your IF statement: =IF(A2=A1,IF(ISNUMBER(SEARCH(B2, C1)), C1, C1 &", " & B2),B2) Regards Cg
unknown
d17435
val
10 xl/workbook.xmlPK-!ûb¥m”§³ That says you're uploading an XML workbook You would first need to convert the file to a comma delimited CSV A: * *Have yout tried with another csv file? Maybe it's a formating error *Do you have to strictly do that trough php? Why not just run directly a sql query like this? *Read this: * *Save CSV files into mysql database *PHP script to import csv data into mysql
unknown
d17436
val
By manually setting the camera position in update, you're delaying the camera movement by at least one frame — physics runs after update, so your camera move happens on the frame after your character moves. When you use a move action instead of directly setting the position, and giving that action a nonzero duration, you're delaying the camera move even more. (The dt in your code is the time between this frame and the last one before it, and you're applying that time to a future movement.) Because the character is still moving while your action runs, the camera will never catch up — you're always moving the camera to where the character was. Setting the camera position at all is just making extra work for yourself, though. Use SKConstraint instead, and SpriteKit itself will make sure that the camera position sticks to the character — it solves constraints after physics, but on the same frame.
unknown
d17437
val
You can use the css :hover selector.. Since you didn't specify the exact structure of your html its hard for me to say how exactly you should implement it. Lets say for this matter that you want to show the on table mouse hover, and you table class is 'my-table'. .my-table:hover{ th{ display:none; } } You can read about the :hover selector here. Edit: If your html strauctre is something like: <span class='my-toggle-span'>Toggle app filter!</span> <app-filter class='my-app-filter'></app-filter> Then your css will be .my-toggle-span:hover +.my-app-filter{ display:none; } The plus selector Selects all element that are placed immediately after it. Edit 2: As opener requested, A javascript based solution: I don't recommend this approach and any way, Your toggle logic should be handled in your component and not in your html. <span class='my-toggle-span' (mouseenter)="toggle=true;" (mouseleave)="toggle=false;">Toggle app filter!</span> <app-filter *ngIf="toggle" class='my-app-filter'></app-filter>
unknown
d17438
val
But PreferLocalXml is supposed to point to a local file, not a web server, so SSL would not apply - the file is accesses using the file API.
unknown
d17439
val
If I didn't missed anything: RewriteEngine On RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/(.+)\.php[^\s]* [NC] RewriteRule ^ /%1 [R=301,NE,L] RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^ %{REQUEST_URI}.php [QSA,NC,L] Requests to /dive-sites.php will issue a 301 redirect to /dive-sites, appending query-strings if any. Requests to /dive-sites will get a 200 response with /dive-sites.php as Content-Location, appending query-strings if any. A: try this: RewriteEngine on RewriteRule ^/(.+)(($|#)*(.*)) /$1.php$2 If removing only the .php this will work. $1 = for the name of the page, e.g foo $2 = take note of the hashtag or the get request eg. <domain>/example ----> <domain>/example.php <domain>/example?get=this ----> <domain>/example.php?get=this <domain>/example#hash ----> <domain>/example.php#hash A: Try this code for .php extension removal: RewriteEngine On ## hide .php extension # To externally redirect /dir/file.php to /dir/file RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(.+?)\.php[\s?] [NC] RewriteRule ^ /%1 [R=301,L,NE] # To internally forward /dir/file to /dir/file.php RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{DOCUMENT_ROOT}/$1.php -f RewriteRule ^(.+?)/?$ /$1.php [L]
unknown
d17440
val
Try this: @FormUrlEncoded @POST(Constants.UrlPath.POST_CLOSE_EVENT) Call<ResponseBody> callDeleteEventRequest(@FieldMap Map <String, String>id); A: add headers in your interface class: @Headers({"Content-Type: application/json", "eventId: 1"}) @POST(Constants.UrlPath.POST_CLOSE_EVENT) Call<ResponseBody> callDeleteEventRequest(); A: check your path Constants.UrlPath.POST_CLOSE_EVENT is right or not. try to call using postman if it is working fine in that or not.
unknown
d17441
val
You can force the use of the index by doing the following: FORCE INDEX (myKey) FORCE INDEX mySQL ...where do I put it?
unknown
d17442
val
object.class.to_s.tableize A: For semantic reasons, you might want to do: object.class.name #=> 'FooBar' You can also use tableize with this sequence, like so: object.class.name.tableize #=> 'foo_bars' I prefer it that way due to readability. As well, note that tableize also does pluralization. If unwanted use underscore. Hope it helps anyone, even if it's an old thread :)
unknown
d17443
val
maybe have a scheduled task to update that information maybe every day or week? Here is one gem for helping on that https://github.com/bvandenbos/resque-scheduler/
unknown
d17444
val
I never did figure out a sure-fire way of ensuring the event gets called. I'm guessing that if the response object never actually starts the stream, it never starts thus never having an ending event. If anyone knows a workaround feel free to answer and get a free accepted answer.
unknown
d17445
val
This is my solution so far. But I am hoping there is a better solution out there... I use the pseudo element of active a to create a white border to hide the sharp corner. body { background:#eee;width:90%;margin:20px auto } ul { margin: 0; padding: 0; } ul li { display: inline-block; list-style: none; position: relative; vertical-align:bottom; } ul li a { padding: 10px 15px; display: block; line-height: 25px; margin-bottom:-1px; } ul li.active a { background:#fff; border:1px solid #aaa; border-bottom:0; border-radius:5px 5px 0 0; } ul li.active:before, ul li.active:after { content:""; position:absolute; bottom:-1px; width:10px; height:10px; border:solid #aaa; } ul li.active:before { left:-10px; border-radius:50% 0; border-width:0 1px 1px 0; box-shadow: 1px 1px white; } ul li.active:after { right:-10px; border-radius: 0 50%; border-width:0 0 1px 1px; box-shadow: -1px 1px white; } .content { border:1px solid #aaa;background:#fff;height:200px } <ul> <li><a href="#">tab 1</a></li> <li class="active"><a href="#">tab2</a></li> <li><a href="#">tab3</a></li> <li><a href="#">tab4</a></li> </ul> <div class="content"></div> UPDATE: My previous answer requires more css so I edited it. Based on the answer of jbutler, I got the idea about adding box-shadow to hide the corners. Nothing much changed on the original css I presented here, I just added the box-shadow. Updated fiddle HERE. A: You can try using a white square block :before and :after the li.active a element, and positioning it so it's between the radius and the li: ul li.active a:before, ul li.active a:after { content: ""; position: absolute; background-color: white; height: 11px; width: 10px; bottom: -1px; } ul li.active a:before { left: -6px; z-index: 1; } ul li.active a:after { right: -6px; background-color: white; z-index: 6; } ul li.active:before { left:-10px; border-radius:8px 0; border-width:0 1px 1px 0; z-index: 5; // <<< This too } ul li.active:after { right:-10px; border-radius: 0 8px; border-width:0 0 1px 1px; z-index: 10; // <<< And here } http://jsfiddle.net/be5ceL9z/4/ This essentially just covers the square bottom corners of the li.active and #content elements by manipulating little square elements to cover them, but to be under the border-radius'd li.active:before and :after. A more thorough explanation (courtesy atomictom's answer): https://css-tricks.com/tabs-with-round-out-borders/ A: Here is an example of how this could be achieved with a combination of rotation and box shadows: Initially, you have your rectangular div/element: +---------+ | ELEMENT | +---------+ From that, you can position a pseudo element either side of the bottom corners, with a border radius of 50% (to make a circle) +---------+ | ELEMENT | O+---------+O Because I haven't set a background colour, you won't see this. I've set a border on both, but then set three of the side colours to 'transparent' (so you only see one border). Rotating this means that you can make the 'curved corner border' for each side: +---------+ | ELEMENT | )+---------+( Using a box shadow then means you can hide the 'elements bottom corner' anyway: +---------+ | ELEMENT | ) --------- ( Then setting the bottom border color to the active elelemtn itself means it is then 'hidden' anyway: +---------+ | ELEMENT | ) ( <-- rotated slightly to create your corner DEMO /*FOR DEMO ONLY*/ $(document).ready(function() { $('.menu div').click(function() { $('.menu div').removeClass("act"); $(this).addClass("act"); }); }); html { background: lightgray; } .menu div { display: inline-block; height: 50px; width: 100px; background: white; margin: 10px; position: relative; text-align: center; border-radius: 10px 10px 0 0; border: 2px solid black; cursor:pointer; } .menu .act { border-bottom-color: white; z-index: 40; } .act:before, .act:after { content: ""; position: absolute; bottom: -2px; height: 20px; width: 20px; border-radius: 50%; border: 2px solid transparent; z-index: 30; } .act:before { left: 100%; border-left-color: black; -webkit-transform: rotate(-40deg); -moz-transform: rotate(-40deg); transform: rotate(-40deg); box-shadow: -20px 2px 0 0 white; } .act:after { right: 100%; border-right-color: black; -webkit-transform: rotate(40deg); -moz-transform: rotate(40deg); transform: rotate(40deg); box-shadow: 20px 2px 0 0 white; } .panel { width: 80vw; margin-top: -12px; background: white; border-top: 2px solid black; z-index: 20; padding-top: 12px; position: relative; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="menu"> <div>1</div> <div class="act">2</div> <div>3</div> </div> <div class="panel">Don't you wish Tabs could just be easy?</div> Note the jquery included here is for demo only, and shows how you can 'switch tabs'. A: I'd just comment but I'm not allowed.. Is this the effect you're after? https://css-tricks.com/tabs-with-round-out-borders/ Looks like you need another psuedo element.
unknown
d17446
val
You might be able to do it with textscan and repmat so you can avoid conversion from strings: Nfeatures = 240; fid = fopen('text.txt'); format = ['%s ' repmat('%f', [1 Nfeatures])]; imageFeatureCell = textscan(fid, format, 'CollectOutput', true); fclose(fid); A test on a file with 7 rows: >> fileData fileData = {7x1 cell} [7x240 double] Move into your desired variables: names = fileData{1}; % names{1} contains first file name, etc. histogram = fileData{2}; % histogram(1,:) contains first file's features A: str = textread('tmp.txt','%s'); str = reshape(str,241,[]).'; names = str(:,1); %'// cell array of strings with image names histogram = str2double(str(:,2:end)); %// each row refers to an image
unknown
d17447
val
importPackage is originally from Rhino. Even Nashorn supports it when Rhino/Mozilla compatibility is requested explicitly using load("nashorn:mozilla_compat.js"); only, see Rhino Migration Guide in the documentation of Nashorn. Graal.js has Nashorn compatibility mode and it supports load("nashorn:mozilla_compat.js"); in this mode. So, you can use something like System.setProperty("polyglot.js.nashorn-compat", "true"); ScriptEngine engine = new ScriptEngineManager().getEngineByName("graal.js"); System.out.println(engine.eval("load('nashorn:mozilla_compat.js'); importPackage('java.awt'); new Point();")); (it prints java.awt.Point[x=0,y=0] which shows that the package java.awt was imported successfully).
unknown
d17448
val
This is not really an answer, but more of a compilation of elements. Reference : The site http://www.cplusplus.com/ is clear: for the wprintf family : ... all format specifiers have the same meaning as in printf; therefore, %lc shall be used to write a wide character (and not %c), as well as %ls shall be used for wide strings (and not %s) Implementations : gcc and clang both conform to above specification MSVC and according to OP Borland C++ do not conform and accept %s for a wide string. A: I managed to find this in the vprinter.c file in the RTL source code (C++Builder comes with its own RTL, it doesn't reference MS): /* The 's' conversion takes a string (char *) as * argument and copies the string to the output * buffer. * * Note: We must handle both narrow and wide versions * depending on the flags specified and the version called: * * Format printf wprintf * ---------------------------------------- * %s narrow wide * %S wide narrow * %hs narrow narrow * %hS narrow narrow * %ls wide wide * %lS wide wide * */ so the code: swprintf(v, 50, L"%hs", "hello"); generates the correct output. However, this doesn't do any UTF-8 conversion; narrow characters are "widened" by attaching a null byte. (Confirmed by inspecting the resut of the source).
unknown
d17449
val
It looks like you want the set difference (that is, IPs in A that are not also in B), soooooo: SELECT a.ip FROM tableA a WHERE tableA.ip NOT IN (SELECT b.ip FROM tableB) A: Use NOT IN: SELECT ip FROM TableA WHERE TableA.ip NOT IN (SELECT ip FROM TableB) A: You can combine two result sets with UNION. select ip from tableA union select ip from tableB; http://dev.mysql.com/doc/refman/5.0/en/union.html The default behavior is to remove duplicate rows. If you want duplicate rows use UNION ALL. A: select a.id from a minus select b.id from b or select a.id from a where a.id not in (select b.id from b) A: SELECT col1, col2, .. , Ip from TableA UNION SELECT col, col2, ...., Ip from TableB To get the differences you can use the MINUS Operator instead of UNION
unknown
d17450
val
You can use from ... import ... statement: from package.obj import obj my_obj = obj() A: Python is not Java. Feel free to put many classes into one file and then name the file according to the category: import mypackage.image this_image = image.png(...) that_image = image.jpeg(....) If your classes are so large you want them in separate files to ease the maintenance burden, that's fine, but you should not then inflict extra pain on your users (or yourself, if you use your own package ;). Gather your public classes in the package's __init__ file (or a category file, such as image) to present a fairly flat namespace: mypackage's __init__.py (or image.py): from _jpeg import jpeg from _png import png mypackage's _jpeg.py: class jpeg(...): ... mypackage's _png.py: class png(...): ... user code: # if gathered in __init__ import mypackage this_image = mypackage.png(...) that_image = mypackage.jpeg(...) or: # if gathered in image.py from mypackage import image this_image = image.png(...) that_image = image.jpeg(....) A: Give your classes and modules meaningful names. That's the way. Name your module 'classes' and name your class 'MyClass'. from package.classes import MyClass myobj = MyClass()
unknown
d17451
val
Your forgot the changes keyword. The correct syntax is when transform $Body changes do ( print "moved" ) A: An already key-framed node will not trigger this handler it is not being driven by the user, but by the system. This will not trigger when you press play in the trackbar. Without knowing exactly what you intend to do it's difficult to recommend an alternative. If you wish to report the position or transform information of a specific node when the trackbar/currentTime changes, you could use registerTimeCallback and unRegisterTimeCallback . fn reportObject = ( print $Box001.pos ) registerTimeCallback reportObject This will trigger when the play button is used, or when you scrub the time bar. Read the documentation regarding timecallbacks as they have specific rules. Hopefully this helps.
unknown
d17452
val
You could create a new xsd:dateTime literal based on the original xsd:date literal. Here is an example if you want to replace the original triples in the graph with new triples with the converted literal as the object: from rdflib import Literal, URIRef from datetime import datetime for s, p, o in g.triples((None, URIRef('hasBirthday', base=ns), None)): d = o.toPython() g.add((s, p, Literal(datetime(d.year, d.month, d.day)))) g.remove((s, p, o))
unknown
d17453
val
That stored procedure that you have posted up is way too large and blocky to even try to interpret and understand. So I will go off of your last sentence: I want the CantSocias column takes the most value of the Ciclo column, but not working Basically if you want to set a specific column to that, you can do something like this: update YourTable set CantSocias = ( select max(Ciclo) from YourOtherTable ) -- here is where you can put a conditional WHERE clause A: You may need to create a sub query to get the most value of Ciclo and join back to your query. An example of what I mean is here: create table #Product ( ID int, ProductName varchar(20) ) insert into #Product(ID, ProductName) select 1,'ProductOne' union select 2,'ProductTwo' create table #ProductSale ( ProductID int, Number int, SalesRegion varchar(20) ) insert into #ProductSale(ProductID,Number,SalesRegion) select 1,1500,'North' union select 1, 1200, 'South' union select 2,2500,'North' union select 2, 3200, 'South' --select product sales region with the most sales select * from #Product p select ProductId, Max(Number) as Bestsale from #ProductSale ps group by ProductID --combining select p.ID, p.ProductName, tp.Bestsale, ps.SalesRegion from #Product p inner join (select ProductId, Max(Number) as Bestsale from #ProductSale ps group by ProductID) as tp on p.ID = tp.ProductID inner join #ProductSale ps on p.ID = ps.ProductID and tp.Bestsale = ps.Number
unknown
d17454
val
Your problem is that the \n characters displayed when your read your text file are actually \\n characters. These characters won't get identified by the VTTCue parser as being new lines, so you need to replace these characters in the third argument of the VTTCue constructor to actual new lines, \n. // make the file available in StackSnippet const txt_uri = URL.createObjectURL(new Blob([String.raw`1 --> 13 "Golden dreams\nand great heartache"`], {type: 'text/plain'})); var video_player = document.querySelectorAll('[video-player]')[0]; track_english = video_player.addTextTrack("captions", undefined, "en"); track_english.mode = "showing"; subtitles_xhr(function(buffer) { var file = buffer; file = file.split('\n'); for (var x = 0; x < file.length; x += 2) { let startTime = file[x].split(" --> ")[0], endTime = file[x].split(" --> ")[1], content = file[x + 1] .replace(/\\n/g, '\n'); // here replace all occurrences of '\\n' with '\n' track_english.addCue( new VTTCue(startTime, endTime, content) ); } }); function subtitles_xhr(cb) { var xhr = new XMLHttpRequest; xhr.open('GET', txt_uri); xhr.onload = function() { cb(xhr.response); }; xhr.send(); } video{max-height:100vh} <video video-player src="https://upload.wikimedia.org/wikipedia/commons/transcoded/a/a4/BBH_gravitational_lensing_of_gw150914.webm/BBH_gravitational_lensing_of_gw150914.webm.480p.webm" autoplay controls></video>
unknown
d17455
val
The path is in the registry but usually you edit through this interface: * *Go to Control Panel -> System -> System settings -> Environment Variables. *Scroll down in system variables until you find PATH. *Click edit and change accordingly. *BE SURE to include a semicolon at the end of the previous as that is the delimiter, i.e. c:\path;c:\path2 *Launch a new console for the settings to take effect. A: Or you can just run this PowerShell command to append extra folder to the existing path: $env:Path += ";C:\temp\terraform" A: To add a PERSISTENT path (eg one that's permanent), you can do this one-liner in PowerShell (adjust the last c:\apps\terraform part) Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value (((Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).path) + ";c:\apps\terraform" ) Alternatively, you can jump directly to the Environment Variables dialog by RUNning/CMD/PowerShell this: rundll32.exe sysdm.cpl,EditEnvironmentVariables A: Here I'm providing solution to setup Terraform environment variable in windows for beginners. * *Download the terraform ZIP file from Terraform site. *Extract the .exe from the ZIP file to a folder eg C:\Apps\Terraform copy this path location like C:\Apps\terraform\ *Add the folder location to your PATH variable, eg: Control Panel -> System -> System settings -> Environment Variables In System Variables, select Path > edit > new > Enter the location of the Terraform .exe, eg C:\Apps\Terraform then click OK *Open a new CMD/PowerShell and the Terraform command should work A: I had issues for a whilst not getting Terraform commands to run unless I was in the directory of the exe, even though I set the path correctly. For anyone else finding this issue, I fixed it by moving the environment variable higher than others! A: Why don't you create a bat file makedos.bat containing the following line? c:\DOS\make.exe %1 %2 %5 and put it in C:\DOS (or C:\Windowsè or make sure that it is in your %path%) You can run from cmd, SET and it displays all environment variables, including PATH. In registry you can find environment variables under: * *HKEY_CURRENT_USER\Environment *HKEY_CURRENT_USER\Volatile Environment *HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment A: just copy it to system32 call make1 or whatever if the name conflicts.
unknown
d17456
val
$ denotes the end of the string (while ^ marks the start), so you should put it at the end of the string. ^.+?testurl\.com/folder-path/(\w+?)/secondfolder$
unknown
d17457
val
See What is the most efficient way to get this kind of matrix from a 1D numpy array? and Copy flat list of upper triangle entries to full matrix? Roughly the approach is result = np.zeros(...) ind = np.triu_indices(...) result[ind] = values Details depend on the size of the target array, and the layout of your values in the target. In [680]: ind = np.triu_indices(4) In [681]: values = np.arange(16).reshape(4,4)[ind] In [682]: result = np.zeros((4,4),int) In [683]: result[ind]=values In [684]: values Out[684]: array([ 0, 1, 2, 3, 5, 6, 7, 10, 11, 15]) In [685]: result Out[685]: array([[ 0, 1, 2, 3], [ 0, 5, 6, 7], [ 0, 0, 10, 11], [ 0, 0, 0, 15]])
unknown
d17458
val
I managed to solve the issue with help from the comments above. The issue was that Unity was unable to compile/build the project, hence as 3Dave and Corey Smith said - if there are any compile errors you are unable to attache scripts to GameObjects. I also realized I was unable to run the project. I first though it might be an issue with .NET versions on Ubuntu, but it turned out to be issue with libssl1.0 library (if you have a greater version then Unity won't work on Ubuntu 19.04). See this post for reference: https://forum.unity.com/threads/empty-log-errors-in-2019-1-0f2.669961/#post-4545013 Installing libssl1.0 solved the compile issues, I'm now able to attache scripts to GameObjects and run the project. A: Old question, but I solved this problem using the Help menu and then Reset Packages to defaults.
unknown
d17459
val
Try this code: #!/usr/bin/env python import gi gi.require_version ('Gtk', '3.0') from gi.repository import Gtk, GdkPixbuf, Gdk, GLib import os, sys, time class GUI: def __init__(self): window = Gtk.Window() self.switch = Gtk.Switch() window.add(self.switch) window.show_all() self.switch.connect('state-set', self.switch_activate) window.connect('destroy', self.on_window_destroy ) def on_window_destroy(self, window): Gtk.main_quit() def switch_activate (self, switch, boolean): if switch.get_active() == True: GLib.timeout_add(200, self.switch_loop) def switch_loop(self): print time.time() return self.switch.get_active() #return True to loop; False to stop def main(): app = GUI() Gtk.main() if __name__ == "__main__": sys.exit(main())
unknown
d17460
val
That should be becouse you got 1405 records where "KWB.CIVCONDGRADE" is actually NULL and 5 records where "KWB.CIVCONDGRADE" isn't NULL but simply an empty field. Try to check with this query if it results 5 records: WHEN KWB.ASYCONDTYPE IN ('CIVIL','CIVIL2') AND KWB.CIVCONDGRADE = '' THEN 'NO CIVIL CG'
unknown
d17461
val
When you downloaded the program you probably got a .exe file, you need to execute this program with two command line arguments like so: programname.exe word1 word2 If your friend didn't give you a executable file you need to compile the source into an executable. CodeBlocks provides this functionality and automatically runs the compiled result. Unfortunately it doesn't pass any arguments to the result which is why the program is telling you that it needs two words. (CodeBlocks is just executing programname.exe) One solution to this problem is to configure code blocks to provide the arguments. As danben pointed out you can use the "Set program arguments" option in the "Project" menu to configure it to provide arguments. If you set your program arguments as word1 word2 then CodeBlocks will execute programname.exe word1 word2 which is what you want. If you want to run this program elsewhere you need to compile it. Luckily whenever you click "run" in CodeBlocks it actually does compile an executable somewhere, typically in the project folder under bin\debug or bin\release you'll find a exectuable file. You can use this file as outlined above. A: This is a question about CodeBlocks rather than about C++, but a quick Google search reveals that you need to select the "Set program arguments" option under the "Project" menu.
unknown
d17462
val
Is there any advantage over the other? The first really should be a val and not a var. Otherwise, they are equivalent. Or, to quote the documentation: There are three ways to declare a MutableState object in a composable: * *val mutableState = remember { mutableStateOf(default) } *var value by remember { mutableStateOf(default) } *val (value, setValue) = remember { mutableStateOf(default) } These declarations are equivalent, and are provided as syntax sugar for different uses of state. You should pick the one that produces the easiest-to-read code in the composable you're writing. In those three: * *In the first, mutableState holds a MutableState, and you use .value and .value= to manipulate the contents *In the second, value holds a MutableState, but the by syntax tells the compiler to treat it as a property delegate, so we can pretend that value just holds the underlying data *In the third, a destructuring declaration gives you getter and setter references to manipulate the content in the underlying MutableState A: The by in this context is a kotlin property delegate. Any class that implements the operator fun operator fun getValue(thisRef: Any?, prop: KProperty<*>): T can use this syntax. Using = will eagerly assign the variable (importantly without delegation), the by will delegate to the operator function. The remember in this case is just a shortcut function to creating the Remember delgate that wraps the value you are creating inside the { ... } block. A typical example is the kotlin Lazy<T> class : val myValue : Int by lazy { 1 }. If used with the by operator you will return the Int value, if used with = it will return Lazy<Int> as you have not used delegation. It is also worth noting that delgates can be setters as well by using this operator fun : operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: T).
unknown
d17463
val
string MyConString = "Data Source='mysql7.000webhost.com';" + "Port=3306;" + "Database='a455555_test';" + "UID='a455555_me';" + "PWD='something';"; A: Here is an example: MySqlConnection con = new MySqlConnection( "Server=ServerName;Database=DataBaseName;UID=username;Password=password"); MySqlCommand cmd = new MySqlCommand( " INSERT Into Test (lat, long) VALUES ('"+OSGconv.deciLat+"','"+ OSGconv.deciLon+"')", con); con.Open(); cmd.ExecuteNonQuery(); con.Close(); A: try creating connection string this way: MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder(); conn_string.Server = "mysql7.000webhost.com"; conn_string.UserID = "a455555_test"; conn_string.Password = "a455555_me"; conn_string.Database = "xxxxxxxx"; using (MySqlConnection conn = new MySqlConnection(conn_string.ToString())) using (MySqlCommand cmd = conn.CreateCommand()) { //watch out for this SQL injection vulnerability below cmd.CommandText = string.Format("INSERT Test (lat, long) VALUES ({0},{1})", OSGconv.deciLat, OSGconv.deciLon); conn.Open(); cmd.ExecuteNonQuery(); }
unknown
d17464
val
With the default InProc session state, the application will terminate when the last session has expired, at which point Application_End occurs. In this scenario the entire appDomain is torn down and all memory freed. As sessions are persisted in memory they are permanently destroyed at this point, and therefore can never live beyond the life of the application. If using Sql Server or State Server where the session is stored on a separate machine, then when the application is torn down the sessions can continue to live. Then because the client retains the original session cookie in the browser, the next time they visit the site the session is restarted, and sessionid used to identify their existing session. A: Yes, when you put the state in SQL Server the application could restart but you will still maintain the session state
unknown
d17465
val
I tried your code, and I put %SIZE(USRI00300) as the second parameter, and I got zero for suppGrpIdx too. As Charles and Mark Sanderson implied, you have to make the receiver big enough to give all the information and also tell the API how big the receiver is. I'm guessing that since you defined your data structure as based, that you are setting p_usrData to some larger storage. If so, give the length of the larger storage instead of the size of USRI0300. When I set p_usrData to point to a 32767-length buffer, and put %size(buffer) as the second parameter, I got 722 for suppGrpIdx.
unknown
d17466
val
The openssl executable that is distributed with Apache for Windows and therefore WAMPServer does not seem to work very well. I have never had the time to work out exactly why! My solution was to download OpenSSL from Shining Light Products They are linked to from the Openssl Binaries page so I assume it is a stable and unhacked distribution of a windows binary etc that does the job for windows users.
unknown
d17467
val
You can find demo code at OCRScannerDemo for old api, for new api new api demo About api javadoc you can generate it with maven. To get source code : git clone http://git.code.sf.net/p/javaocr/source javaocr-source
unknown
d17468
val
see http://gist.github.com/22877
unknown
d17469
val
The regex issue can be answered with a simple negative assertion: preg_replace('/(<(?!img)\w+[^>]+)(style="[^"]+")([^>]*)(>)/', '${1}${3}${4}', $article->text) And a simpler approach might be using querypath (rather than fiddly DOMDocument): FORACH htmlqp($html)->find("*")->not("img") EACH $el->removeAttr("style"); A: This does as you've asked $string = '<img attribut="value" style="myCustom" attribut=\'value\' style=\'myCustom\' /> <input attribut="value" style="myCustom" attribut=\'value\' style=\'myCustom\'> <span attribut="value" style="myCustom" attribut=\'value\' style=\'myCustom\'> style= </span>'; preg_match_all('/\<img.+?\/>/', $string, $images); foreach ($images[0] as $i => $image) { $string = str_replace($image,'--image'.$i.'--', $string); } $string = preg_replace(array('/style=[\'\"].+?[\'\"]/','/style=/'), '', $string); foreach ($images[0] as $i => $image) { $string = str_replace('--image'.$i.'--',$image, $string); } OUTPUTS <img attribut="value" style="myCustom" attribut='value' style='myCustom' /> <input attribut="value" attribut='value' > <span attribut="value" attribut='value' > </span> A: A very simple regular expression to get rid of them, without going too much into it would be preg_replace( '/style="(.*)"/', 'REPLACEMENT' ) Very simple, effective enough though
unknown
d17470
val
"2000-04-16T18:57" is not %d/%m/%Y %H:%M format but %Y-%m-%dT%H:%M format. Check list date formatters here https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes A: Your widget format just show for client, not for Form.So you can try add a method named clean_date(self) to replace 'T' with whitespace then return it. or add your format into DATETIME_INPUT_FORMATS list of settings.py. A: i ended up managing to solve the problem, however I did not like the solution because it does not seem the most right ... however I will share it here in case people experience the same problem :) What i did was: create a copy of my GET so it becomes mutable getCopy = request.GET.copy() after that i converted the DATE that was comming from GET ts = time.strptime(request.GET['date'], "%Y-%m-%dT%H:%M") getCopy['date'] = time.strftime("%m/%d/%Y", ts) and when i call my form.is_valid instead of passing request.GET, i pass my mutable copy of GET with my formatted date :)
unknown
d17471
val
As said in the doc, the main differences are in how you are going to get an instance through Dependency Injection. With Named Client you need to inject the factory and then get the client by a string. var client = _clientFactory.CreateClient("github"); With Typed Client you can inject the client needed as a type. //GitHubService encapsulate an HTTP client public TypedClientModel(GitHubService gitHubService) { _gitHubService = gitHubService; } Both of them give the solution to your problem. The selection is more in how comfortable you are with the dependency injection method of each one. I personally prefer the Typed client.
unknown
d17472
val
You can pass the name of the list and append it to the selector as follows: function foo(){ bar("p1_lSelect"); bar("p1_rSelect"); } function bar(list){ $(`.${list} option:selected`).each(function() { selected = $(this).text(); console.log(selected); }); //Console log does not print } A: Please try following code based on your structure: function foo(){ var lList = $(".p1_lSelect"); var rList = $(".p1_rSelect"); bar(lList); bar(rList); } function bar(list){ $(list).find("option:selected").each(function() { selected = $(this).text(); console.log(selected); }); //Console log does not print } A: Use the find() method: function bar(list) { list.find("option:selected").each(function() { console.log($(this).text()); }); });
unknown
d17473
val
Could be your id_unidad_que_diligencia si an object an not a single value. $idUnidadQueDiligencia = Yii::$app->getUser()->identity->getIdUnidad(); $model->id_unidad_que_diligencia = $idUnidadQueDiligencia; try chech this situation using var_dump($model->id_unidad_que_diligencia) then if is not a flat string value adjust you code for gettin the proper value.
unknown
d17474
val
Try this: change the order of the factors and put the group you want first: FHBficData$TrtName<-factor(FHBficData$TrtName,levels=c("TC_ctrl","D_332","J_045","J_185","Neg_ctrl","D_112"),ordered=TRUE) FHBficFit3dpi <- aov(X3dpi~ TrtName, FHBficData) set.seed(115) FHBficDunnett3dpi <- glht(model = FHBficFit3dpi, linfct=mcp(TrtName="Dunnett")) summary(FHBficDunnett3dpi) You'll get this: Simultaneous Tests for General Linear Hypotheses Multiple Comparisons of Means: Dunnett Contrasts Fit: aov(formula = X3dpi ~ TrtName, data = FHBficData) Linear Hypotheses: Estimate Std. Error t value Pr(>|t|) D_332 - TC_ctrl == 0 -1.0000 0.3624 -2.759 0.0391 * J_045 - TC_ctrl == 0 -0.1667 0.3624 -0.460 0.9873 J_185 - TC_ctrl == 0 -0.2381 0.3492 -0.682 0.9361 Neg_ctrl - TC_ctrl == 0 -0.5000 0.3624 -1.380 0.5114 D_112 - TC_ctrl == 0 -1.1667 0.3624 -3.219 0.0128 * --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 (Adjusted p values reported -- single-step method)
unknown
d17475
val
You can add the following part to your CSS: #overlay { display: none; } #overlay:target { display: block; } And then in your code change: .product-detailscar .overlay To: #overlay And change opacity to more then 0, ex. 0.5; Note that it will only work one way, so it will only show the overlay. If you want to show/hide overlay in pure CSS, the checkbox hack is the way to go. For more info check https://css-tricks.com/the-checkbox-hack/ Updated example (no checkbox hack): .button i { padding: 8px 13px; display: inline-block; -moz-border-radius: 180px; -webkit-border-radius: 180px; border-radius: 180px; -moz-box-shadow: 0px 0px 2px #888; -webkit-box-shadow: 0px 0px 2px #888; box-shadow: 0px 0px 2px #888; background-color: yellow; color: red; position: absolute; left: 20%; top: 20%; } .button i:hover { color:#FFF; background-color:#000; } .product-detailscar:hover .overlay { opacity: 1; } .product-detailscar { background-color: #E6E6E6; text-align: center; position: relative; } .intro, .userfield1car { color:#fff; font-weight:700; font-size:22px; text-align:center; background-color:green; } #overlay { display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0.5; border-radius: 0; background: blue; color: #FFF; text-align: left; border-top: 1px solid #A10000; border-bottom: 1px solid #A10000; -webkit-transition: opacity 500ms; -moz-transition: opacity 500ms; -o-transition: opacity 500ms; transition: opacity 500ms; } #overlay:target { display: block; } <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/> <div> <a href="#" target="_blank"> <div class="product-detailscar"> <div class="image-video-linksidebar"> <img alt="#" src="http://lorempixel.com/200/200"> <div class="read-more"><a href="#overlay" class="button"><i class="fa fa-file-text-o fa-3x" aria-hidden="true"></i></a> </div> </div> <div id="overlay"> <div class="intro"> Intro description car </div> <div class="userfield1car"> Userfield-1-car </div> <div class="userfield1car"> Userfield-2-car </div> <div class="userfield1car"> Userfield-3-car </div> </div> </div> <!--</div>--></a> </div> BTW, it is a good idea to clean up your code ;) A: You can move the overlay div just beneath the image-video-linkssidebar class like this: <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/> <div> <a href="#" target="_blank"> <div class="product-detailscar"> <div class="image-video-linksidebar"> <div id="overlay"> <div class="intro"> Intro description car </div> <div class="userfield1car"> Userfield-1-car </div> <div class="userfield1car"> Userfield-2-car </div> <div class="userfield1car"> Userfield-3-car </div> </div> <img alt="#" src="http://lorempixel.com/200/200"> <div class="read-more"><a href="#overlay" class="button"><i class="fa fa-file-text-o fa-3x" aria-hidden="true"></i></a> </div> </div> </div> <!--</div>--></a> </div> Then add these styles to overlay: position: absolute; z-index: 9999; margin: 0 auto; width: 100%;
unknown
d17476
val
Follow these steps: 1- Change your itemChecked function to this $scope.itemChecked = function(data) { var selected = $scope.selectedItems.findIndex(function(itm) { return itm == data.item }); if (selected == -1) { $scope.selectedItems.push(data.item); } else { $scope.selectedItems.splice(selected, 1); } }; 2- Add an array for showing data after any filtering. Also add a function which filter your data according to input text: $scope.filter = function() { if (!$scope.searchField) { $scope.data2Show = angular.copy($scope.data); } else { $scope.data2Show = []; $scope.data.map(function(itm) { if (itm.item.indexOf($scope.searchField) != -1) { $scope.data2Show.push(itm); } }); } }; $scope.data2Show = []; Use this array to show items in list: <li ng-repeat="data in data2Show"> 3- Write a function to check if an item is selected or not and use: $scope.isChecked = function (data) { var selected = $scope.selectedItems.findIndex(function(itm) { return itm == data.item; }); if (selected == -1) { return false; } else { return true; } } And usage in html : <input type="checkbox" ng-change="itemChecked(data)" name="select" ng-model="selectedItems" ng-checked="isChecked(data)"> 4- Change checkbox ngModels from selectedItems to data.flag ng-model="data.flag" Final code: var app = angular.module("myApp", []); app.controller("myCtrl", function($scope, $http) { $scope.selectEnable = false; $scope.selectedItems = []; $scope.openSelect = function() { $scope.selectEnable = !$scope.selectEnable; }; $scope.itemChecked = function(data) { var selected = $scope.selectedItems.findIndex(function(itm) { return itm == data.item; }); if (selected == -1) { $scope.selectedItems.push(data.item); } else { $scope.selectedItems.splice(selected, 1); } }; $scope.filter = function() { if (!$scope.searchField) { $scope.data2Show = angular.copy($scope.data); } else { $scope.data2Show = []; $scope.data.map(function(itm) { if (itm.item.indexOf($scope.searchField) != -1) { $scope.data2Show.push(itm); } }); } }; $scope.isChecked = function(data) { var selected = $scope.selectedItems.findIndex(function(itm) { return itm == data.item; }); if (selected == -1) { return false; } else { return true; } } $scope.data2Show = []; $scope.data = [{ item: "a", /*"category": "x",*/ flag: false }, { item: "b", /*"category": "y",*/ flag: false }, { item: "c", /*"category": "x",*/ flag: false }, { item: "d", /*"category": "y",*/ flag: false } ]; $scope.filter(); }); ul li { list-style: none; text-align: center; } #category { text-align: center; background: #ddd; } #listContainer { width: 20%; } span { cursor: pointer; } <html lang="en" ng-app="myApp"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script> <link rel="stylesheet" href="stylesheet/style.css"> </head> <body ng-controller="myCtrl"> <input type="text" ng-click="openSelect()"> <div id="selectContainer" ng-show="selectEnable"> <div>{{selectedItems.toString()}}</div> <input type="text" id="searchField" ng-model="searchField" ng-change="filter()"> <div id="listContainer"> <ul> <li ng-repeat="data in data2Show"> <input type="checkbox" ng-change="itemChecked(data)" name="select" ng-model="data.flag" ng-checked="isChecked(data)"> {{data.item}} </li> </ul> </div> </div> </body> </html> There are some prepared directives for multi-selecting. for example this one Angular-strap selects
unknown
d17477
val
Usually, such things happen when you didn't require vendor/autoload.php, or autoload wasn't generated. IDE may show you that everything is OK just because it parsed your composer.json. Try to: * *composer update *get sure you required vendor/autoload.php in your script
unknown
d17478
val
Seems to me you are missing a semicolon after requiring the typeahead.
unknown
d17479
val
Your first example is correct and absolutely should work: var contacts = db.vMyView.OrderBy(c => c.LastName).ThenBy(c => c.FirstName); // not sure why you need to reorder. Which could distort previous sorting contacts = contacts.OrderBy(orderExpressions[sortExpression]).ThenBy(orderExpressions["FirstName"]); Something looks off in your second example. OrderBy and ThenBy are already ascending there's no need for the additional parameter. There are alternatives for descending which are suffixed appropriately: OrderByDescending and ThenByDescending.
unknown
d17480
val
I reckon you should be able to create a new scheme to run your UI Tests and uncheck unit tests from the Test action in Edit Scheme. Later you can configure your new bot settings be specifying the UI Test scheme, selecting the "Perform test action" and select the iOS9 devices connected to your server. You can continue to run unit tests with existing bot on all iOS devices and simulators.
unknown
d17481
val
I think you may just be looking for var varType *os.File tpe := reflect.TypeOf(varType).Elem() fmt.Println(tpe == reflect.TypeOf(somevar).Elem())
unknown
d17482
val
You can simply create a boolean for show/hide and toggle it on your click method like. scope.get_menu_items = function(folder){ //if folder.folder exist means we don't need to make $http req again if(folder.folders){ $scope.showFolder = !$scope.showFolder } else{ http.get("/api/folders/" + folder.id).success(function(data){ folder.folders = data.data.folders; folder.files= data.data.files; $scope.showFolder = true; }) } } and add ng-if on your view like. <span ng-click="get_menu_items(folder)> <i class="fa fa-folder-o"></i> {{ folder.name }} </span> <ul ng-if="showFolder"> <li class="item" ng-repeat="file in folder.files"> <label> <input type="checkbox" name="file_map[]" value="{{ file.id }}" ng-model="file_map[file.id]" ng-click="update_selection(file.id)"/> <i class="fa fa-file-o"></i> <span>{{ file.name }}</span> </label> </li> <li menuitem ng-repeat="folder in folder.folders" ng-model="folder"></li> </ul> Hope it helps. A: Add a global variable in controller as scope. Outside controller, add a variable (for example called: toggleVariable) and assign it to false. Inside controller put this: scope.toggleVariable = !scope.toggleVariable; In HTML, add to ul tag: ng-show="toggleVariable". Give it a try
unknown
d17483
val
But how about declare a fundamental type (e.g., int, double or float)? Declaring POD type objects won't cause an exception to be thrown. Constructors of non-POD types can throw exceptions. Only the documents/source code of those types can help you figure out whether that will happen for a particular type. A: It is the constructor of std::condition_variable that can throw an exception. Primitive types like int and double do not have any constructors. They simply have some stack space allocated for them and that's it, plus a value being written if you initialize the variable. The only way this could cause an exception is if you overflow the stack and the ensuing undefined behaviour happens to throw one. A: POD types typically are initialized with initializer expressions instead of constructors. Like constructors, initializers can throw exceptions. But if you have neither a constructor nor an initializer, there's no code associated with the definition and therefore also no possibility for that code to throw.
unknown
d17484
val
The FlatList component expects an array input for the data prop. Based on your JSON format, it appears you're passing in an object rather than an array. Consider the following adjustment to your render method: // Convert object to array based on it's values. If favPro not // valid (ie during network request, default to an empty array) const data = this.state.favPro ? Object.values(this.state.favPro) : [] <FlatList data={data} renderItem={this.fav} keyExtractor={item => item.pro_id} /> A: You're using async / await incorrectly. Instead of calling .then you assign your call to await to a variable (or don't assign it if it does not return a value) and wrap the call (or calls) to await in a try / catch block. The await keyword will automatically handle resolve and reject so you get the appropriate information. retrieveData = async () => { try { const data = JSON.parse(await AsyncStorage.getItem("userFavorites")) this.setState({ favPro: data }) } catch (error) { console.error(error) this.setState({ favPro: [] }) } } You also need to pass an array, the shape of your data looks like an object, but it should be an array of objects. This is not a terribly difficult transformation and I can provide a helper function if you need it. edit: if you need to convert an object into an array, you can use the reduce function const data = { '44': { a: 2 }, '55': { b: 3 }, } const dataArr = Object.keys(data).reduce( (arr, key) => arr.concat(data[key]), [] ) By using Object.keys we can each object by name. Then call reduce and the array returned by Object.keys, passing a function as the first argument, and an empty array as the second argument. The second argument is automatically passed to the function as the first argument, arr, and the second argument of the function we pass is the key of the object. Then it's just a matter of adding the objects to the array using concat. Array.reduce can seem a little overwhelming at first but it's a very powerful method and you can get a lot done with it.
unknown
d17485
val
I think your onResponse should use List<SearchModel> instead of SearchModel. Your response format is array.
unknown
d17486
val
What is the datatype of [therapist ID]? There seems to be a datatype mismatch with the value of therid. A: In that case maybe you are just missing a # matchstr_t = "[appt date]= #" & appt(j) & "# AND [appt time] = #" & slottime & "# AND [therapist ID] = #" & therid
unknown
d17487
val
For Basic Auth where the credentials are sent on each request it's expected. In order for the ServiceClient to retain the Session cookies that have been authenticated you should set the RememberMe flag when you authenticate, e.g using CredentialsAuthProvider: var client = new JsonServiceClient(BaseUrl); var authResponse = client.Send(new Authenticate { provider = "credentials", UserName = "user", Password = "p@55word", RememberMe = true, }); Behind the scenes this attaches the user session to the ss-pid cookie (permanent session cookie), which the client retains and resends on subsequent requests from that ServiceClient instance.
unknown
d17488
val
Normally, in an axios request, the data comes in results.data Also, because you don't return anything inside .map, it will just be an array of undefined. You need to return inside .map componentDidMount() { const cluster = '...'; const index= '...'; const field= '...'; const paragraphs = uuids.map(uuid => { // Get the results. // ADDED RETURN INSIDE .map return getResults(cluster, index, field, uuid, 'source') .then(results => { // Get value with console.log OK. console.log(results); // Return a undefined value... return results; }) .catch(error => { console.error(error); }); }); And if you want to get the data from paragraphs, you need to use Promise.all or async/await for it to work.
unknown
d17489
val
Welcome to SO. Although this is definitely not efficient for a small tuple, for a large one this will speed up the process greatly (from an O(n^2) solution to an O(n)). I hope this helps. x = (2, 3, 4, 5) y = ((2, 3), (3.5, 4.5), (6, 9), (4, 7)) for a, b in enumerate(y): if b[0] <= x[a] <= b[1]: print(f'{x[a]} is in between {b}.') else: print(f'{x[a]} is not in between {b}') For boolean values: interval = lambda t, i: [b[0] <= t[a] <= b[1] for a, b in enumerate(i)] x = (2, 3, 4, 5) y = ((2, 3), (3.5, 4.5), (6, 9), (4, 7)) print(interval(x, y)) All within linear (O(n)) time! Thanks for reading and have a great day. A: You can achieve this in linear time using one loop. You only have to iterate once on both of the tuples, something like this: x = (2, 3, 4, 5) y = ((2,3), (3.5, 4.5), (6, 9), (4, 7)) for index, number in enumerate(x): if number > y[index][1] or number < y[index][0]: print(f'{number} is NOT in {y[index}') else: print(f'{number} is in {y[index]}') the output is: 2 is in the interval (2, 3) 3 is NOT in the interval (3.5, 4.5) 4 is NOT in the interval (6, 9) 5 is in the interval (4, 7) As i said, this solution will take O(n), instead of O(n^2) A: What about something like this >>> x = (2, 3, 4, 5) >>> y = ((2,3), (3.5, 4.5), (6, 9), (4, 7)) >>> def f(e): ... p, (q, r) = e ... return q <= p <= r >>> list(map(f, zip(x,y))) [True, False, False, True]
unknown
d17490
val
By default, UIImageViews do not have user interaction enabled. Try setting your UIImageView's user interaction enabled to "YES": [myImageView setUserInteractionEnabled:YES];
unknown
d17491
val
Indeed the expm's package does use exponentiation by squaring. In pure r, this can be done rather efficiently like so, "%^%" <- function(mat,power){ base = mat out = diag(nrow(mat)) while(power > 1){ if(power %% 2 == 1){ out = out %*% base } base = base %*% base power = power %/% 2 } out %*% base } Timing this, m0 <- diag(1, nrow=3,ncol=3) system.time(replicate(10000, m0%^%4000))#expm's %^% function user system elapsed 0.31 0.00 0.31 system.time(replicate(10000, m0%^%4000))# my %^% function user system elapsed 0.28 0.00 0.28 So, as expected, they are the same speed because they use the same algorithm. It looks like the overhead of the looping r code does not make a significant difference. So, if you don't want to use expm, and need that performance, then you can just use this, if you don't mind looking at imperative code. A: A shorter solution with eigenvalue decomposition: "%^%" <- function(S, power) with(eigen(S), vectors %*% (values^power * t(vectors))) A: If A is diagonizable, you could use eigenvalue decomposition: matrix.power <- function(A, n) { # only works for diagonalizable matrices e <- eigen(A) M <- e$vectors # matrix for changing basis d <- e$values # eigen values return(M %*% diag(d^n) %*% solve(M)) } When A is not diagonalizable, the matrix M (matrix of eigenvectors) is singular. Thus, using it with A = matrix(c(0,1,0,0),2,2) would give Error in solve.default(M) : system is computationally singular. A: The expm package has an %^% operator: library("sos") findFn("{matrix power}") install.packages("expm") library("expm") ?matpow set.seed(10);t(matrix(rnorm(16),ncol=4,nrow=4))->a a%^%8 A: Although Reduce is more elegant, a for-loop solution is faster and seems to be as fast as expm::%^% m1 <- matrix(1:9, 3) m2 <- matrix(1:9, 3) m3 <- matrix(1:9, 3) system.time(replicate(1000, Reduce("%*%" , list(m1,m1,m1) ) ) ) # user system elapsed # 0.026 0.000 0.037 mlist <- list(m1,m2,m3) m0 <- diag(1, nrow=3,ncol=3) system.time(replicate(1000, for (i in 1:3 ) {m0 <- m0 %*% m1 } ) ) # user system elapsed # 0.013 0.000 0.014 library(expm) # and I think this may be imported with pkg:Matrix system.time(replicate(1000, m0%^%3)) # user system elapsed #0.011 0.000 0.017 On the other hand the matrix.power solution is much, much slower: system.time(replicate(1000, matrix.power(m1, 4)) ) user system elapsed 0.677 0.013 1.037 @BenBolker is correct (yet again). The for-loop appears linear in time as the exponent rises whereas the expm::%^% function appears to be even better than log(exponent). > m0 <- diag(1, nrow=3,ncol=3) > system.time(replicate(1000, for (i in 1:400 ) {m0 <- m0 %*% m1 } ) ) user system elapsed 0.678 0.037 0.708 > system.time(replicate(1000, m0%^%400)) user system elapsed 0.006 0.000 0.006 A: Simple solution `%^%` <- function(A, n) { A1 <- A for(i in seq_len(n-1)){ A <- A %*% A1 } return(A) }
unknown
d17492
val
The service can not be initialized using the constructor instead you should do it like this: protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { using (IServiceScope scope = _serviceProvider.CreateScope()) { var _localServiceManager = scope.ServiceProvider.GetRequiredService<IServiceManager>(); var ewr = _serviceManager.CountryService.GetAll(); _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); await Task.Delay(1000, stoppingToken); } } } This is an example of microsoft
unknown
d17493
val
If i get it correct, your situation is as follows: You have, for example, one application (EXE) which uses a shared library (DLL). From both, the EXE and the DLL, you want to be able to log. Last time i checked out the logog library i run in problems with the situation described above. Maybe now it is corrected? Under windows (only!), the logog library doesn't export any symbols - it is simply not ready to be used as DLL. This forces you to build and use logog as static library - which leads to problems with static variables inside the logog library which should exist only once, but in reality are existing as many times as the static library was linked to a module (EXE or DLL). The solution would be to build and use the logog library as DLL. Maybe this covers your problem and you may take the effort to export the symbols of the logog library. Or you could get in contact with the library writer.
unknown
d17494
val
Rather than extending ArrayBuffer[Person] directly, you can use the pimp my library pattern. The idea is to make Persons and ArrayBuffer[Person] completely interchangeable. class Persons(val self: ArrayBuffer[Person]) extends Proxy { def names = self map { _.name } // ... other methods ... } object Persons { def apply(ps: Person*): Persons = ArrayBuffer(ps: _*) implicit def toPersons(b: ArrayBuffer[Person]): Persons = new Persons(b) implicit def toBuffer(ps: Persons): ArrayBuffer[Person] = ps.self } The implicit conversion in the Persons companion object allows you to use any ArrayBuffer method whenever you have a Persons reference and vice-versa. For example, you can do val l = Persons(new Person("Joe")) (l += new Person("Bob")).names Note that l is a Persons, but you can call the ArrayBuffer.+= method on it because the compiler will automatically add in a call to Persons.toBuffer(l). The result of the += method is an ArrayBuffer, but you can call Person.names on it because the compiler inserts a call to Persons.toPersons. Edit: You can generalize this solution with higher-kinded types: class Persons[CC[X] <: Seq[X]](self: CC[Person]) extends Proxy { def names = self map (_.name) def averageAge = { self map (_.age) reduceLeft { _ + _ } / (self.length toDouble) } // other methods } object Persons { def apply(ps: Person*): Persons[ArrayBuffer] = ArrayBuffer(ps: _*) implicit def toPersons[CC[X] <: Seq[X]](c: CC[Person]): Persons[CC] = new Persons[CC](c) implicit def toColl[CC[X] <: Seq[X]](ps: Persons[CC]): CC[Person] = ps.self } This allows you to do things like List(new Person("Joe", 38), new Person("Bob", 52)).names or val p = Persons(new Person("Jeff", 23)) p += new Person("Sam", 20) Note that in the latter example, we're calling += on a Persons. This is possible because Persons "remembers" the underlying collection type and allows you to call any method defined in that type (ArrayBuffer in this case, due to the definition of Persons.apply). A: Apart from anovstrup's solution, won't the example below do what you want? case class Person(name: String, age: Int) class Persons extends ArrayBuffer[Person] object Persons { def apply(ps: Person*) = { val persons = new Persons persons appendAll(ps) persons } } scala> val ps = Persons(new Person("John", 32), new Person("Bob", 43)) ps: Persons = ArrayBuffer(Person(John,32), Person(Bob,43)) scala> ps.append(new Person("Bill", 50)) scala> ps res0: Persons = ArrayBuffer(Person(John,32), Person(Bob,43), Person(Bill,50))
unknown
d17495
val
Every render cycle the RenderComponent component is recreated, so it is mounted every render, and thus, mounts its children. Consider the following code where you render <Test /> directly, it's output is identical to {renderComponent()}. export default function App() { const [number, updateNumber] = useState(0); const renderComponent = () => { return <Test />; }; const RenderComponent = () => { return <Test />; }; useEffect(() => { updateNumber(1); updateNumber(2); }, []); useEffect(() => { console.log("every-render"); }); return ( <div className="App"> {/* {renderComponent()} */} {/* <RenderComponent /> */} <Test /> // <-- "Mounted Test", "every-render", "every-render" <h1>Rerender times: {number}</h1> </div> ); } The function renderComponent is executed and the return value is <Test />, thus equivalent to just rendering <Test /> directly, whereas RenderComponent is a new component each cycle. A: When diffing two trees, React first compares the two root elements. The behavior is different depending on the types of the root elements. Consider 3 cases: {renderComponent()} <RenderComponent /> <Test /> 1) {renderComponent()} Every render just return Test type, algorithm compares and sees that the type has not changed. Result: mount Test component 1 time. 2) <RenderComponent /> Every render return new component type RenderComponent, algorithm compares and sees RenderComponent1 type != RenderComponent2 type, and: Whenever the root elements have different types, React will tear down the old tree and build the new tree from scratch. Result: mount child Test component 2 times. Add console to mount RenderComponent: const RenderComponent = () => { useEffect(() => console.log('RenderComponent mount'), []); return <Test />; }; RenderComponent too mount 2 times. 3) <Test /> Similarly 1 case. Result: mount Test component 1 time.
unknown
d17496
val
A first attempt using table and cut: table(cut(x, breaks=seq(0,3,length.out=100))) It avoids the extra output, but takes about 34 seconds on my computer: system.time(table(cut(x, breaks=seq(0,3,length.out=100)))) user system elapsed 34.148 0.532 34.696 compared to 3.5 seconds for hist: system.time(hist(x, breaks=seq(0,3,length.out=100), plot=FALSE)$count) user system elapsed 3.448 0.156 3.605 Using tabulate and .bincode runs a little bit faster than hist: tabulate(.bincode(x, breaks=seq(0,3,length.out=100)), nbins=100) system.time(tabulate(.bincode(x, breaks=seq(0,3,length.out=100))), nbins=100) user system elapsed 3.084 0.024 3.107 Using tablulate and findInterval provides a significant performance boost relative to table and cut and has an OK improvement relative to hist: tabulate(findInterval(x, vec=seq(0,3,length.out=100)), nbins=100) system.time(tabulate(findInterval(x, vec=seq(0,3,length.out=100))), nbins=100) user system elapsed 2.044 0.012 2.055 A: Seems your best bet is to just cut out all the overhead of hist.default. nB1 <- 99 delt <- 3/nB1 fuzz <- 1e-7 * c(-delt, rep.int(delt, nB1)) breaks <- seq(0, 3, by = delt) + fuzz .Call(graphics:::C_BinCount, x, breaks, TRUE, TRUE) I pared down to this by running debugonce(hist.default) to get a feel for exactly how hist works (and testing with a smaller vector -- n = 100 instead of 1000000). Comparing: x = runif(100, 2.5, 2.6) y1 <- .Call(graphics:::C_BinCount, x, breaks + fuzz, TRUE, TRUE) y2 <- hist(x, breaks=seq(0,3,length.out=100), plot=FALSE)$count identical(y1, y2) # [1] TRUE
unknown
d17497
val
Scala's "f interpolator" is useful for this: x.foreach { case (text, price, amount) => println(f"$amount x $text%-40s $$${price*amount}") } // prints: 1 x (Burger and chips,4.99) $4.99 2 x (Pasta & Chicken with Salad,8.99) $17.98 2 x (Rice & Chicken with Chips,8.99) $17.98
unknown
d17498
val
Update package -> connect-mongo Then change the code of index.js-> const MongoStore = require('connect-mongo'); store: MongoStore.create( { mongoUrl: 'mongodb://localhost/codeial_development', mongooseConnection: db, autoRemove: 'disabled' } It will work 100%
unknown
d17499
val
A naive approach would truncate the creation timestamp to date, then compare: where date(m.create_dtm) = current_date - interval 1 day But it is far more efficient to use half-open interval directly against the timestamp: where m.create_dtm >= current_date - interval 1 day and m.create_dtm < current_date A: You can try next queries: SELECT m.meeting_id, m.member_id, m.org_id, m.title, m.create_dtm FROM meeting m -- here we convert datetime to date for each row -- it can be expensive for big table WHERE date(create_dtm) = DATE_SUB(CURDATE(), INTERVAL 1 DAY); SELECT m.meeting_id, m.member_id, m.org_id, m.title, m.create_dtm FROM meeting m -- here we calculate border values once and use them WHERE create_dtm BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 DAY) AND DATE_SUB(CURDATE(), INTERVAL 1 SECOND); Here live fiddle: SQLize.online
unknown
d17500
val
Data can be passed between forms in different ways. Here's a good tutorial on how to do that.The Constructor and Property approach is easier to implement. You dont seem to be saving the orderid on the form1 class Declare a variable for the OrderID on Form1 class string OrderId; Modify your exisiting Method public string orderNumber() { OrderId = "ORD" + OrderId + DateTime.Now.Year; } And then follow the Constructor Approach to pass over the value to PrintForm Again declare a variable for orderID inside the PrintForm class string OrderId; Change your PrintForm Constructor to this public PrintForm(string value) { InitializeComponent(); OrderId=value; } on Form1 Button click event private void button1_Click(object sender, System.EventArgs e) { PrintForm frm=new PrintForm(OrderId); PrintForm.Show(); } A: Create a container class with a static property in the same namespace: class clsDummy { internal static string ptyValue { get; set; } } you can assign this property where you are getting order id: public string orderNumber() { string ord = "ORD" + get_next_id() + DateTime.Now.Year; clsDummy.ptyValue =ord ; return ord; } after that where ever you want to access just check value inside : clsDummy.ptyValue
unknown