_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d12701
train
Amazon RDS is a database server, just like any other. If you start up an RDS MySQL server, you can connect to it from anything else that can connect to a MySQL server. The difference is that you do not have direct host access to the RDS server. Meaning, you cannot SSH into it and get a command prompt. But you can connect to it from any MySQL client, including MySQL Workbench.
unknown
d12702
train
Change the sample argument to reflect the variable inside the data. Air_time <- flights[, "air_time"] # Or select a random sample to save time ggplot(data = Air_time, mapping = aes(sample = air_time)) + stat_qq_band() + stat_qq_line() + stat_qq_point()
unknown
d12703
train
layout_constraintBottom_toBottomOf and other layout_constraint... won't work inside RelativeLayout, these are desired to work with ConstraintLayout as strict parent. if you want to align two Views next to/below/above inside RelativeLayoyut you have to use other attributes, e.g. android:layout_below="@+id/starFirst" android:layout_above="@+id/starFirst" android:layout_toRightOf="@id/starFirst" android:layout_toLeftOf="@id/starFirst" note that every attr which starts with layout_ is desired to be read by strict parent, not by View which have such attrs set. every ViewGroup have own set of such edit: turned out that this is an elevation case/issue (Z axis), so useful attributes are android:translationZ="100dp" android:elevation="100dp"
unknown
d12704
train
These extension methods should provide needed mapping: using var db = ConnectionFactory.Instance.GetMainDB(); await db.SomeEntityTable .Where(e => e.ID == dto.ID) .AsUpdatable() .Set(dto, projectExpr) // new extension method .Set(e => e.LastEditedAt, DateTime.Now()) .UpdateAsync(); await db.SomeEntityTable .AsValueInsertable() .Values(dto, projectExpr) // new extension method .Value(e => e.LastEditedAt, DateTime.Now()) .InsertAsync(); And implementation: public static class InsertUpdateExtensions { private static MethodInfo _withIUpdatable = Methods.LinqToDB.Update.SetUpdatableExpression; private static MethodInfo _withIValueInsertable = Methods.LinqToDB.Insert.VI.ValueExpression; public static IUpdatable<TEntity> Set<TEntity, TDto>( this IUpdatable<TEntity> updatable, TDto obj, Expression<Func<TDto, TEntity>> projection) { var body = projection.GetBody(Expression.Constant(obj)); var entityParam = Expression.Parameter(typeof(TEntity), "e"); var pairs = EnumeratePairs(body, entityParam); foreach (var pair in pairs) { updatable = (IUpdatable<TEntity>)_withIUpdatable.MakeGenericMethod(typeof(TEntity), pair.Item1.Type) .Invoke(null, new object?[] { updatable, Expression.Lambda(pair.Item1, entityParam), Expression.Lambda(pair.Item2) })!; } return updatable; } public static IValueInsertable<TEntity> Values<TEntity, TDto>( this IValueInsertable<TEntity> insertable, TDto obj, Expression<Func<TDto, TEntity>> projection) { var body = projection.GetBody(Expression.Constant(obj)); var entityParam = Expression.Parameter(typeof(TEntity), "e"); var pairs = EnumeratePairs(body, entityParam); foreach (var pair in pairs) { insertable = (IValueInsertable<TEntity>)_withIValueInsertable.MakeGenericMethod(typeof(TEntity), pair.Item1.Type) .Invoke(null, new object?[] { insertable, Expression.Lambda(pair.Item1, entityParam), Expression.Lambda(pair.Item2) })!; } return insertable; } private static IEnumerable<Tuple<Expression, Expression>> EnumeratePairs(Expression projection, Expression entityPath) { switch (projection.NodeType) { case ExpressionType.MemberInit: { var mi = (MemberInitExpression)projection; foreach (var b in mi.Bindings) { if (b.BindingType == MemberBindingType.Assignment) { var assignment = (MemberAssignment)b; foreach (var p in EnumeratePairs(Expression.MakeMemberAccess(entityPath, assignment.Member), assignment.Expression)) { yield return p; } } } break; } case ExpressionType.New: { var ne = (NewExpression)projection; if (ne.Members != null) { for (var index = 0; index < ne.Arguments.Count; index++) { var expr = ne.Arguments[index]; var member = ne.Members[index]; foreach (var p in EnumeratePairs(Expression.MakeMemberAccess(entityPath, member), expr)) { yield return p; } } } break; } case ExpressionType.MemberAccess: { yield return Tuple.Create(projection, entityPath); break; } default: throw new NotImplementedException(); } } }
unknown
d12705
train
For c++ code, the command is usually something like: g++ Main.cpp -o FileNameToWriteTo Alternatively, if you just run g++ Main.cpp it will output to a default file called a.out. Either way, you can then run whichever file you created by doing: ./FileNameToWriteTo.out See this for more details: http://pages.cs.wisc.edu/~beechung/ref/gcc-intro.html
unknown
d12706
train
For HTML parsing, I'd suggest jsoup: jsoup is a Java library for working with real-world HTML. It provides a very convenient API for extracting and manipulating data, using the best of DOM, CSS, and jquery-like methods. jsoup implements the WHATWG HTML5 specification, and parses HTML to the same DOM as modern browsers do. A: After some searching I found Jericho. I use XPath with the help of this article and Jaxen I'm just not sure if this is the best way...
unknown
d12707
train
I found the answer here: If your ultimate aim is just to resign the first responder, this should work: [self.view endEditing:YES] The endEditing(_:) method is designed right for it Causes the view (or one of its embedded text fields) to resign the first responder status. A: UIViewController inherits from UIResponder so a naive way (I am pretty sure is not the smartest way to do it) would be by overwriting the following methods (at least 1 of them) – touchesBegan:withEvent: – touchesMoved:withEvent: – touchesEnded:withEvent: - touchesCancelled:withEvent: Next you could get the touched view by doing UITouch *touch = [touches anyObject]; UIView *touchedView = [touch view]; finally resign the first responder if that view is not your text field if(touchedView != textField){ [textField resignFirstResponder]; } _ Demerits of this approach: You will have to handle the "tap" by yourself. (Same problem as the old iOS 3.1 or earlier). You will have to come up with your own implementation to differentiate single taps from drags, swipes, double taps, long taps, etc. Is not hard to get it working well but it is not likely you get it exactly the same way Apple detects taps (timings, distances, thresholds count!) However, that depends on your needs. If your view structure is simple enough then you could add a gesture recognizer to the container view and resign the first responder every time the handler is called :) Hope this helps A: Nobody has yet presented the best answer here: [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil]; From the documentation on this method: Normally, this method is invoked by a UIControl object that the user has touched. The default implementation dispatches the action method to the given target object or, if no target is specified, to the first responder. Subclasses may override this method to perform special dispatching of action messages. I bolded the relevant part of that paragraph. By specifying nil for the to: parameter, we automatically call the given selector on the first responder, wherever it is, and we don't need to have any knowledge of where in the view hierarchy it is. This can also be used to invoke other methods on the first responder as well, not just cause it to resign first responder status. A: -(BOOL)textFieldShouldReturn:(UITextField *)textField { [self.TextField resignFirstResponder]; return YES; } A: Give a unique Tag to your UITextfield (i.e. 333), then to resign the first responder do this: UITextField *textField = (UITextField *)[self.view viewWithTag:333]; [textField resignFirstResponder]; A: For a more robust and clean solution add a tap gesture recognizer to your primary view. This will work better with nested views and will be cleaner than secret buttons in code and UI builder. In your view did load: UITapGestureRecognizer* tapBackground = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard:)]; [tapBackground setNumberOfTapsRequired:1]; [self.view addGestureRecognizer:tapBackground]; ..and define your target action to be triggered on tap: -(void) dismissKeyboard:(id)sender { [self.view endEditing:YES]; } A: The best option is the shortest way ;) - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self.view endEditing:YES]; } A: Using Swift you can do this: func viewDidLoad() { super.viewDidLoad() let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.hideKeyboardByTappingOutside)) self.view.addGestureRecognizer(tap) } @objc func hideKeyboardByTappingOutside() { self.view.endEditing(true) } A: Just create an IBOutlet or pointer to the text field and call [textField resignFirstResponder]; from where ever you want. A: UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapTodissmiss)]; [self.view addGestureRecognizer:tap]; and selector -(void)TapTodissmiss{ [self.txtffld resignFirstResponder]; } A: I am posting this as a separate answer because a lot of the other answers recommend using [textField resignFirstResponder]. This is causing an invalid capability error in Xcode 11.5 with the incomprehensible addition "Unable to insert COPY_SEND" On a iPad with iOS 9.3.6: 2020-05-23 20:35:01.576 _BSMachError: (os/kern) invalid capability (20) 2020-05-23 20:35:01.580 _BSMachError: (os/kern) invalid name (15) On a iPad with iPadOS 13.5: 2020-05-23 20:38:49 [Common] _BSMachError: port 12f0f; (os/kern) invalid capability (0x14) "Unable to insert COPY_SEND" On a iPhone with iOS 13.5: 2020-05-23 20:43:34 [Common] _BSMachError: port d503; (os/kern) invalid capability (0x14) "Unable to insert COPY_SEND" [textField resignFirstResponder] cannot be used anymore. A: When possible the best option is to make your UIView to inherit from UIButton instead. You just need to change it in Interface Builder and immediately you will get the options to create an Action "Touch Up Inside" like any other button. Your view will work as usual because UIButton is still a view but you will get notified when someone taps on the view. There you can call [self.view endEditing:YES]; To resign any keyboard. Please note that if your view is an UIScrollView this solution is not for you. A: Create your IBOutlet in ViewController.h file like below: //YOUR ViewController.h FILE #import <UIKit/UIKit.h> @interface ViewController : UIViewController { //WIRE THIS WITH YOUR UITextField OBJECT AT YOUR .xib FILE IBOutlet UITextField *yourIBOutletUITextField; } @end Add this to your ViewController.m file: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ [yourIBOutletUITextField resignFirstResponder]; } like below: //YOUR ViewController.m FILE #import "ViewController.h" @implementation ViewController //ADD THIS METHOD BELOW - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ [yourIBOutletUITextField resignFirstResponder]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } #pragma mark - View lifecycle - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } @end A: For my implementation, [self.view endEditing:YES] did not work. To finally make sure the keyboard was hidden, I had to make one of my views the first responder, and then immediately make it resign as per the function below: -(void) hideKeyboardPlease{ [uiTextTo becomeFirstResponder]; [uiTextTo resignFirstResponder]; } A: This is what I do... UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideAllKeyboards)]; tapGesture.cancelsTouchesInView = NO; [self.view addGestureRecognizer:tapGesture]; -(void) hideAllKeyboards { [textField_1 resignFirstResponder]; [textField_2 resignFirstResponder]; [textField_3 resignFirstResponder]; . . . [textField_N resignFirstResponder]; } A: This is the easiest way iv found that works consistently. Just add a tap gesture recognizer on the view and you're good to go. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self.view endEditing:YES]; } A: Update I found another simple way simply declare a property :- @property( strong , nonatomic) UITextfield *currentTextfield; and a Tap Gesture Gecognizer:- @property (strong , nonatomic) UITapGestureRecognizer *resignTextField; In ViewDidLoad _currentTextfield=[[UITextField alloc]init]; _resignTextField=[[UITapGestureRecognizer alloc]initWithTarget:@selector(tapMethod:)]; [self.view addGestureRecognizer:_resignTextField]; Implement the textfield delegate method didBeginEditing -(void)textFieldDidBeginEditing:(UITextField *)textField{ _currentTextfield=textField; } Implement Your Tap Gesture Method (_resignTextField) -(void)tapMethod:(UITapGestureRecognizer *)Gesture{ [_currentTextfield resignFirstResponder]; } A: Create a big button behind it all, and the button's callback calls resignFirstResponder to every input you have. Just make sure to put everything that the user interacts with on top of the button. Of course the button will be custom rect and transparent. I would look into implementing an IBOutletCollection called resignables and set every input to that collection. And the button callback iterates over that collection calling resignFirstResponder to them all. Edit: if it is a re-sizable scroll view, remember to correctly set the re-size markers in the button's view option, that way the button will always expand and contract to the scrollview's height and width
unknown
d12708
train
You are inserting your data inside a <pre> block, effectively telling the browser not to wrap the text. I assume you do this so that literal newlines in the 'note' data are indeed printed. To alter wrapping space-characters and newline functionality of an element, you can use the CSS white-space property. So, to get what you want (both wrapping AND literal newlines), you can set white-space to either pre-line or pre-wrap, depending on your need. Eg. change the <pre> to ...<pre style="white-space:pre-wrap;">' . base64_decode($eval['note']) . '</pre>... See the reference for more details Good luck, bob
unknown
d12709
train
Please can you provide sample data? You can do something like: SELECT DateIncrement = SUM(DATEADD(D,@CNT,@WEEK)) OVER (ORDER BY officeID) FROM... This gets an incremented date value for each record which you can then check against your start and end dates. A: This is making a number of assumption because you didn't post ddl or any consumable sample data. Also, there is a variable @lvCounter not defined in your code. This is perfect opportunity to use a tally or numbers table instead of a loop. declare @lvCounter int = 42; DECLARE @CNT INT = 0, @WEEK DATE = '2015-11-01', @FLAG INT; WITH E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)) , cteTally(N) AS ( SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E1 ) select 5134 as officeId , @lvCounter as Id , DATEADD(DAY, N - 1, @WEEK) as weekDate , '09:00 AM' as startsOn , '05:00 PM' as EndOn , Flag from cteTally t cross apply ( select CAST(count(*) as bit) as Flag from YearRange where DATEADD(Day, t.N, @WEEK) > CONVERT(DATE,taxseasonbegin) AND DATEADD(Day, t.N, @WEEK) <= CONVERT (DATE,taxSeasonEnd) ) y where t.N <= 7; A: You could try some Kind of this one. This gives you the data I think you Need for your insert. I do not have a table named YEARRANGE so I couldn't test it completely DECLARE @CNT INT = 0, @WEEK DATE = '2015-11-01', @FLAG INT; CREATE TABLE #Tmpdata (officeId int,id smallint, weekDate date,startsOn varchar(10),endsOn varchar(10),flag bit); WITH CTE AS ( SELECT num AS cnt, DATEADD(D, SUM(num) OVER(ORDER BY num ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) , @WEEK) AS [week] FROM ( SELECT ROW_NUMBER() OVER (ORDER BY nl) -1 AS num FROM (SELECT NULL AS nl UNION ALL SELECT NULL AS nl UNION ALL SELECT NULL AS nl UNION ALL SELECT NULL AS nl UNION ALL SELECT NULL AS nl UNION ALL SELECT NULL AS nl UNION ALL SELECT NULL AS nl ) AS ni ) AS no ) INSERT INTO #Tmpdata (officeId,id,weekDate,startsOn,endsOn,flag) SELECT 5134 AS officeID, cnt AS id, [week],'09:00 AM' AS startsOn,'05:00 PM' AS endsOn, COALESCE(A1.flag,0) AS flag FROM CTE OUTER APPLY (SELECT 1 FROM YEARRANGE WHERE [week] BETWEEN CONVERT(DATE,taxseasonbegin) AND CONVERT (DATE,taxSeasonEnd) ) AS A1(flag);
unknown
d12710
train
You list object names look strange ', , RF, RUN1, PA1' but you should be able to access them using index. e.g. roc_value[[1]], roc_value[[2]]... etc so, then further to select Testing.data would be simply as roc_value[[1]]['Testing.data']
unknown
d12711
train
Define: template<typename ...> struct types; Then: template <typename... Args> struct Entity { struct Inner { typedef types<Args...> entity_args_t; }; struct SomeOtherInner { typedef types<Args...> entity_args_t; }; }; Then you can pass entity_args_t to a template that has a partial specialization for types<T...>. If you typedef the Entity, you can instead write a partial specialization for Entity<T...>, which may make more sense for your case template <typename... Args> struct Entity { struct Inner { // Equivalent: typedef Entity entity_args_t; typedef Entity<Args...> entity_args_t; }; struct SomeOtherInner { typedef Entity<Args...> entity_args_t; }; }; So having a typedef for entity_args_t equal Entity<Args...>, you could write this as follows (untested, but should work): template<typename ProbablyInner, typename ProbablyEntity> struct is_inner_impl : std::false_type { }; template<typename ProbablyInner, typename ...Args> struct is_inner_impl<ProbablyInner, Entity<Args...>> : std::is_same< typename Entity<Args...>::Inner ProbablyInner> { }; template<typename ProbablyInner, typename = std::true_type> struct is_inner : std::false_type { }; template<typename ProbablyInner> struct is_inner<ProbablyInner, std::integral_constant<bool, is_inner_impl< ProbablyInner, typename ProbablyInner::entity_args_t>::value>> : std::true_type { };
unknown
d12712
train
The ArithmeticException is thrown because your division leads to a non terminating decimal, if you explicitly provide the method with a rounding mode, this exception will no longer be thrown. So, try this BigDecimal average = total.divide(test_count, RoundingMode.HALF_UP);
unknown
d12713
train
Here's an example, although the links in comments point to similar approaches. Grab a shapefile: download.file(file.path('http://www.naturalearthdata.com/http/', 'www.naturalearthdata.com/download/50m', 'cultural/ne_50m_admin_1_states_provinces_lakes.zip'), {f <- tempfile()}) unzip(f, exdir=tempdir()) Plotting: library(rgdal) shp <- readOGR(tempdir(), 'ne_50m_admin_1_states_provinces_lakes') plot(subset(shp, admin=='Australia'), col=sample(c('#7fc97f', '#beaed4', '#fdc086', '#ffff99'), 9, repl=TRUE)) opar <- par(plt=c(0.75, 0.95, 0.75, 0.95), new=TRUE) plot.new() plot.window(xlim=c(0, 1), ylim=c(0, 1), xaxs='i', yaxs='i') rect(0, 0, 0.5, 0.5, border=NA, col='#7fc97f') rect(0.5, 0, 1, 0.5, border=NA, col='#beaed4') rect(0, 0.5, 0.5, 1, border=NA, col='#fdc086') rect(0.5, 0.5, 1, 1, border=NA, col='#ffff99') points(runif(100), runif(100), pch=20, cex=0.8) box(lwd=2) par(opar) See plt under ?par for clarification. A: This is how I did it in the past grid.newpage() vp <- viewport(width = 1, height = 1) submain <- viewport(width = 0.9, height = 0.9, x = 0.5, y = 1,just=c("center","top")) print(p, vp = submain) subvp2 <- viewport(width = 0.2, height = 0.2, x = 0.39, y = 0.35,just=c("right","top")) print(hi, vp = subvp2) subvp1 <- viewport(width = 0.28, height = 0.28, x = 0.0, y = 0.1,just=c("left","bottom")) print(ak, vp = subvp1) in my case p, ak and hi were gg objects (maps created with ggplot) and I was inserting a small version of each near the main use map (p) - as it is typically done
unknown
d12714
train
Please use this Code $(document).ready(function() { $("span").each(function(){ if (parseInt($(this).text()) > 0){ $(this).removeClass("cart-summary__count"); $(this).addClass("cart-summary__count_full"); } }); }); Refer this Fiddle Edit Based on your edit, use the following code. HTML <div id="cart-summary"> <div class="cartContainer"> <span class="cart-summary__count" data-v-observable="cart-count">0</span> <a href class="cart">example.com</a> </div> <div class="cartContainer"> <span class="cart-summary__count" data-v-observable="cart-count">1</span> <a href class="cart">example1.com</a> </div> </div> JS $(document).ready(function() { $("span").each(function(){ if (parseInt($(this).text()) > 0){ $(this).parent().find('a').removeClass("cart"); $(this).parent().find('a').addClass("cart-full"); } }); }); CSS .cart-full { border : 2px solid red } .cartContainer { padding-top : 5px; } Refer New Fiddle A: Hope this is what you are looking for.I have removed id in your code as the id should be unique and i have added a class cart-summary for all the spans.Once you run the below code it will append the required classes. $('#cart .cart-summary').each(function(){ var span_value = parseInt($(this).text()); if(span_value == 0){ $(this).addClass('cart-summary__count'); } else{ $(this).addClass('cart-summary__count_full'); } }) .cart-summary__count{ color:green; } .cart-summary__count_full{ color:red; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="cart"> <span class="cart-summary" data-v-observable="cart-count">0</span> <span class="cart-summary" data-v-observable="cart-count">1</span> <span class="cart-summary" data-v-observable="cart-count">1</span> <span class="cart-summary" data-v-observable="cart-count">1</span> <span class="cart-summary" data-v-observable="cart-count">1</span> </div>
unknown
d12715
train
Angular by default reuses component if the route doesn't change (and redirect doesn't count as route change). Apart from implementing custom RouteReuseStrategy (which seems like an overkill here), the only idea I have is creating some kind of LogoutComponent attached to /logout path. That component would redirect user back to root during ngOnInit, or it could be guarded by AuthGuard, which will perform redirection.
unknown
d12716
train
you can install the Windows 8 SDK http://msdn.microsoft.com/en-us/windows/desktop/hh852363.aspx
unknown
d12717
train
You can do it with the Flexbox and @media queries: * {box-sizing: border-box} body {margin: 0} #container { width: 1200px; /* adjust */ max-width: 100%; /* responsiveness */ margin: 0 auto; /* horizontally centered on the page */ padding: 0 5px; /* adjust */ } h1 {text-align: center} #flex { display: flex; /* displays flex-items (children) inline */ flex-wrap: wrap; /* enables their wrapping */ margin: 0; } figure { display: flex; /* flex behavior also for figure elements */ flex-direction: column; /* stacks flex-items vertically */ justify-content: center; /* centers them vertically */ align-items: center; /* and horizontally */ flex: 0 1 calc(50% - 10px); /* initial width set to 50% - 10px (2 x 5px left & right padding) of the flex-container's (#flex) width */ margin: 5px; /* adjust */ } img { display: block; /* removes bottom margin/whitespace */ max-width: 100%; /* responsiveness */ } @media (max-width: 568px) { /* adjust */ #flex {flex-direction: column} } <div id="container"> <h1>title</h1> <div id="flex"> <figure id="r"> <img src="http://placehold.it/400x300" alt=""> <figcaption>caption</figcaption> </figure> <figure id="p"> <img src="http://placehold.it/400x300" alt=""> <figcaption>caption</figcaption> </figure> <figure id="c"> <img src="http://placehold.it/400x300" alt=""> <figcaption>caption</figcaption> </figure> <figure id="s"> <img src="http://placehold.it/400x300" alt=""> <figcaption>caption</figcaption> </figure> </div> </div>
unknown
d12718
train
The map is an array of N buckets. The put() method starts by calling hashCode() on your key. From this hash code, it uses a modulo to get the index of the bucket in the map. Then, it iterates through the entries stored in the linked list associated with the found bucket, and compares each entry key with your key, using the equals() method. If one entry has a key equal to your key, its value is replaced by the new value. Else, a new entry is created with the new key and the new value, and stored in the linked list associated with the bucket. Since Cat instances and String instances are never equal, a value associated with a String key will never be modified by putting a value associated with a Cat key. A: It will be defined by your object. You have to create a hashCode() and a equals() method so it can be stored in your hashtable. As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.) See the javadoc at java.lang.Object http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html#hashCode() or you can read this for an explanation http://www.javaworld.com/javaworld/javaqa/2002-06/01-qa-0621-hashtable.html I hope it helps A: Storing the value to HashMap depends on the hashcode() and equals() method.Please find the more reference from here. HashMap - hashcode() Example More information of HashMap get() retrieval of values.Here A: When a HashMap is used, the keys in it are unique. This uniqueness of the keys is checked in Java from the definition of the equals() and hashCode() methods that the class of the objects under consideration provides. This is done by comparing using the equals() method first and if it returns equal then comparing using hashCode().Also, you must be knowing that each reference pointing to an object has a bit pattern which may be different for multiple references referring to the same object. Hence, once the equals() test passes, the object won't be inserted into the map since the map should have unique keys. So, each hashCode value for objects which are keys in the map will form different buckets for a range of hashCode values and the object will be grouped accordingly. EDIT to provide an example: For example, let us consider that two objects have a String attribute with values "hello" and "hlleo" and suppose the hashCode() function is programmed such that the hash code of an object is the sum of the ASCII values of the characters in the String attribute and the equals() method returns true if the values of the String attribute are equal. So, in the above case, equals() return false as the strings are not equal but the hashCode will be same. So the two objects will be placed in the same hash code bucket. Hope that helps.
unknown
d12719
train
Do you have Salesforce CRM and Marketing Cloud Connect? If so, You could use Salesforce data extensions, and pass click and open data at the individual level or aggregate level. This way you could create easy-to-use reporting in Salesforce without having to write queries.
unknown
d12720
train
Known issues in Xcode 6.1: Localization and Keyboard settings (including 3rd party keyboards) are not correctly honored by Safari, Maps, and developer apps in the iOS 8.1 Simulator. [NSLocale currentLocale] returns en_US and only the English and Emoji keyboards are available. (18418630, 18512161) Problem exists since Xcode 6 GM
unknown
d12721
train
I found a possible Workaround, but this doesn't fix the problem: Including the following css-code hides the div-container containing the unbeloved checkboxes. <style type="text/css"> .dojoxGridView > .dijitCheckBox{ display: none; } </style> Unfortunately, this involeves the checkBoxes that are generated by the rowSelector-option within the DataGrid-declaration. So if you dont need the rowSeletion-feature (at least by checkboxes), this works. A: I had this problem many time and it is removed by including Grid.css and theme css. This can be remove by just playing with css.
unknown
d12722
train
sp_search_code is what I use to find any code items which are in the DB; however, what you need is a redgate tool which will index the db and help you search its contents. I will suggest as Just Aguy did, that you spend some time cleaning up those generic column names and any gen table names for that matter, good luck. http://vyaskn.tripod.com/sql_server_search_stored_procedure_code.htm
unknown
d12723
train
the problem is temporary solved. i you use all collations uf8_turkish_ci you can get correct result. but i am wondering why i have to use turkish_ci. try collate all columns utf8_turkish_ci, tables utf8_turkish_ci, and database too. good luck
unknown
d12724
train
Try this out: routes.MapRoute(null, "Login/{token}/{nameII}", new { controller = "InicioPareja", action = "Login" //, token = UrlParameter.Optional, nameII = UrlParameter.Optional } ,new {token = @"[0-9a-f]{12}",nameII = @"^\w{1,20}$" } );
unknown
d12725
train
Your arguement context is not a acitivity or fragment, and you need those two to call getSharedPreferences method. class PreferenceManager(context: Context) : PreferencesFunctions{
unknown
d12726
train
Try this PHP <?php $username = $_POST['username']; $password = $_POST['password']; if (isset($username) && isset($password)) { try { $connection = new PDO('mysql:host=localhost;dbname=dbname', $username, $password); // to close connection $connection = null; } catch (PDOException $e) { print "Error!: " . $e->getMessage() . "<br/>"; die(); } } ?> A: Try this maybe.... <html> <form action='LoginAction.php' method='POST'> Username: <input type='text' name='username'/><br/> Password: <input type='password' name='password'/><br/> Database: <input type='text' name='database'/><br/> <input type='submit' value='Login'/> </form> </html> And the php.... <?php $username = $_POST['username']; $password = $_POST['password']; $database = $_POST['database']; if (isset($username) && isset($password) && isset($database)) { $connect = mysql_connect("myphpadmin.net", $username, $password, $database) or die("Couldn't connect!"); mysql_select_db("users") or die("Coulnd't find db!"); } else { die("please fill in all fields."); } ?> A: In your edit you mentioned PDO, here's an example ! <?php $config['db'] = array( 'host' => 'yourHost(i.e. localhost)', 'username' => 'yourUsername', 'password' => 'yourPassword', 'dbname' => 'yourDBName' ); $db = new PDO('mysql:host=' . $config['db']['host'] . '; dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']); ?> Your login situation would be something in the likes of this: <?php include '../connection_file.php'; $username= $_GET['username']; $password = $_GET['password']; $select_query = "SELECT username, password FROM user WHERE username = :username AND password = :password"; $get_user = $db->prepare($select_query); $get_user->execute(array(':username' => $username, ':password' => $password)); $countRows = $get_user->rowCount(); if($countRows >= 1){ //The user is logged in //echo "true" or header('yourLocation') }else{ //The user doesn't exist //echo "true" or header('yourLocation') } ?> I Hope this helped ! EDIT Stupid mistake, maybe you want to encrypt the password, you can do so by doing: $password = $_GET['password']; $encrypt_password = md5($password); //As you guessed "md5" encrypts the password ;) Of course don't forget to also replace "$password" in your $get_user->execute(array) with $encrypt_password ! A: Also you can try this: $connect = mysql_connect("myphpadmin.net", $username, $password) or die("Couldn't connect!"); mysql_select_db($database, $connect) or die("Coulnd't find db!");
unknown
d12727
train
As per the Fragment testing page, you must use debugImplementation for the fragment-testing artifact: debugImplementation 'androidx.fragment:fragment-testing:1.2.0-alpha01'
unknown
d12728
train
I think the defaultEnvId attribute for the environment is set incorrectly in your server_name.conf file. Typically the defaultEnvId would look something like below- <engine id="rwEng" initEngine="1" minEngine="0" maxEngine="10" engLife="50" maxIdle="30" defaultEnvId="JP"/> And consecutively the definition as- <environment id="JP"> <envVariable name="NLS_LANG" value="Japanese_Japan.JA16SJIS"/> <envVariable name="NLS_CURRENCY" value="¥"/> <envVariable name="DISPLAY" value="MyServer.MyCompany.com:0.0"/> </environment> I am assuming that your file has the defaultEnvID="myenv" and <environment id="myenv">. Check this to make sure it points to the right environment. Make sure that the defaultEnvId in enginedefinition matches the environment definition. Also, keep in mind that this is an optional setting so you may or may not need this. See this for details.
unknown
d12729
train
How do you know if one car is faster than another? Drive both of them and compare the times. Generally, databases are more efficient at joining data than in-memory Linq (due to pre-computed indices, hashes, etc.) but there certainly could be cases where in-memory would be faster. However, when you're not pulling ALL of the data into memory, the benefit of having less data over the wire might make a bigger difference than any performance improvement in joining. So there's not a definitive answer. Start with something that works, THEN focus on performance improvements by measuring the time before and after the changes. A: One of the slower parts of executing a database query is the transport of the data from the DBMS to your local process. Hence it is wise to limit the amount of data to be transported to your process. Only transport the data you actually plan to use. So if you query "Teachers with their Students", you'll know that the ID of the teacher will equal the foreign key 'TeacherIdin everyStudent`. So why transport this foreign key for every of the teacher's 1000 students if you already know the value? Another reason to let the DBMS perform the query is because the software in the database is optimized to perform queries. If the DBMS created a temporary table for a query, and it detects that a new query needs the same temporary table, a smart DBMS will reuse this temporary table, even if the query came from another process. Smart DBMSes will detect that certain indexes are used more often than others, and keep them in memory, instead of reading them from disk all the time. So a DBMS has all kinds of tricks to speed up the execution of queries. You can see that this tricks help by measuring: perform a query twice in a row and see that the second query is executed faster than the first one. This effect is also a reason that you can't measure whether it is faster to let given query execute by the DBMS or to execute it in local memory., as some suggested. The only proper method would be to measure the chosen strategy with all kinds of queries during a longer period of time (minutes, if not hours), with a lot of processes that perform these queries. One thing you'll know for certain is that executing queries AsEnumerable can't benefit from the queries executed by others.
unknown
d12730
train
Your last code example is fine. Just use map() instead of subscribe() and subscribe at call site. You can use return http.post(...).toPromise(val => ...)) or return http.post(...).map(...).toPromise(val => ...)) to get the same behavior as in Angular where you can chain subsequent calls with .then(...)
unknown
d12731
train
Use std::codecvt_facet template to perform the conversion. You may use standard std::codecvt_byname, or a non-standard codecvt_facet implementation. #include <locale> using namespace std; typedef codecvt_facet<wchar_t, char, mbstate_t> Cvt; locale utf8locale(locale(), new codecvt_byname<wchar_t, char, mbstate_t> ("en_US.UTF-8")); wcout.pubimbue(utf8locale); wcout << L"Hello, wide to multybyte world!" << endl; Beware that on some platforms codecvt_byname can only emit conversion only for locales that are installed in the system. A: Well, after some testing I figured out that FILE is accepted for _iobuf (in the w*fstream constructor). So, the following code does what I need.#include <iostream> #include <fstream> #include <io.h> #include <fcntl.h> //For writing FILE* fp; _wfopen_s (&fp, L"utf-8_out_test.txt", L"w"); _setmode (_fileno (fp), _O_U8TEXT); wofstream fs (fp); fs << L"ąfl"; fclose (fp); //And reading FILE* fp; _wfopen_s (&fp, L"utf-8_in_test.txt", L"r"); _setmode (_fileno (fp), _O_U8TEXT); wifstream fs (fp); wchar_t array[6]; fs.getline (array, 5); wcout << array << endl;//For debug fclose (fp);This sample reads and writes legit UTF-8 files (without BOM) in Windows compiled with Visual Studio 2k8. Can someone give any comments about portability? Improvements? A: The easiest way would be to do the conversion to UTF-8 yourself before trying to output. You might get some inspiration from this question: UTF8 to/from wide char conversion in STL A: get FILE* or integer file handle form a std::basic_*fstream? Answered elsewhere. A: You can't make STL to directly work with UTF-8. The basic reason is that STL indirectly forbids multi-char characters. Each character has to be one char/wchar_t. Microsoft actually breaks the standard with their UTF-16 encoding, so maybe you can get some inspiration there.
unknown
d12732
train
You could use os.system, but subprocess.run is probably better. You should also use glob: import glob import subprocess files = glob.glob('*.wav') for file in files: subprocess.run(['xWMAEncode', file, file.replace('.wav', '.xwm')])
unknown
d12733
train
Simple solution: The formula needs to be a string that includes an "equals" (=) prefix. Cell E5 presently contains a formula (=E4) which yields: {FILTER(DBD!B2:F;LÆNGDE(DBD!B2:B)>0);FILTER(Platformen!B2:F;LÆNGDE(Platformen!B2:B)>0) Two things to note here: 1) the content is treated as text 2) there is no "equals sign" (=) at the beginning of the string. The content should look like this: ={FILTER(DBD!B2:F;LÆNGDE(DBD!B2:B)>0);FILTER(Platformen!B2:F;LÆNGDE(Platformen!B2:B)>0) How to fix it Edit Cell E5 (or Cell E4, whichever suits you) to insert an equals sign (=) to the left of the opening curly bracket. The result will still be treated as a string, so there is no danger involved ;) One proviso: I had to convert "LÆNGDE" to "LEN" in order for my test to work. But I think this is probably just an issue of "Display Language" which, for me, is English (Australia), and for you is probably Danish.
unknown
d12734
train
Read ReadMe file of Rest-client git, it has lots of examples showing different types of request. For your answer, try : url = "http://example.com" RestClient.post url,:param1=>foo, :param2=>bar
unknown
d12735
train
As you've said, package body without its specification is useless: SQL> create package body pkg_test as 2 procedure p_test; 3 end; 4 / Warning: Package Body created with compilation errors. SQL> show err Errors for PACKAGE BODY PKG_TEST: LINE/COL ERROR -------- ----------------------------------------------------------------- 0/0 PL/SQL: Compilation unit analysis terminated 1/14 PLS-00201: identifier 'PKG_TEST' must be declared 1/14 PLS-00304: cannot compile body of 'PKG_TEST' without its specification SQL> exec pkg_test.p_test; BEGIN pkg_test.p_test; END; * ERROR at line 1: ORA-06550: line 1, column 7: PLS-00201: identifier 'PKG_TEST.P_TEST' must be declared ORA-06550: line 1, column 7: PL/SQL: Statement ignored SQL> Therefore, I see no advantage(s) in having a package body. Perhaps it can be used as code graveyard - you know, there are some procedures and functions you wrote but you don't need them any more - create a package body and put all that code in there. You won't be able to use them, but will be able to have a look if necessary. Something like your own code repository stored in the database, instead of scattered all over your hard disk in different directories and different kind of files (.SQL, .PRC, .PKG, ...). A: I think the premise of the question is misleading and probably wrong.The Interviewer perhaps wanted you to know the difference between variables and procedures that are not defined in package specification and defined and called or used internally within the package body. A package body can be used to define local procedures and variables without them having defined inside package specification. create or replace package pkg_spec_test AS procedure p1; v_1 NUMBER := 10; END; / create or replace package body pkg_spec_test AS procedure p1 AS BEGIN dbms_output.put_line('HELLO. I can be called externally'); END p1; procedure p2 AS BEGIN dbms_output.put_line('I''m private to package body.'); END; procedure main as begin p2; --called within the body; END main; END pkg_spec_test; / begin pkg_spec_test.p1; end; / Works fine. HELLO. I can be called externally PL/SQL procedure successfully completed. begin pkg_spec_test.p2; end; / Causes error Error starting at line : 30 in command - begin pkg_spec_test.p2; end; Error report - ORA-06550: line 2, column 15: PLS-00302: component 'P2' must be declared The one below works fine begin pkg_spec_test.main; end; / I'm private to package body. PL/SQL procedure successfully completed.
unknown
d12736
train
This is how position: sticky is intended to work. If you need it to also work outside the parent than you have to change the HTML structure. See also the official definition: https://www.w3.org/TR/css-position-3/#sticky-pos A: There is a little trick you can try. In some cases it will break your layout and in others it won't. In my case, I have a header with some buttons but when I scroll down, I want to have access to some action buttons which are inside that one-line header. The only change is to set the display property of your parent to be inline. .parent { display: inline; } A: Sticky works that way, it will remain sticky relative to its parent. You need to use fixed. Check this codepen A: Already 7 months ago, but I found a CSS only solution if the element you want to be sticky is the last one of its parent, its very simple: Just give the parent element position: sticky; and also give it top: -xx;, depending on the height of the elements before the last one. #parent { position: -webkit-sticky; position: sticky; top: -3em; } #some_content { height: 3em; } #sticky { background-color: red; } #space { height: 200vh; } <div id="parent"> <div id="some_content">Some Content</div> <div id="sticky">Sticky div</div> </div> <div id="space"></div> <p>Scroll here</p> A: Based on https://stackoverflow.com/a/46913147/2603230 and https://stackoverflow.com/a/37797978/2603230's code, here's an combined solution that does not require hard-coded height. $(document).ready(function() { // Get the current top location of the nav bar. var stickyNavTop = $('nav').offset().top; // Set the header's height to its current height in CSS // If we don't do this, the content will jump suddenly when passing through stickyNavTop. $('header').height($('header').height()); $(window).scroll(function(){ if ($(window).scrollTop() >= stickyNavTop) { $('nav').addClass('fixed-header'); } else { $('nav').removeClass('fixed-header'); } }); }); body { margin: 0px; padding: 0px; } nav { width: 100%; background-color: red; } .fixed-header { position: fixed; top: 0; left: 0; width: 100%; z-index: 10; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <header> <div> <h1 style="padding-bottom: 50px; background-color: blue;"> Hello World! </h1> </div> <nav> A nav bar here! </nav> </header> <main style="height: 1000px;"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </main> A: Like mentioned, sticky works that way. However there is a CSS hack that you can play around with. Disclaimer This is an ugly hack and will probably create a lot of problems with the following content. So I would not recommend it for most usecases. Having that said... Negative margin hack There is a hack you could play around with including negative margin. If you extend the height of the container and then give it some negative bottom margin, it could at least "visually leave" the container. I altered your code and created a JSFiddle for demonstration. HTML <div class="page"> <div class="parent"> <div class="child"><p>...<br>...<br>...<br>...<br>...</p></div> <div class="child-sticky"> <p>i want to be sticky, even when I'm outside my parent.</p> </div> <div class="child"><p>...<br>...<br>...<br>...<br>...</p></div> <div class="child"><p>...<br>...<br>...<br>...<br>...</p></div> </div> <div class="following-content"> </div> </div> CSS .child-sticky { height: 200px; background: #333366; position:sticky; top:20px; color:#ffffff; } .parent { height: 1250px; background: #555599; margin-bottom: -500px; } .following-content { background: red; height:500px; } .child { background-color: #8888bb; } .page { height: 3000px; background: #999999; width: 500px; margin: 0 auto; } div { padding: 20px; } https://jsfiddle.net/74pkgd9h/
unknown
d12737
train
Unfortunately, for no good reason, Apple doesn't list any 3rd party apps in the Photos app even for apps that register the fact that they can open such files. If you want this feature, file an enhancement request using Apple's bug reporting tool. A: To directly answer your question, no there is no way to get your application on that list. For some reason Apple handles images with their own activity sheet. To get images off the camera roll, look into UIImagePickerController
unknown
d12738
train
You can use the hasClass() jquery method for this: cy.get('selector').then(($ele) => { if ($ele.hasClass('foo')) { //Do something when you have the class } else { //Do something when you don't have the class } }) A: Add the class like this. You don't need to check the condition since $el.addClass() works either way. cy.get('selector').then($el => $el.addClass("blue")) A: You can retrieve the class attribute with should() and check that it contains your class, something like: cy.get('.selector') .should('have.attr', 'class') .and('contain', 'some-class');
unknown
d12739
train
You can iterate over the array and push the date to the desired field. var givenData = [{"fName": "john"}, {"fName": "mike"}, {"country": "USA"}] var result = { 'fName[]': [], 'country[]': [] }; givenData.forEach(function (data) { if (data.fName) { result['fName[]'].push(data.fName); } if (data.country) { result['country[]'].push(data.country); } }); console.log(result); A: You could take the key and build an object with the key and arrays as properties. var givenData = [{"fName": "john"}, {"fName": "mike"}, {"country": "USA"}], grouped = givenData.reduce(function (r, o) { var key = Object.keys(o)[0] + '[]'; r[key] = r[key] || []; r[key].push(o[Object.keys(o)[0]]); return r; }, Object.create(null)); console.log(grouped); A: Suggestion (using ES6 syntax) const transformData = (data) => { const newData = {} data.forEach( (item) => { for (let key in item) { const newKey = key + "[]" if (!newData.hasOwnProperty(newKey)) newData[newKey] = [] newData[newKey].push(item[key]) } }) return newData } /* added some extra keys just to test */ let givenData = [ {"fName": "john", "country": "England"}, {"fName": "mike"}, {"country": "USA"}, {"language": "English"} ] console.log(transformData(givenData)) /* { "fName[]": ["john","mike"], "country[]": ["England","USA"], "language[]":["English"] } */ A: In ES6: const newData = givenData.reduce(function (r, o) { const key = `${Object.keys(o)[0]}[]`; return { ...r, [key]: [ ...r[key], o[key] ] } }, {}); This doesn't modify your original data and is very clean.
unknown
d12740
train
This should work. img.on('click', function () { txt.text('this is new text') }); Or for innerHTML: img.on('click', function () { txt.html('this is new text') }); Remember that you cannot use traditional HTML in SVG Texts. Read here: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/text
unknown
d12741
train
Here is an inline approach Example Select Distinct A.* From ##tableA A Cross Apply ( Select RetSeq = Row_Number() over (Order By (Select null)) ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)'))) From (Select x = Cast('<x>' + replace((Select replace(replace(A.KeyWords,',',' '),' ','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A Cross Apply x.nodes('x') AS B(i) ) B Left Join ##dictionary C on B.RetVal=C.keyword Where C.keyWord is null Returns id keywords 2 I typed a sentence here because I can't follow directions. 3 potato and apple Just another BRUTE FORCE OPTION - Just for fun Declare @S varchar(max) = (Select * From ##tableA For XML Raw ) Select @S = replace(@S,keyword,'') From ##dictionary Select id = B.i.value('@id', 'int') From (Select x = Cast(@S as xml).query('.')) as A Cross Apply x.nodes('row') AS B(i) Where B.i.value('@keywords', 'varchar(max)') like '%[a-z]%' A: Under SQL Server 2017, you can use STRING_SPLIT: SELECT id FROM ##tableA CROSS APPLY STRING_SPLIT(keywords, ' ') splitBySpace CROSS APPLY STRING_SPLIT(splitBySpace.value, ',') splitBySpaceOrComma WHERE splitBySpaceOrComma.value NOT IN (SELECT keyword FROM ##dictionary) GROUP BY id; A: Using: Splitter you can split lines by delimiter then use the result to match against the dictionary. like this: SELECT t.keywords FROM ##tablea t CROSS APPLY (SELECT REPLACE(t.keywords, ' and ', ',')) new(kwds) CROSS APPLY dbo.DelimitedSplit8K(new.kwds, ',') s WHERE s.item NOT IN (SELECT keyword FROM ##dictionary) A: Try this: select t.* from ##tableA t cross join ( select max(case when id = 1 then keyword end) firstKeyword, max(case when id = 2 then keyword end) secondKeyword, max(case when id = 3 then keyword end) thirdKeyword, max(case when id = 4 then keyword end) fourthKeyword from ##dictionary ) d where len(replace(replace(replace(replace(replace(replace(keywords, firstKeyword, ''), secondKeyword, ''), thirdKeyword, ''), fourthKeyword, ''), ' ', ''), ',', '')) > 0 First, you need to pivot your data from ##dictionary, then you can replace your keywords with '' as well as spaces and commas, and see in the end if the are any characters left.
unknown
d12742
train
You can use str.split: >>> x = "hello Why You it from the" >>> x.split() ['hello', 'Why', 'You', 'it', 'from', 'the'] >>> x = "hello Why You it from the" >>> x.split() ['hello', 'Why', 'You', 'it', 'from', 'the'] >>> Without any arguments, the method defaults to splitting on whitespace characters. I just noticed that all of the strings in your example list are lowercase. If this is needed, you can call str.lower before str.split: >>> x = "hello Why You it from the" >>> x.lower().split() ['hello', 'why', 'you', 'it', 'from', 'the'] >>> A: str.split() should do it: >>> x = "hello Why You it from the" >>> x.split() ['hello', 'Why', 'You', 'it', 'from', 'the'] If you want all lowercase (as @iCodez also points out): >>> x.lower().split() ['hello', 'why', 'you', 'it', 'from', 'the'] From the link above: If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. sep is the first argument of split().
unknown
d12743
train
Given Contact contactList[100]; int num_entries; you can use std::sort to sort the list of contacts. std::sort has two forms. In the first form, you can use: std::sort(contanctList, contactList+num_entries); if you define operator< for Contact objects. In the second form, you can use: std::sort(contanctList, contactList+num_entries, myCompare); if you define myCompare to be callable object that can compare two Contact objects. To use the first form, change Contact to: struct Contact { string name, number, notes; bool operator<(Contact const& rhs) const { return (this->name < rhs.name); } }; If you want to the comparison of names to be case insensitive, convert both names to either uppercase or lowercase and them compare them.
unknown
d12744
train
Please go to X-axis in format tab in Visualizations and change type from Continuous to Categorical. Type as Categorical Create a calculated column as follows and sort it using Date field MonthLabel = CONCATENATE(CONCATENATE(LEFT([Date].[Month],3)," "),Right([Date],4)) Hope this helps! Best Regards, Shani Noorudeen
unknown
d12745
train
You have done it the exact right way if there is no other endpoint available to fetch multiple post author information at a time. Well, this is meant to be an answer, but I'd start with a question. Do you have access to the maintainer or developer handling the Restful API endpoint you are trying to get from? If yes? Tell them to simply include the author information on the response for fetching the post(s) Or simply provide you with an endpoint that allows you to get author information for many posts at a time. If No Go over the documentation provided (if any) and see if there is any endpoint that allows you to fetch author information for multiple posts with a single request. If none of the above option seems to be a way, kindly remember to block the UI When fetching the resources. You can also fetch for few authors first and display while fetching for more in the background or on request for more by user, that way you would give a better user experience. Happy hacking and coding
unknown
d12746
train
Opencv is probably the easiest library to get started with, there are some tutorials on image filtering
unknown
d12747
train
since i see tag <Bes> and <Aes> in class A and class B.. i feel that you have already defined root element.. i mean class A and Class B are subset of another class.. check this because an xml can have only one root element. if it is so then root element in class A and B is not valid. i don't see any issue with the xml defined in the class. for more information please visit http://java.dzone.com/articles/jaxb-and-root-elements A: Never mind, I'm an idiot. -.-' In my client code, for some reason I was retrieving Set<B> and Set<C> instead of A and B, respectively.
unknown
d12748
train
Check if this works for you. Inside the aggregate function, you can pass all the values that you want to capture. df2 = (df.groupby([pd.Grouper(key = 'Detection Date & Time', freq = 'H'),df.Detection_Location],sort=False)['Detection Date & Time'] .agg(['first','last','size'])).reset_index().rename(columns={"first": "Detection Date & Time - Start", "last": "Detection Date & Time - End", "size": "Tags"})
unknown
d12749
train
The reason could be that the system path is not configured correctly. Try this, export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CONDA_PREFIX/lib/ Source: https://www.tensorflow.org/install/pip
unknown
d12750
train
I have the same problem, I am just revoked my access from Third-party apps with account access. and it's work for me A: Make the following changes - * *var {google} = require('googleapis'); instead of var google = require('googleapis'); *Write var OAuth2 = google.auth.OAuth2; instead of var googleAuth = require('google-auth-library'); *Do not npm install google-auth-library. If you did, remove it from your package.json and do npm install again. *Make sure you have the latest version of googleapis package. If you do not - do npm install googleapis@27 to get it. (Also add it to the package.json for future). *For any callback - instead of response.items, do response.data.items. You do not necessarily need the callback output when you create an event but you definitely need it when you list events. So do not forget to make this change there. I don't think there would be any issue once you follow all these steps. If there still is, just reply to this. I will try my best to get it resolved!
unknown
d12751
train
Well, I actually did like I said. I take my file, then send it to CloudPrint via its JSON Api. I need to send it to a dummy printer, a printer I registered in CloudPrint but actually is never connected to Internet. Then, I get the number of pages of the PDF file in the value of response's "numberOfPages" attribute. Save this number in some var. Finally, I send a delete petition to JSON Api for my file in the dummy printer, indeed isn't necessary at all. Thanks!
unknown
d12752
train
I can't see your image here, unfortunately - but if I get what you're trying to ask; you can access forms from another assembly if they're public. Then just check this setting is true: Tools > Options > Windows Forms Designer > General : AutoToolboxPopulate Alternatively: Alternatively, you need to make sure that the HR project is referenced by the Classic_steel_hr project then in your forms code (assuming it's namespace is HR) using HR; private void ShowForm() { HR.Form1 hrForm = new HR.Form1(); hrForm.Show(); }
unknown
d12753
train
IE has problems with not properly encoded URLS, it has also problems with simple <a href containing unencoded chars. LABEL%20NAME instead of LABEL NAME should work. With JSONP, jQuery generates a <script src="http://technopress-demo.blogspot.com/feeds/posts/default/-/LABEL NAME?alt=json-in-script&max-results=5"> which has the unencoded char in it. Instead of encodeURIComponent(LABEL NAME), use quotation marks: encodeURIComponent("LABEL NAME") Important: Save your files UTF-8 encoded. (pic from blog.flow.info) Example which works in IE (copied from Firefox+Firebug): A: In your live demo, removing .shortext { text-indent: -9999px; } From the css makes it look OK in IE for me. The div with id="recent" and class="recent shortext" seems to have different markup in FF.
unknown
d12754
train
Usually the log file from a ClickOnce installation tells you what the problem is. I suggest you take a look at that file. In my experience, it usually is some dependency that's missing. Here's a useful guide: Troubleshooting Specific Errors in ClickOnce Deployments If you are using the Google Chrome web browser to launch ClickOnce applications, then take a look at the Chrome Extension for ClickOnce.
unknown
d12755
train
You can use the following command for Basic MSI and InstallScript MSI: ISCmdBld.exe -y "1.0.5" A: Another way: IsCmdBld.exe -z "ProductVersion=1.0.0002"
unknown
d12756
train
There are two ways you can allocate an array of strings in C. * *Either as a true 2D array with fixed string lengths - this is what you have currently. char strings [x][y];. *Or as an array of pointers to strings. char* strings[x]. An item in this pointer array can be accessed through a char**, unlike the 2D array version. The advantage of the 2D array version is faster access, but means you are stuck with pre-allocated fixed sizes. The pointer table version is typically slower but allows individual memory allocation of each string. It's important to realise that these two forms are not directly compatible with each other. If you wish to declare a function taking these as parameters, it would typically be: void func (size_t x, size_t y, char strings[x][y]); // accepts 2D array void func (size_t x, size_t y, char (*strings)[y]); // equivalent, accepts 2D array or void func (size_t x, char* strings[x]); // accepts pointer array void func (size_t x, char** strings); // equivalent - accepts pointer array
unknown
d12757
train
Maybe you need left: 0 in the first style rule so that the transition is from 0px to 500px (which can be interpolated) rather than auto to 500px (which can't). (Also, there are differences between your -webkit-* declarations and your -moz-* declarations, but I don't think there need to be.) A: Put the declaration on the element, not the added class: .ui-dialog-body { position: relative; /* Needed for sliding left, right */ min-height:60px; padding: .5em 1em; -webkit-transition: left .5s linear; -moz-transition: left .5s linear; -ms-transition: left .5s linear; -o-transition: left .5s linear; transition: left .5s linear; } .ui-dialog-body.slideLeft { left:-500px; }
unknown
d12758
train
See Split a string in C++? #include <string> #include <sstream> #include <vector> using namespace std; void split(const string &s, char delim, vector<string> &elems) { stringstream ss(s); string item; while (getline(ss, item, delim)) { elems.push_back(item); } } vector<string> split(const string &s, char delim) { vector<string> elems; split(s, delim, elems); return elems; } So in your case just do: words = split(temp,' '); A: You can use the operator >> direct to a microbuffer (string) to extract the word. (getline is not needed). Take a look at the function below: vector<string> Extract(const string& Text) { vector<string> Words; stringstream ss(Text); string Buf; while (ss >> Buf) Words.push_back(Buf); return Words; } A: #include <algorithm> // std::(copy) #include <iostream> // std::(cin, cout) #include <iterator> // std::(istream_iterator, back_inserter) #include <sstream> // std::(istringstream) #include <string> // std::(string) #include <vector> // std::(vector) using namespace std; auto main() -> int { string user_input; getline( cin, user_input ); vector<string> words; { istringstream input_as_stream( user_input ); copy( istream_iterator<string>( input_as_stream ), istream_iterator<string>(), back_inserter( words ) ); } for( string const& word : words ) { cout << word << '\n'; } } A: Here I have created a vector of words from the sentence. #include<bits/stdc++.h> using namespace std; int main(){ string s = "the devil in the s"; string word; vector<string> v; for(int i=0; i<s.length(); i++){ if(s[i]!=' '){ word+=s[i]; } else{ v.push_back(word); if(i<s.length()+1) word.clear(); } } v.push_back(word); for(auto i:v){ cout<<i<<endl; } }
unknown
d12759
train
There is a built-in way to get the line and column number in JavaScript, but unfortunately, it isn't supported in (literally) all browsers. The only browser that supports it is Firefox. Right now, the best thing you can do is just get it from the browser console. However, to get it from the Error object, you can first wrap your code in a try/catch statement. try { a(); } catch (err) { console.log(err); // ReferenceError: a is... } Then, you can get the line and column numbers from it. Beware; it's only supported in Mozilla! console.log(err.lineNumber, err.columnNumber); // 5 5 The only properties that aren't non-standard in the Error object is the name and message. In conclusion, even though there is a built-in way to get the line and column number in JavaScript, it is non-standard and only supported in Firefox. The best way to get it is to get it from the browser console (or to get it from third-party libraries, if possible).
unknown
d12760
train
Use below code @Html.DropDownListFor(m => m.nDepartmentID, (SelectList)ViewBag.DepartmentList, "Select Any Department", new {@class="select1",@style="width: 150px;" }) Your controller Action will be public ActionResult ShowPage() { var deptmnts=db.Departments.ToList(); ViewBag.DepartmentList=new SelectList(deptmnts,"ID","DepartmentName"); retun View(); }
unknown
d12761
train
You can use Ray in the way that you described. The ray.get call will simply return a list of None values, which you can ignore. You can also look up ray.wait which can be used to wait for certain tasks to finish without actually retrieving the task outputs.
unknown
d12762
train
try Zend_Gdata_Calendar with this library you are able to insert or get events from any user(with the right username and password obviously) from google calendar and integrate with your own calendar or display it..here a short example: $service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME; $client = Zend_Gdata_ClientLogin::getHttpClient('[email protected]', 'gmailpassword', $service); $service = new Zend_Gdata_Calendar($client); $query = $service->newEventQuery(); $query->setUser('default'); $query->setVisibility('private'); try { $eventFeed = $service->getCalendarEventFeed($query); } catch (Zend_Gdata_App_Exception $e) { echo "Error: " . $e->getMessage(); } echo "<ul>"; foreach ($eventFeed as $event) { echo "<li>" . $event->title . " (Event ID: " . $event->id . ")</li>"; } echo "</ul>"; $eventURL = "http://www.google.com/calendar/feeds/default/private/full/Dir0FthEpUbl1cGma1lCalendAr"; try { $event = $service->getCalendarEventEntry($eventURL); echo 'Evento: ' . $event->getTitle() .'<br>'; echo 'detalles: ' . $event->getContent().'<br>'; foreach ($event->getWhen() as $dato) { echo 'inicia: ' . substr($dato->startTime, 0,-19) . ' a las: ' . substr($dato->startTime, 11,-10) .'<br>'; echo 'termina: ' .substr($dato->endTime,0,-19) . ' a las: ' . substr($dato->endTime,11,-10) .'<br>'; } } catch (Zend_Gdata_App_Exception $e) { echo "Error: " . $e->getMessage(); } with this you can add, update, edit or delete events from calendar form any user with mail and password... A: Use OAuth 2 and the Authorization Code flow (web server flow), with offline enabled. Store the refresh tokens (which last indefinitely until the user has revoked), and you'll be able to upload events to Google Calendar even when the user isn't currently logged in. More info: https://developers.google.com/accounts/docs/OAuth2WebServer#offline
unknown
d12763
train
so far i understand your problem you want to take sortOder value from activity B and bring it to Activity A.This can be achieved if you startActivityForResult and there in activity B when you are done with everything just call setresult method and give it the resultant intent and finish this activity B. In activity A you have to override onActivityResult and handle the result from activity B . like startActivityForResult(new Intent(this,ActivityB.class),123); @Override public void onActivityResult(int requestCode, int resultCode, Intentdata) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { if (requestCode==123) { String sordData= data.getStringExtra("sortOrder","byName") sortYourDAta(sordData); } } } and in activity b when sort order is selected just store value in a variable sortOrder="byDate"; and onbackpressed or when ever you want to go back just call this setResult(123,new Intent().putExtra("sortOrder",sortOrder)); finish();
unknown
d12764
train
The issue is a very small one - just change your CommonsMultipartFile to MultipartFile and your test should run through cleanly. The reason for this issue is the mock file upload parameter that is created is a MockMultipartFile which cannot be cast to the more specific CommonsMultipartFile type. A: The simple way how to test multipart upload is use StandardServletMultipartResolver. and for test use this code: final MockPart profilePicture = new MockPart("profilePicture", "stview.jpg", "image/gif", "dsdsdsd".getBytes()); final MockPart userData = new MockPart("userData", "userData", "application/json", "{\"name\":\"test aida\"}".getBytes()); this.mockMvc.perform( fileUpload("/endUsers/" + usr.getId().toString()).with(new RequestPostProcessor() { @Override public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) { request.addPart(profilePicture); request.addPart(userData); return request; } }) MockPart class public class MockPart extends MockMultipartFile implements Part { private Map<String, String> headers; public MockPart(String name, byte[] content) { super(name, content); init(); } public MockPart(String name, InputStream contentStream) throws IOException { super(name, contentStream); init(); } public MockPart(String name, String originalFilename, String contentType, byte[] content) { super(name, originalFilename, contentType, content); init(); } public MockPart(String name, String originalFilename, String contentType, InputStream contentStream) throws IOException { super(name, originalFilename, contentType, contentStream); init(); } public void init() { this.headers = new HashMap<String, String>(); if (getOriginalFilename() != null) { this.headers.put("Content-Disposition".toLowerCase(), "form-data; name=\"" + getName() + "\"; filename=\"" + getOriginalFilename() + "\""); } else { this.headers.put("Content-Disposition".toLowerCase(), "form-data; name=\"" + getName() + "\""); } if (getContentType() != null) { this.headers.put("Content-Type".toLowerCase(), getContentType()); } } @Override public void write(String fileName) throws IOException { } @Override public void delete() throws IOException { } @Override public String getHeader(String name) { return this.headers.get(name.toLowerCase()); } @Override public Collection<String> getHeaders(String name) { List<String> res = new ArrayList<String>(); if (getHeader(name) != null) { res.add(getHeader(name)); } return res; } @Override public Collection<String> getHeaderNames() { return this.headers.keySet(); } }
unknown
d12765
train
After uploading the file have to be displayed in the list of static files. The list of files have a column Reference, which contain a string like this: #APP_IMAGES#test.css. Copy this string and put it, for example, on the page in the section CSS - File URLs. This should work. Then make sure that file reference works. Open your page and take a look on a list of CSS files. The same functionality is present in all browsers, but it is accessible by different ways. In IE: * *Press F12. *Open Network tab. *Press "Enable network traffic capturing" (a green triangle in the left top corner). *Reload the page. A list of files appears. *Find your file in a list: * *If the file is not present, then you copied an incorrect link, or you copied it into an incorrect place, etc. *If the file is present, normally it should have status 200 (the Result column). If a status is not 200, there could be a lot of reasons (depending on the status). *If the file is present with the status 200, your CSS property doesn't work, because it is overridden with another CSS. To define with which one, go to the Dom Explorer tab. A: You can try this approach: * *On server, go to ORACHE_HOME/apex/images/css (path can be different, but you can find it by .css extension) *Put you file here *Id editor, in page properties, go to the CSS -> File URLs section *Write path like this: /i/css/new.css (i - in general, alias for your images directory)
unknown
d12766
train
Try: =IFERROR(VLOOKUP(G6,[SO31165136a.xlsx]Sheet1!$G:$H,2,0),"") adjusted for your sheet and workbook names.
unknown
d12767
train
Few thoughts that might be useful for you: First of all you can get rid of first $sort as you have another one in the last pipeline stage and that one will guarantee right order. There are few ways how to replace $lookup + $unwind + $match + $project + $group. You can use $addFields with $filter to filter out some elements before you $unwind: { $lookup: { from: 'products', localField: 'product', foreignField: '_id', as: 'productModel', } }, { $addFields: { productModel: { $filter: { input: '$productModel', as: 'model', cond: { $ne: [ '$$model.archived', true ] } } } } }, { $unwind: '$productModel' } In this case you can remove $match since this operation is performed in nested array. Second way might be to use $lookup with custom pipeline, so that you can perform this additional filtering inside $lookup: { $lookup: { from: 'products', let: { productId: "$product" }, pipeline: [ { $match: { $expr: { $and: [ { $eq: [ "$$productId", "$_id" ] }, { $ne: [ "$archived", true ] } ] } } } ], as: 'productModel', } } As another optimization in both cases you don't need $unwind as your productModel array is filtered and then you can just modify your $group: { $group: { _id: '$product', saleModelsCount: { $sum: { $size: "$productModel" } }, quantity : { $sum: '$quantity' }, } }
unknown
d12768
train
You may try this solution: const data = { abc_0: 'a', bcd_0: 'b', cde_0: 'c', abc_1: 'a', bcd_1: 'b', cde_1: 'c', def_1: 'd', }; const result = Object.entries(data).reduce((acc, [combo, value]) => { const [key, index] = combo.split('_'); acc[index] = { ...acc[index], [key]: value }; return acc; }, {}); console.log(result); A: You can write something like this to achieve it const obj = { abc_0: 'a', bcd_0: 'b', cde_0: 'c', abc_1: 'a', bcd_1: 'b', cde_1: 'c', def_1: 'd', }; const groupByChar = () => { const res = {}; for (let k in obj){ const char = k.charAt(k.length-1); if (!res[char]){ res[char] = {}; } const key = k.substring(0, k.length - 2); res[char][key] = obj[k]; } return res; } const res = groupByChar(); console.log(res); A: I deliberately disrupted the data sequence to better meet your needs. const data = { abc_0: 'a', abc_1: 'a', bcd_0: 'b', bcd_1: 'b', cde_0: 'c', cde_1: 'c', def_0: 'd', def_1: 'd', }; const res = Object.keys(data) .map((key) => { const [char, num] = key.split('_'); return { [num]: { [char]: data[key], }, }; }) .reduce((acc, cur) => { const acc_keys = Object.keys(acc); const [cur_key] = Object.keys(cur); if (acc_keys.includes(cur_key)) { acc[cur_key] = { ...acc[cur_key], ...cur[cur_key] }; return { ...acc, }; } else { return { ...acc, ...cur }; } }, {}); console.log(res); A: Another way of writing it const obj= { abc_0: 'a', bcd_0: 'b', cde_0: 'c', abc_1: 'a', bcd_1: 'b', cde_1: 'c', def_1: 'd', } const filtered = Object.keys(obj).map((el)=>el.split('_')[1]).filter((el, i)=>Object.keys(obj).map((el)=>el.split('_')[1]).indexOf(el)===i); const res = Object.entries(obj).reduce((acc, curr, i)=>{ const left=curr[0].split('_')[0] const right=curr[0].split('_')[1] filtered.forEach((index)=>{ if(right==index){ !acc[index]? acc[index]={}:null !acc[index][left]?acc[index][left]=obj[`${left}_${right}`]:null } }) return acc },{}) console.log(res);
unknown
d12769
train
You are misunderstanding object files. Start by taking a look at this question: What does an object file contain? Object files do contain binary machine language instructions for the target platform, so there is no "translator" of any kind between the binary code contained in them and what is executed on the target CPU. I think your confusion stems from the fact that object files also contain other information, such as symbol tables and constants. It is the linker's job to collect all of this information and package it into an executable. Side Note: This answer is assuming a C/C++ perspective. Languages like Java that execute on a virtual machine have other layers in between compiling and execution.
unknown
d12770
train
Without a good, minimal, complete code example, it's impossible to know for sure what the best approach is. However, if you have set your ListView up correctly and the ItemsSource is a collection of Discussion objects, then by default the SelectedValue property will return the Discussion object instance reference that corresponds to the selected item in the list. In that case, you would just change your code to look like this: private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e) { DependencyObject clickedObj = (DependencyObject)e.OriginalSource; while (clickedObj != null && clickedObj != listDiscussion) { if (clickedObj.GetType() == typeof(ListViewItem)) { Discussion selectedDiscussion = (Discussion)listDiscussion.SelectedValue; this.NavigationService.Navigate(new MessagePage(selectedDiscussion)); break; } clickedObj = VisualTreeHelper.GetParent(clickedObj); } } I.e. just use the SelectedValue property instead of SelectedItem. If you have deviated from the default by setting the SelectedValuePath property, then you will want to use the ItemContainerGenerator object to get the correct reference: private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e) { DependencyObject clickedObj = (DependencyObject)e.OriginalSource; while (clickedObj != null && clickedObj != listDiscussion) { if (clickedObj.GetType() == typeof(ListViewItem)) { Discussion selectedDiscussion = (Discussion)listDiscussion.ItemContainerGenerator .ItemFromContainer((ListViewItem)listDiscussion.SelectedItem); this.NavigationService.Navigate(new MessagePage(selectedDiscussion)); break; } clickedObj = VisualTreeHelper.GetParent(clickedObj); } } If neither of those seem to apply in your case, please edit your question so that it includes a good code example, with which a better answer can be provided.
unknown
d12771
train
I think you have the right idea. You will want to keep the old fields together with their field numbers unchanged as long as there is data stored in the old format. One of the great things about protocol buffers is that unset fields are essentially free, so you can add as many new fields as you want to facilitate the migration. What I would do is add a new set of float fields and rename the double fields while preserving their field numbers: message Matrix { // Values in these fields should be transitioned to floats double deprecated_width = 1; double deprecated_height = 2; repeated double deprecated_entries = 3; float width = 4; float height = 5; repeated float entries = 6; } Whenever you read a Matrix from persistent storage move any values from the deprecated fields to the non-deprecated fields and write back the result. This should facilitate incremental migration to floats. I will mention one more thing that you probably already know: protocol buffers don't care about the fields names. Only field numbers matter for serialization and deserialization. This means fields can be renamed freely as long as the code that manipulates them is likewise updated. At some point in the future when the migration has been completed remove the migration code and delete the deprecated fields but reserve their field numbers: message Matrix { reserved 1, 2, 3; float width = 4; float height = 5; repeated float entries = 6; } This ensures any stray messages in the old format blow up on deserialization instead of cause data corruption. Hope this helps!
unknown
d12772
train
Stackoverflows rarely happen with typical streams; without code I can't be sure what's wrong. In earlier versions of RxJava, there were reentrancy problems in some operators that could result in StackOverflows but we haven't received any bug reports like it in some time now. Please make sure you are using the latest RxJava from the 1.x line (the RxAndroid plugin's dependency may need overriding as it is infrequently updated in this regard). There are a few things you can do: * *compact subsequent doOnNext and doOnError calls into doOnEach *add observeOn(Schedulers.computation()) occasionally *avoid chaining too many mergeWiths, collect up sources into a List and use merge(Iterable) *upgrade to RxJava 2.x which should have less stack depth (have not verified) Edit: Based on the stacktrace, my undestanding is that you have too many empty sequences and switchIfEmpty keeps deepening the stack when switching from one empty sequence to the next. As you found out, subscribeOn helps "restart" the stack. I'll investigate possible resolutions within RxJava itself. A: The cause of this problem was Jack compiler (https://source.android.com/source/jack.html) which I use in the project for lambdas support. I switched it off and now everything works fine
unknown
d12773
train
I do not know Epics, but I think I can give you some hints about how to address this problem. Let's start from the fact that you have an array of ids, assetIds, and you want to make an http call for each id with a controlled level of concurrency, maxParallelQueries. In this case from function and mergeMap operator are yor friends. What you need to do is // from function transform an array of values, in this case, to a stream of values from(assetIds).pipe( mergeMap(id => { // do whatever you need to do and eventually return an Observable return AssetDataService.fetchThumbnailData(id) }, maxParallelQueries) // the second parameter of mergeMap is the concurrency ) In this way you should be able to invoke the http calls keeping the limit of concurrency you have established A: * *I am able to get the batch based response in next method of subscribe. However, the action invoked in this function along with response is not getting invoked. You mustn't call an action imperatively in redux-observable. Instead you need to queue them. actions.AssetActions.receivedThumbnailsAction(response, meta) would return an plain object of the shape {type: "MY_ACTION", payload: ...} instead of dispatching an action. You rather want to return that object wrapped inside an observable inside mergeMap in order to add the next action to the queue. (see solution below) *maxParallelQueries dont seems to be working as intended. All the fetchThumbnailObservables() are executed at once and not in the batches of 3 as set as constant/ First guess: What is the return type of AssetDataService.fetchThumbnailData(assetIds.slice(count, count + batchSize))? If it is of type Promise then maxParallelQueries has no effect because promises are eager and start immediately when created thus before mergeMap has the chance to control the request. So make sure that fetchThumbnailData returns an observable. Use defer rather than from if you need to convert a Promise to an Observable to make sure that a promise is not being fired prematurely inside fetchThumbnailData. Second guess: forkJoin is firing all the request so mergeMap doesn't even have the chance to restrict the number of parallel queries. I'm surprised that typescript doesn't warn you here about the incorrect return type in mergeMap(fetchThumbnailObservable => fetchThumbnailObservable, ...). My solution below replaces forJoin with from and should enable your maxParallelQueries. *How to handle return of observable so that mergeMap do not give syntax error . Argument of type '({ payload }: IAction) => void' is not assignable to parameter of type '(value: IAction, index: number) => ObservableInput'. Type 'void' is not assignable to type 'ObservableInput'.ts(2345) This is not a syntax error. In an epic you have either the option to return an empty observable return empty() if no subsequent actions are intended or dispatch another action by returning an observable of type IAction. Here my (untested) attempt to meet your requirements: const getThumbnails: Epic<IAction, IAction, IStoreState> = (action$, state$) => action$.ofType(ActionTypes.AssetActions.DATA.FETCH_THUMBNAILS).pipe( mergeMap( ({ payload }) => { const assetIds = Object.keys(payload); const meta = payload; const batchSize = 10; const maxParallelQueries = 3; const fetchThumbnailObservables : Observable<IThumbnailResponse>[] = []; for (let count = 0; count < assetIds.length; count += batchSize) { fetchThumbnailObservables.push( AssetDataService.fetchThumbnailData( assetIds.slice(count, count + batchSize) ) ); } return from(fetchThumbnailObservables) .pipe( mergeMap( fetchThumbnailObservable => fetchThumbnailObservable, maxParallelQueries ), map((response) => // dispatch action for each response actions.AssetActions.receivedThumbnailsAction(response, meta) ), // catch error early so epic continue on error catchError((error) => of(actions.Common.errorOccured({ error }))) ); }) ); Please notice that I moved catchError closer to the request (inside the inner forkJoin Observable) so that the epic does not get terminated when an error occurs. Error Handling - redux observable This is so because when catchError is active it replaces the failed observable with the one that is returned by catchError. And I assume you don't want to replace the whole epic in case of an error? And one thing: redux-observable handles the subscriptions for you so won't need to call .subscribe or .unsubscribe anywhere in your application. You just need to care a about the lifecycle of observables. Most important to know here is when does an observable start, what happens to it when it completes, when does it complete or what happens when an observable throws.
unknown
d12774
train
Some problems with that code: * *Select Case Range(Target.Address) doesn't make sense - it takes the Target range, takes its address and creates a range from that address, which points to the original Target range, and finally VB takes the default property of that range, because its not being used in an object reference context. So the whole thing should be replaced with Target.Value. *Later same thing happens to minhaCelula. *Code under "C" and "P" is the same and should be placed under the same Case branch. *Colons are not used in VB's Select Case. *AddComment should be called without parentheses. Even better, you should benefit from the fact AddComment returns the reference to the added comment, so you can directly use that (in which case you must keep the parentheses). So that should be rewriteen as: Private Sub Worksheet_Change(ByVal Target As Range) If Not Application.Intersect(Me.Range("A1:S1000"), Target) Is Nothing Then Select Case Target.Value Case "C", "P" Target.AddComment("").Visible = True End Select End If End Sub As for the question, when you use Comment.Visible, Excel stops managing the comment's visibility. To leave the management on Excel side, make the comment's shape visible instead: Private Sub Worksheet_Change(ByVal Target As Range) If Not Application.Intersect(Me.Range("A1:S1000"), Target) Is Nothing Then Select Case Target.Value Case "C", "P" With Target.AddComment("").Shape .Visible = msoTrue .Select End With End Select End If End Sub
unknown
d12775
train
I faced the same issue before. it's look like git do something like smart cloning which only clone the changes made to the repository. issue resolved once i added an additional behavior to to Wipe out repository & force clone like below:
unknown
d12776
train
You have to set to set SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS before Pygame and the joystick module is initialized: import os os.environ["SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS"] = "1" import pygame pygame.init()
unknown
d12777
train
(3,) does not mean the 3 is first. It is simply the Python way of writing a 1-element tuple. If the shape were a list instead, it would be [3]. (, 3) is not valid Python. The syntax for a 1-element tuple is (element,). The reason it can't be just (3) is that Python simply views the parentheses as a grouping construct, meaning (3) is interpreted as 3, an integer. A: As you know, numpy arrays are n-dimensional. The shape tells dimensions in the order. If it is 1-D you will see only 1st dimension, 2-D only 2 dimensions and so on. Here x is a 2-D array while v is a 1-D array (aka vector). That is why when you do shape on v you see (3,) meaning it has only one dimension whereas x.shape gives (4,3). When you transpose v, then that is also a 1-D array. To understand this better, try another example. Create a 3-D array. z=np.ones((5,6,7)) z.shape print (z)
unknown
d12778
train
You can use text box with custom validation. Here isNumberKey only accept the number for each character function isNumberKey(evt){ var charCode = (evt.which) ? evt.which : evt.keyCode if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } function show(){ console.log(document.getElementById('test').value) } <input id="test" type="text" onkeypress="return isNumberKey(event)"/> <button type="button" value="show value" onClick="show()">show value</button>
unknown
d12779
train
In general, I think it is not a good idea to try to emulate Haskell patterns in F#. In Haskell, lot of code is written as very generic, because monads and applicatives are used more frequently. In F#, I prefer writing more specialized code, because you do not need to write code polymorphic over monads or applicatives and it just makes it easier to see what is going on. So, I do not think I would ever want to write <*> operator that works over any "applicative" in practice in F#. That said, the issue with your code is that the <*> operator uses the same ^A type parameter for both arguments and the result (while they are different types in the call) - if you use three separate type parameters it works fine: let inline (<*>) (f: ^B) (t:^A) : ^C = let apply' = (^A : (member apply : ^B -> ^C) (t, f)) apply'
unknown
d12780
train
You can use z-index property for .navigation instead of using opacity for phone_button. in CSS file you set z-index:10; for .navigaion class. Besides that, it's better to set the property in one class in CSS and after clicking on phone_button just toggle this specific class for navigation You can do like this: const btn=document.querySelector(".menuBtn"); const nav=document.querySelector('.navigation'); const closeBtn=document.querySelector('.closeBtn'); btn.addEventListener('click',function(){ nav.classList.add('show'); }) closeBtn.addEventListener('click',function(){ nav.classList.remove('show'); }) *{ margin:0; box-sizing:border-box; } .container{ position:relative; display:flex; } .navigation{ position:absolute; width:200px; height:100vh; background-color:#e45; transform:translateX(-100%); transition:transform 0.5s; z-index:10 } .navigation.show{ transform:translateX(0) } li{ list-style:none; margin:0; } a{ text-decoration:none; color:white; padding:0.3rem 1rem; margin-top:0.5rem; display:block; } .closeBtn{ cursor:pointer; color:white; padding:1rem; display:block; margin-left:auto; } <div class="container"> <button class='menuBtn'>click me</button> <nav class="navigation"> <span class="closeBtn">close</span> <ui> <li> <a href="#">home</a> </li> <li> <a href="#">about</a> </li> </ui> </nav> </div> With this snippet code after the user clicked on the click me button, the .show class add to nav item class list. A: You can use the transitionend event and hide the Button in an eventlistener A: You can use this event check this tutorial. var x = document.getElementById("myDIV"); // Code for Chrome, Safari and Opera x.addEventListener("webkitAnimationEnd", myEndFunction); // Standard syntax x.addEventListener("animationend", myEndFunction);
unknown
d12781
train
If you are trying to use version 3.1.2 of the plugin, you want org.grails.plugins:cxf:3.1.2, not org.grails.plugins:grails-cxf:3.1.2. A: The problem is that the plugin's documentation talks about to use the version 3.1.2, but the latest version in the repository is the 3.0.9
unknown
d12782
train
In a single loop. Hopefully, it'll work. Couldn't test so let me if you face any situation. <?php $faqs = new WP_Query([ 'post_type' => 'faq', 'post_status' => 'publish', ]); $half = intval($faqs->post_count / 2); $counter = 0; ?> <div class="row"> <div class="col-lg-6"> <?php while ($faqs->have_posts()) : $faqs->the_post(); ?> <?php if ( $counter === $half ) : ?> </div><div class="col-lg-6"> <?php endif; ?> <?php the_content(); ?> <?php ++$counter; endwhile; ?> </div> </div> A: try it like this <?php $faqs = new WP_Query( array ( 'post_type' => 'faq' )); ?> <div class="row"> <div class="col-lg-6"> <!-- The first half of the total loop count. --> <?php $i=0; while ($faqs->have_posts() && $i < $faqs->post_count / 2) : $faqs->the_post(); $i++ the_content(); endwhile(); ?> </div> <div class="col-lg-6"> <!-- The second half of the tootal loop count. --> <?php while ($faqs->have_posts()) : $faqs->the_post(); the_content(); endwhile(); ?> </div> </div> https://wordpress.stackexchange.com/questions/27116/counting-the-posts-of-a-custom-wordpress-loop-wp-query
unknown
d12783
train
are you deploying to sharepoint or a standalone (native-mode) report server? http://msdn.microsoft.com/en-us/library/ms155802(v=sql.105).aspx 10.In the TargetServerURL text box, type the URL of the target report server. Before you publish a report, you must set this property to a valid report server URL. When publishing to a report server running in native mode, use the URL of the virtual directory of the report server (for example, http://server/reportserver or https://server/reportserver). This is the virtual directory of the report server, not Report Manager. When publishing to a report server running in SharePoint integrated mode, use a URL to a SharePoint top-level site or subsite. If you do not specify a site, the default top-level site is used (for example, http://servername, http://servername/site or http://servername/site/subsite).
unknown
d12784
train
If both theDate and theDate2 can be determined by the flag processDate then do it in your select rather than in the insert. Assuming that the columns are nullable (as your CASE in the INSERT clause seems to indicate they are mutually exclusive, then I'd be inclined to do something like; INSERT INTO tableOne (theDate, theDate2) SELECT CASE WHEN processDate <> '' THEN sDate ELSE NULL END theDate, CASE WHEN processDate = '' THEN sDate ELSE NULL END theDate2, FROM #tableTwo A: what about two queries which would look like that: INSERT INTO tableOne (theDate) SELECT sDate FROM #tableTwo WHERE processDate <> '' Followed by something like INSERT INTO tableOne (theDate2) SELECT sDate FROM #tableTwo WHERE processDate = '' A: The proper syntax for an insert is insert into table (field1, field2, etc) select field3, field4, etc from somewhere I have no idea if this will work, but you can try: insert into tableOne (case when processDate <> '' then theDate else Date2 end) select sdate from #table2
unknown
d12785
train
You make the title but you don't actually add it to the view. [cell.contentView addSubview:title];
unknown
d12786
train
OBIEE doesn't use flash anymore since many years because it's dead technology. You didn't upgrade and now get penalized. Any version that still uses flash is out of date and unsupported.
unknown
d12787
train
This is the way to do it... I have made a jsfiddle showing this: Edit: Recently worked out a way to get this binding using vanilla knockout. I've tested this out on the latest version of knockout (3.4) Just use this binding and knockout datatables works! ko.bindingHandlers.dataTablesForEach = { page: 0, init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { valueAccessor().data.subscribe(function (changes) { var table = $(element).closest('table').DataTable(); ko.bindingHandlers.dataTablesForEach.page = table.page(); table.destroy(); }, null, 'arrayChange'); var nodes = Array.prototype.slice.call(element.childNodes, 0); ko.utils.arrayForEach(nodes, function (node) { if (node && node.nodeType !== 1) { node.parentNode.removeChild(node); } }); return ko.bindingHandlers.foreach.init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); }, update: function (element, valueAccessor, allBindings, viewModel, bindingContext) { var options = ko.unwrap(valueAccessor()), key = 'DataTablesForEach_Initialized'; ko.unwrap(options.data); // !!!!! Need to set dependency ko.bindingHandlers.foreach.update(element, valueAccessor, allBindings, viewModel, bindingContext); (function() { console.log(options); var table = $(element).closest('table').DataTable(options.dataTableOptions); if (options.dataTableOptions.paging) { if (table.page.info().pages - ko.bindingHandlers.dataTablesForEach.page == 0) table.page(--ko.bindingHandlers.dataTablesForEach.page).draw(false); else table.page(ko.bindingHandlers.dataTablesForEach.page).draw(false); } })(); if (!ko.utils.domData.get(element, key) && (options.data || options.length)) ko.utils.domData.set(element, key, true); return { controlsDescendantBindings: true }; } }; JSFiddle A: I made a fiddle with a solution http://jsfiddle.net/Jarga/hg45z9rL/ Clicking "Update" will display the current knockout model as text below the button. What was missing was the linking the change of the textbox to the observable by adding a listener in the render function. Also each row's textbox was being given the same id, which is not a good idea either. (Note: the event aliases are just to prevent collision with other handlers) Changing the render function to build useful ids and adding the following should work: $('#' + id).off('change.grid') $('#' + id).on('change.grid', function() { row.age($(this).val()); }); Ideally Knockout would handle this for you but since you are not calling applyBindings nor creating the data-bind attributes for the html elements all that knockout really gives you here is the observable pattern. Edit: Additional Solution Looking into it a little bit more you can let Knockout handle the rendering by adding the data-bindattribute into the template and binding your knockout model to the table element. var html = '<div style="display:inline-flex">' + '<input type="text" class="headerStyle h5Style" id="' + id + '" data-bind="value: $data[' + cell.row + '].age"/>' And ko.applyBindings(people, document.getElementById("example")); This removes the whole custom subscription call when constructing the Personobject as well. Here is another fiddle with the 2nd solution: http://jsfiddle.net/Jarga/a1gedjaa/ I feel like this simplifies the solution. However, i do not know how efficient it performs nor have i tested it with paging so additional work may need to be done. With this method the mRender function is never re-executed and the DOM manipulation for the input is done entirely with knockout. A: Here is a simple workaround that re-binds the data in knockout and then destroys/recreates the datatable: // Here's my data model var ViewModel = function() { this.rows = ko.observable(null); this.datatableinstance = null; this.initArray = function() { var rowsource1 = [ { "firstName" : "John", "lastName" : "Doe", "age" : 23 }, { "firstName" : "Mary", "lastName" : "Smith", "age" : 32 } ]; this.redraw(rowsource1); } this.swapArray = function() { var rowsource2 = [ { "firstName" : "James", "lastName" : "Doe", "age" : 23 }, { "firstName" : "Alice", "lastName" : "Smith", "age" : 32 }, { "firstName" : "Doug", "lastName" : "Murphy", "age" : 40 } ]; this.redraw(rowsource2); } this.redraw = function(rowsource) { this.rows(rowsource); var options = { paging: false, "order": [[0, "desc"]], "searching":true }; var datatablescontainer = $('#datatablescontainer'); var html = $('#datatableshidden').html(); //Destroy datatable if (this.datatableinstance) { this.datatableinstance.destroy(); datatablescontainer.empty(); } //Recreate datatable datatablescontainer.html(html); this.datatableinstance = datatablescontainer.find('table.datatable').DataTable(options); } }; ko.applyBindings(new ViewModel("Planet", "Earth")); // This makes Knockout get to work https://jsfiddle.net/benjblack/xty5y9ng/
unknown
d12788
train
You are describing the behavior of a dynamic array. The easiest way to implement this data structure is to create a new array once the array is full or below some threshold (only 1/4 of the cells are occupied, for example), and copy existing values into the new array. If you want to know how it is done in java, and what optimizations are being made - you might want to have a look on the ArrayList class source. A: You can read the source for ArrayList here: SOURCE And you are right, it keeps an array and replaces it as needed to allow room for more objects. But it also stores the length so the array can be longer than is needed. That allows the ArrayList to grow a little without having to re-create the actual array everytime. If the ArrayList gets smaller, it doesn't have to re-create. It just changes the length as stored. You can read the code to see how they decide when to change the array itself. Whenever they do that, they have to copy the old one's contents over. You are right, BTW, that the old arrays get garbage collected as long as there are not variables referencing them. It sort of depends on how your code works. If that code you show and the definition is the only reference, then it will get GC'ed when you make a new array and store it. A: The official implementation of ArrayList never reduces the size of an array, only increases the capacity when needed. When an element is removed from the ArrayList, it ensures that the posterior elements return one position and sets null for the free element on the right.
unknown
d12789
train
I faced pretty much the same error. It seems that the code hangs at detectAndCompute in my case, not when creating the dictionary. For some reason, sift feature extraction is not multi-processing safe (to my understanding, it is the case in Macs but I am not totally sure.) I found this in a github thread. Many people say it works but I couldn't get it worked. (Edit: I tried this later which works fine) Instead I used multithreading which is pretty much the same code and works perfectly. Of course you need to take multithreading vs multiprocessing into account
unknown
d12790
train
The mistery function is called TYPE :-) select type(date '2008-03-07'- date '2009-04-10') It's not INTERVAL DAY, it's an INTEGER. You only get INTERVALS when you request them explicitly, but they're hardly used as the maximum number of digits is only 4: select date '2008-03-07'- date '2009-04-10' MONTH(4)
unknown
d12791
train
In the way malloc() request memory from heap, there are system calls (for e.g. shmget()) to request/create shared memory segment. If your request is successful, you can copy whatever you like over there. (Yes, you can use memcpy.) But remember to be careful about pointers, a pointer valid for one process, kept in its shared memory, is not necessarily valid for another process using that shared memory segment. The shared memory is accessible to all processes for reading and/or writing. If multiple processes are reading/writing to a shared memory segment, then, needless to say, some synchronization techniques (for e.g. semaphore) need to be applied. Please read up on shared memory. An excellent source is "The Linux Programming Interface" by Michael Kerrisk. Reference: * *http://man7.org/linux/man-pages/man7/shm_overview.7.html *http://man7.org/linux/man-pages/man2/shmget.2.html *http://www.amazon.com/The-Linux-Programming-Interface-Handbook/dp/1593272200
unknown
d12792
train
A = clientA config!B:B = clientB In a "summary" sheet, I need to add a dropdown in column C depending on the column A For example summary!A2 contains "client A" so the dropdown in summary!C2 will show the list of clientA And summary!A3 contains "client B" so the dropdown in summary!C3 will show the list of clientB What I currently do is named the range each in the "config" then in "summary" I put the Data Validation for the specific name. I was wondering if there's a custom formula that I can put in the Data Validation for Column C that depends on the value in column A. The only challenge is there are spaces so in the Named Range I remove the space. And since it depends on the column, the row number is moving. Looking for a formula since I am avoiding App Script for this specific file. Thanks Hopefully someone could help me on this. Thanks much. You are all awesome! A: What you can do is set an Auxiliary sheet (or extra columns far in "Summary"). You can set Summary!C2 the next Data Validation: =Auxiliary!A1:1 Open the settings of that data validation and make sure there are no anchors (no $, for example A$1). If there is some, delete them Close it and then copy and paste special - Data Validation only to the rest of the cells This way C2 will be associated with row 2 from Auxiliary, C3 with row 3 and so on Then, you can go to Auxiliary and set a formula in each row to filter the values according to B2, B3 (or however you identify the client... (a Query, or Filter) --> You'll probably need to transpose the information, so the list becomes a row With that done, each data validation will depend now on the value of that row Re-reading your example, you can do the same but instead of filter you can transpose the entire Config sheet and you'll have a row per client ...... You have an example here: https://docs.google.com/spreadsheets/d/1jF5XoBkQll5tHEjADg508NMznmbuB43tyWv5R2S1mM8/edit?usp=sharing
unknown
d12793
train
library(tidyverse) data <- tibble(data = c("Doe, John - Mr", "Anna, Anna - Ms", " ,asd;flkajsd")) data data %>% # first word must ed with a filter(data %>% str_detect("^[A-z]+a")) %>% separate(data, into = c("Last", "First", "Title"), sep = "[,-]") %>% mutate_all(str_trim) # A tibble: 1 × 3 # Last First Title # <chr> <chr> <chr> #1 Anna Anna Ms A: We may use extract to do this - capture the regex pattern as two groups ((...)) where the first group would return word (\\w+) from the start (^) of the string followed by a ,, zero or more space (\\s*), another word (\\w+), then the - (preceding or succeeding zero or more space and the second capture group with the word (\\w+) before the end ($) of the string library(tidyr) library(dplyr) extract(C22, ITEM, into = c("Name", "Title"), "^(\\w+,\\s*\\w+)\\s*-\\s*(\\w+)$") %>% mutate(Name = coalesce(Name, ITEM), .keep = 'unused') NOTE: The mutate is added in case the regex didn't match and return NA elements, we coalesce with the original column to return the value that corresponds to NA
unknown
d12794
train
Your best performance will be if you can encode your "tests" into the SQL logic itself, so you can boil everything down to a handful of UPDATE statements. Or at least get as many as possible done that way, so that fewer rows need to be updated individually. For example: UPDATE tablename set firstname = [some logic] WHERE [logic that identifies which rows need the firstname updated]; You don't describe much about your tests, so it's hard to be sure. But you can typically get quite a lot of logic into your WHERE clause with a little bit of work. Another option would be to put your logic into a stored procedure. You'll still be doing 350,000 updates, but at least they aren't all "going over the wire". I would use this only as a last resort, though; business logic should be kept in the application layer whenever possible, and stored procedures make your application less portable. A: SQL #1: CREATE TABLE t with whatever columns you might need to change. Make all of them NULL (as opposed to NOT NULL). SQL #2: Do a bulk INSERT (or LOAD DATA) of all the changes needed. Eg, if changing only first_name, fill in id and first_name, but have the other columns NULL. SQL #3-14: UPDATE real_table JOIN t ON t.id = real_table.id SET real_table.first_name = t.first_name WHERE t.first_name IS NOT NULL; # ditto for each other column. All SQLs except #1 will be time-consuming. And, since UPDATE needs to build a undo log, it could timeout or otherwise be problematical. See a discussion of chunking if necessary. If necessary, use functions such as COALESCE(), GREATEST(), IFNULL(), etc. Mass UPDATEs usually imply poor schema design. (If Ryan jumps in with an 'Answer' instead of just a 'Comment', he should probably get the 'bounty'.)
unknown
d12795
train
I guess that your jar file generated with Ant does not have jar-in-jar-loader, that's why it is not able to find classes inside embedded jars. When you generate JAR with Eclipse you can Save Ant script, then jar-in-jar-loader.zip file would be added to project. Then use generated Ant file to create your JAR. This approach works for me. Your Ant script should look like this: <jar destfile="C:\Users\\workspace\Your.jar"> <manifest> <attribute name="Main-Class" value="org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader"/> <attribute name="Rsrc-Main-Class" value="org.mypackage.MainClass"/> <attribute name="Class-Path" value="."/> <attribute name="Rsrc-Class-Path" value="./ libA.jar "/> </manifest> <zipfileset src="jar-in-jar-loader.zip"/> <fileset dir="${ProjectPath}/bin"/> <zipfileset dir="${ProjectPath}\lib" includes="libA.jar"/> </jar> First zipfileset would include jar-in-jar-loader.zip fileset would add all your classes Second zipfileset would add libA.jar as embedded jar and same should be mentioned in Rsrc-Class-Path A: With your Ant-generated Manifest, it is looking for the library jar files outside of the main jar file, the Eclipse one uses a special Main-Class and class loader to get to the bundled dependencies. You probably want to use the OneJar ant task (or something similar) to achieve something comparable to what Eclipse does.
unknown
d12796
train
Ideally, it should hardly matter to you. But I see the arrow in my code base for the functions implemented outside the class-declaration (i.e. into implementation file). All inline methods are shown without the arrow symbol. I am not sure why they are duplicated in your case. May be namespace implementation has something to do. But, again - why does it matter?
unknown
d12797
train
I think the problem with Collections.shuffle() is that is uses default Random instance which is a thread-safe singleton. You say that your program is multi-threaded, so I can imagine synchronization in Random being a bottle-neck. If you are happily running on Java 7, simply use ThreadLocalRandom. Look carefully, there is a version of shuffle() taking Random instance explicitly: Collections.shuffle(arr, threadLocalRandom); where threadLocalRandom is created only once. On Java 6 you can simply create a single instance of Random once per thread. Note that you shouldn't create a new instance of Random per run, unless you can provide random seed every time. A: Part of the problem might be the overhead of the Integer boxing and unboxing. You might find it helpful to reimplement the Fisher-Yates shuffle directly on an int[]. A: My approach woul be to generate the numbers with the Math.random() method as in the example here and initialize the list via a static init block like this: private static List<int> list = new ArrayList<int>(); static { for(int i = 0; i < 100; i++) { // randomize number list.add(number); } } Hope this helped, have Fun! A: To shuffle an array a of n elements (indices 0..n-1): for i from n − 1 downto 1 do j ← random integer with 0 ≤ j ≤ i exchange a[j] and a[i] Check Fischer and Yattes algorithm.
unknown
d12798
train
Should I be doing this at all, and / or is it the best way to do this? Use XMVECTOR instead of XMFLOAT3 since most of the functions in DriectXMath use XMVECTOR. thus you can avoid the boring type cast and make your code clean. I was able to use the + operator on D3DXVECTOR3, but now not XMFLOAT3? How do I add these together? Again, use XMVECTOR instead of XMFLOAT3 XMVECTOR also has some disadvantage(I mean the code seems a little complicated sometimes). with D3DXVECTOR3, you can simply initialize a variable as D3DXVECTOR3 a(x, y, z, w) and get it's component as a.x, a.y, ... but XMVECTOR use a different way. To initialize an XMVECTOR, use XMVectorSet function. XMVECTOR lookAt = XMVectorSet(x, y, z, w); To get component of an XMVECTOR, use the following functions. * *XMVectorGetX *XMVectorGetY *XMVectorGetZ *XMVectorGetW A: 1. Should I? Should I be doing this at all, and / or is it the best way to do this? Generally speaking, you use Windows SDK to write your new code, but you don't have to convert any old code (yours or, especially, others). It`s just a waste of time. You can install DirectX SDK to be able to build it. On the other hand, it is a good opportunity to learn a little more about DrectX and its infrastructure. For example, portng from D3DXMath to DirectXMath (previously XMMath), you will learn pros and cons of SSE-based math libraries, and it is a good place to begin to write your own. 2. How to? If you really decided to do this hard work, then 90% of info you will find in a good article by Chuck Walbourn - MSFT: Living without D3DX. Another 9.9% you will figure out by yourself from documentation, and 0.1% more from looking at DirectXMath source code (it is a header library, all functions inlined and you cann freely learn them). You will, probably, also interested in another articles by that guy on MSDN. 3. operator+ problem Instead of single D3DXVECTORn type (where n is a number of components), new math contains two types: XMFLOATn and XMVECTOR. Same for matrices: XMMATRIX and XMFLOATaXb (where a and b is a dimensions of matrix). * *XMFLOAT folks are to be used to just store values. It is just a plain floats. No operators defined for them and no functions, except XMLoad*/XMStore* accept them. *XMVECTOR and XMMATRIX is a work horses: they used in all functions and also have overloaded operators (which is not recommended to use. Use XM* functions instead). They use supersonic speed SSE internals. But.. it is a hard to use it to store values. For example, you will have alignment problems if you make XMVECTOR class member. *So, basically, you store and moving around your values in XMFLOATs, but before any calculations, you transform them to XMVECTOR and XMMATRIX, using XMLoad* functions (as you've done with XMVector3TransformCoord()), and after calculations, you transform them back to XMFLOATs, using XMStore* functions. Or you can gain a little more profit, by aligning properly your classes and structs, so you can store XMVECTOR and XMMATRIX directly (probably, you will need aligned memory allocator). Well, now you are ready to go. Happy porting! =)
unknown
d12799
train
Need somewhere for that value to return to. Try this: def update(): a = sqrt(10) b = 239 c = getTotal(a,b) print c def getTotal(a,b): num = a*b return num
unknown
d12800
train
I faced the same problem before, and it was not because of Json. It was because of sending too much requests to google in a period. So I just slow down the frequency of sending post to Google, and never seen this message again. A: what @ohyes means is that you send multiple (too much) requests to google using your API key in too short of a time (for example, over 100 in a minute - just an example). for that you are receiving the OVER_QUERY_LIMIT and the empty JSON array while you should consider changing the time between the requests, you should also verify that the array received in fact has any elements try { // Tranform the string into a json object final JSONObject json = new JSONObject(result); JSONArray routeArray = json.getJSONArray("routes"); if(routeArray.size() > 0) { JSONObject routes = routeArray.getJSONObject(0); JSONObject overviewPolylines = routes.getJSONObject("overview_polyline"); encodedString = overviewPolylines.getString("points"); List<LatLng> list = decodePoly(encodedString); } } catch (JSONException e) { e.printStackTrace(); } That would solve the exception being thrown, but it won't solve the fact that you are getting no result, probably because of the too much requests EDIT: The OVER_QUERY_LIMIT thing happens (probably) because of too fast calls to getJSONFromUrl() function. Please add the code that makes these calls so we could try and be more helpful on that. Probably 500 ms delay is not enough (I'm assuming you're doing this on a background thread and not Sleeping the UI thread as this is a bad habbit). try increasing the delay to something very high, such as a minute (60000 ms) and see if this helps. If it does, lower that number to the lowest one that works. And add the code please.
unknown