qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
29,571,502
I have an iPad app. I am creating an UIAlertController and adding a textfield. It crashes. It only crashes when I add a textfield. ``` let alert = UIAlertController(title: "Enter Name", message:nil, preferredStyle: UIAlertControllerStyle.Alert); alert.addTextFieldWithConfigurationHandler { (textfield:UITextField!) -> Void in textfield.placeholder = "Sexy time"; } alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: {(action:UIAlertAction!) -> Void in //Some action here })); self.presentViewController(alert, animated: true, completion: nil); ``` I get a fun crash telling me that the constraints are messed up. This code works fine in < 8.3 with no warnings. Even on a clean project with nothing in it but this code, it crashes - The project needs to be a splitview project on iPad. Here is the full stack trace plus bizarre constraint warnings which appears only after trying to add the textfield to alertController. ``` 2015-04-10 15:25:07.155 Observation[18235:281813] The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x7fb66cf9dfc0 UITableView:0x7fb66b855000.left == UIView:0x7fb66fae68e0.left> When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView _viewHierarchyUnpreparedForConstraint:] to debug. 2015-04-10 15:25:07.155 Observation[18235:281813] The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x7fb66cf9e010 UITableView:0x7fb66b855000.right == UIView:0x7fb66fae68e0.right> When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView _viewHierarchyUnpreparedForConstraint:] to debug. 2015-04-10 15:25:07.155 Observation[18235:281813] The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x7fb66fb37f90 UITableView:0x7fb66b855000.top == UIView:0x7fb66fae68e0.top> When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView _viewHierarchyUnpreparedForConstraint:] to debug. 2015-04-10 15:25:07.156 Observation[18235:281813] The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x7fb66fb80580 UITableView:0x7fb66b855000.bottom == UIView:0x7fb66fae68e0.bottom> When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView _viewHierarchyUnpreparedForConstraint:] to debug. 2015-04-10 15:25:13.589 Observation[18235:281813] View hierarchy unprepared for constraint. Constraint: <NSLayoutConstraint:0x7fb66cf9dfc0 UITableView:0x7fb66b855000.left == UIView:0x7fb66fae68e0.left> Container hierarchy: <UIView: 0x7fb66fa86e00; frame = (0 0; 0 0); layer = <CALayer: 0x7fb66fadf8e0>> | <UIView: 0x7fb66af3e080; frame = (0 0; 0 0); clipsToBounds = YES; layer = <CALayer: 0x7fb66fae32c0>> | | <_UIAlertControllerShadowedScrollView: 0x7fb66fa68c80; frame = (0 0; 0 0); clipsToBounds = YES; gestureRecognizers = <NSArray: 0x7fb66fa38a80>; layer = <CALayer: 0x7fb66fa97560>; contentOffset: {0, 0}; contentSize: {0, 0}> | | | <UIView: 0x7fb66fa87350; frame = (0 0; 0 0); layer = <CALayer: 0x7fb66fadf810>> | | | | <UILabel: 0x7fb66fa88740; frame = (0 0; 0 0); text = 'Enter Name'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x7fb66fa94ed0>> | | | | <UILabel: 0x7fb66fa73710; frame = (0 0; 0 0); userInteractionEnabled = NO; layer = <_UILabelLayer: 0x7fb66cc0ee10>> | | | | <UIView: 0x7fb66fae68e0; frame = (0 0; 0 0); clipsToBounds = YES; layer = <CALayer: 0x7fb66fa90160>> | | <UILabel: 0x7fb66fa3ad40; frame = (0 0; 0 0); userInteractionEnabled = NO; layer = <_UILabelLayer: 0x7fb66fa73680>> | | <UICollectionView: 0x7fb66c130200; frame = (0 0; 0 0); clipsToBounds = YES; gestureRecognizers = <NSArray: 0x7fb66faebab0>; layer = <CALayer: 0x7fb66fa3acf0>; contentOffset: {0, 0}; contentSize: {0, 0}> collection view layout: <_UIAlertControllerCollectionViewFlowLayout: 0x7fb66fae0b30> View not found in container hierarchy: <UITableView: 0x7fb66b855000; frame = (0 20; 768 1004); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x7fb66cf79f30>; layer = <CALayer: 0x7fb66cf600a0>; contentOffset: {0, 0}; contentSize: {768, 25}> That view's superview: NO SUPERVIEW 2015-04-10 15:25:13.594 Observation[18235:281813] *** Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to install constraint on view. Does the constraint reference something from outside the subtree of the view? That's illegal. constraint:<NSLayoutConstraint:0x7fb66cf9dfc0 UITableView:0x7fb66b855000.left == UIView:0x7fb66fae68e0.left> view:<UIView: 0x7fb66fa86e00; frame = (0 0; 0 0); layer = <CALayer: 0x7fb66fadf8e0>>' *** First throw call stack: ( 0 CoreFoundation 0x0000000102940c65 __exceptionPreprocess + 165 1 libobjc.A.dylib 0x000000010221dbb7 objc_exception_throw + 45 2 CoreFoundation 0x0000000102940b9d +[NSException raise:format:] + 205 3 Foundation 0x0000000101daf479 -[NSLayoutConstraint _addToEngine:integralizationAdjustment:mutuallyExclusiveConstraints:] + 187 4 UIKit 0x00000001039bca34 __57-[UIView(AdditionalLayoutSupport) _switchToLayoutEngine:]_block_invoke_2 + 474 5 Foundation 0x0000000101dbd1be -[NSISEngine withBehaviors:performModifications:] + 155 6 UIKit 0x00000001039bc83a __57-[UIView(AdditionalLayoutSupport) _switchToLayoutEngine:]_block_invoke + 452 7 UIKit 0x00000001039bc64d -[UIView(AdditionalLayoutSupport) _switchToLayoutEngine:] + 197 8 UIKit 0x00000001039bc933 __57-[UIView(AdditionalLayoutSupport) _switchToLayoutEngine:]_block_invoke_2 + 217 9 Foundation 0x0000000101dbd1be -[NSISEngine withBehaviors:performModifications:] + 155 10 UIKit 0x00000001039bc83a __57-[UIView(AdditionalLayoutSupport) _switchToLayoutEngine:]_block_invoke + 452 11 UIKit 0x00000001039bc64d -[UIView(AdditionalLayoutSupport) _switchToLayoutEngine:] + 197 12 UIKit 0x00000001039bc933 __57-[UIView(AdditionalLayoutSupport) _switchToLayoutEngine:]_block_invoke_2 + 217 13 Foundation 0x0000000101dbd1be -[NSISEngine withBehaviors:performModifications:] + 155 14 UIKit 0x00000001039bc83a __57-[UIView(AdditionalLayoutSupport) _switchToLayoutEngine:]_block_invoke + 452 15 UIKit 0x00000001039bc64d -[UIView(AdditionalLayoutSupport) _switchToLayoutEngine:] + 197 16 UIKit 0x00000001033b5717 __40-[UIView(Hierarchy) layoutBelowIfNeeded]_block_invoke + 39 17 Foundation 0x0000000101dbd1be -[NSISEngine withBehaviors:performModifications:] + 155 18 UIKit 0x00000001033b5556 -[UIView(Hierarchy) layoutBelowIfNeeded] + 320 19 UIKit 0x000000010374a394 -[_UIAlertControllerAnimatedTransitioning animateTransition:] + 470 20 UIKit 0x000000010344fa4e __56-[UIPresentationController runTransitionForCurrentState]_block_invoke + 1867 21 UIKit 0x000000010336562c _applyBlockToCFArrayCopiedToStack + 314 22 UIKit 0x00000001033654a6 _afterCACommitHandler + 533 23 CoreFoundation 0x0000000102873ca7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23 24 CoreFoundation 0x0000000102873c00 __CFRunLoopDoObservers + 368 25 CoreFoundation 0x0000000102869a33 __CFRunLoopRun + 1123 26 CoreFoundation 0x0000000102869366 CFRunLoopRunSpecific + 470 27 GraphicsServices 0x0000000106dd6a3e GSEventRunModal + 161 28 UIKit 0x0000000103341900 UIApplicationMain + 1282 29 Observation 0x0000000101612927 main + 135 30 libdyld.dylib 0x0000000104f60145 start + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException ```
2015/04/10
[ "https://Stackoverflow.com/questions/29571502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/947948/" ]
**Edit:** This fix changes depending on if you are building with Xcode 6 or Xcode 7, so I've added the relevant information for both versions of Xcode. --- I ran into this today and what it's saying is that it can't add the text field to the view controller's view or that it can't add auto-layout constraints to its superview. This seems to be because it hasn't created the superview to add it to yet, and so it all panics and crashes. Simple fix I found is add the text field after you tell the alert controller to present. That fixed it to me, though I'm not sure if it'll affect anything like the text field popping in as the alert is presenting. **Built with Xcode 6** ``` let alertController = UIAlertController(title: "Enter Name", message:nil, preferredStyle: .Alert) let okAction = UIAlertAction(title: "Ok", style: .Default) { (_) -> Void in // Some action here } alertController.addAction(okAction) presentViewController(alertController, animated: true, completion: nil) // Add any text fields after presenting the alert controller to fix crash in iOS 8.3 alertController.addTextFieldWithConfigurationHandler { (textfield) -> Void in textfield.placeholder = "Name" } ``` P.s. As a side note from your code example, remember with Swift, you don't need to use `;` at the end of every line, though it doesn't matter if you do. --- **Built with Xcode 7** When you build your app using Xcode 7, it seems like Apple have fixed the issue. Using the method shown above will no longer show a text field in iOS 9 (even though it still shows correctly in iOS 8). Below is a snippet of code, how it should have been the whole time, and when built in Xcode 7 it runs correctly in iOS 8 and iOS 9. ``` let alertController = UIAlertController(title: "Enter Name", message:nil, preferredStyle: .Alert) alertController.addTextFieldWithConfigurationHandler { (textfield) -> Void in textfield.placeholder = "Name" } let okAction = UIAlertAction(title: "Ok", style: .Default) { (_) -> Void in // Some action here } alertController.addAction(okAction) presentViewController(alertController, animated: true, completion: nil) ``` Tested in Swift 2.0 and Obj-C with Xcode 7 GM (7A218)
63,673,173
I am trying to implement the `ShaderMask` to only the background image in the container below with color `Color(0xFFFF0000)` and transparency `29%` but I am not able to do so, the below code I have implemented it is masking all the elements of the container, but I want only the background image in the below code to be masked, please guide me how should I do that? ``` ShaderMask ( shaderCallback: (rect){ return LinearGradient( begin: Alignment.center, end: Alignment.center, colors: [ Colors.transparent, Color(0xFFFF0000), ] ).createShader(Rect.fromLTRB(0, 0, rect.width, rect.height)); }, blendMode: BlendMode.color, child: Container( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, decoration: new BoxDecoration( image: DecorationImage( image: AssetImage('images/background.jpg',), fit: BoxFit.cover, ), ) child:Container() ) ) ```
2020/08/31
[ "https://Stackoverflow.com/questions/63673173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
**Using the stack and shader widget** ``` class BackgroundImageExample extends StatelessWidget { const BackgroundImageExample({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Stack( children: [ backgroudImage(), Scaffold( backgroundColor: Colors.transparent, body: SafeArea( child: Column( children: [ // your body content here ], ), ), ), ], ); } Widget backgroudImage() { return ShaderMask( shaderCallback: (bounds) => LinearGradient( colors: [Colors.transparent, Color(0xFFFF0000)], begin: Alignment.center, end: Alignment.center, ).createShader(bounds), blendMode: BlendMode.darken, child: Container( decoration: BoxDecoration( image: DecorationImage( image: AssetImage('images/background.jpg'), fit: BoxFit.cover, colorFilter: ColorFilter.mode(Colors.black45, BlendMode.darken), ), ), ), ); } } ```
68,541,546
**Note**: Not a duplicate problem.. here I need to skip empty arrays. Say I have several arrays like: ``` var a = [1, 2, 3, 4], b = [2, 4], c = [], d = [4]; ``` Using following function, I could get the desired result: `[4]` ```js var a = [1, 2, 3, 4], b = [2, 4], c = [], d = [4]; var res = [a, b, c, d].reduce((previous, current) => !previous.length || previous.filter((x) => !current.length || current.includes(x)), ); console.log(res) ``` I included `!current.length ||` above to bypass empty array `c`. But this doesn't work if first array in the collection i.e. `a` is empty. The result would be `[]`.
2021/07/27
[ "https://Stackoverflow.com/questions/68541546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1506282/" ]
You can add a `fill` in your `aes`. Data for the example: ``` df <- data.frame(SFC = c("z","f", "q", "h", "g", "n" , "o", "w"), share = sample(1:100, 8)) %>% arrange(share) SFC share 1 q 4 2 o 24 3 h 25 4 z 29 5 f 44 6 n 59 7 g 72 8 w 93 ``` Code: ``` ordre <- df$SFC ggplot(df,aes(x = SFC, y = share, fill = factor(rep(seq(1:2), each=4)))) + geom_col() + scale_x_discrete(limits = ordre) + labs(fill = "Legend") + scale_fill_discrete(labels = c("first","second")) ``` Output: [![Output](https://i.stack.imgur.com/RpUuG.png)](https://i.stack.imgur.com/RpUuG.png)
44,927,184
I am new to JSF 2.0 / PrimeFaces and I've created one webapp using JSF 2.0 + Spring 4. For session timeout, I've done below mapping in web.xml : ``` <session-config> <session-timeout>1</session-timeout> </session-config> <error-page> <exception-type>javax.faces.application.ViewExpiredException</exception-type> <location>/resources/login/timeout.xhtml</location> </error-page> ``` After login, user redirects to admin.xhtml in which there element as ``` <h:link value="showAnotherPage" outcome="other.xhtml"/> ``` But after 2 or 5 minutes, when I click on the link, it redirects me to other.xhtml page not on timeout page. Is anything that I'm missing to configure? Please help.
2017/07/05
[ "https://Stackoverflow.com/questions/44927184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1776616/" ]
I had this problem. You need to make sure there is no client call polling (ajax) server side resource, if this happens the session will not expire. I had a `<p:poll />` tag that didn't let the session expire.
3,909,763
ive had to solve $\,99x \equiv 18 \mod 30$ Firstly $\gcd(99,30)=3$ and $3 | 18$ so the equation has solutions. I can devide by $3$. So we get: $$33x \equiv 6 \mod 10$$ Since $\,\gcd(33,10)=1$ we can find an inverese to $33$ with the extended euclidean algorithm. I calculated: $(-3)33+10\*10=1$, so the inverse element should be $-3$ Now we write: $$(-3)33x \equiv (-3)6 \mod 10$$ which should give: $$x \equiv -18 \mod 10$$ So $x=10\*p + 8$ with $p\in \mathbb{Z}$ But when I try out the found $x$ the solution is simply wrong.. Actually I found by trying out, $x = 12$ does work.. I am really confused where I messed it up :( Can someone help? Thanks
2020/11/16
[ "https://math.stackexchange.com/questions/3909763", "https://math.stackexchange.com", "https://math.stackexchange.com/users/700036/" ]
Just reduce $\pmod {30}$ to $9x \equiv 18 \pmod {30}$ so that $x=2$ is a solution. Even further, dividing by $3$ we get $3x \equiv 6 \pmod {10}$ to see that $x\equiv 2 \pmod {10}$ is the set of solutions. Your solution isn't working because you have $-99x \equiv -18 \pmod {10}$ and to make this clear to you, add $100x$ to both sides so that $x \equiv -18 \equiv 2 \pmod {10}$. You could get to this instantly by noticing $99 \equiv -1 \pmod {10}$ as well.
47,431,325
My directory structure is ``` MyPhoto MyPhoto/css/myPhoto.css MyPhoto/images/fatherday1.jpg ``` In the css, I have defined following class ``` .jumbotron-welcome { background-image: url('../images/fathersday1.jpg'); background-size: cover; color:white; } ``` I notice that `url('../images/fathersday1.jpg');` works but `url('/images/fathersday1.jpg');` doesn't. Should `/images/..` path work? I suppose `MyPhoto` directory is root of my project and it has `images` folder.
2017/11/22
[ "https://Stackoverflow.com/questions/47431325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6703783/" ]
I'll try to explain: `../` means "go up one dir from where you are now". Your current working directory is `css`. You go up on, and then enter `images`. This is a legit path. When you start your resource with `/`, you start from the document root. You may see `/` as `http://example.com/`. So you are at the document root and try to enter `images`. But that doesn't exist. You first have to go into `myPhoto`: `url('/myPhoto/images/fathersday1.jpg');` *Please note that this is based on a simple server setup. If you use a more complex parser, the actual needed path may differ, but the logic remains. Figure out where the path `/` really starts.*
7,254,356
``` if (lblevent.Text == Request.QueryString["name"]) { string EventName = Request.QueryString["name"]; const string SQL = "SELECT SMS FROM Event WHERE EventName = @EventName"; using (SqlConnection con = new SqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true")) using (SqlCommand Command = new SqlCommand(SQL, con)) Command.Parameters.Add("@EventName", EventName); { con.Open();//at here the "con" has an error it says:"'con' does not exist on current context." } } ``` Actually i have already declared an sqlconnection(con) int he above code but it does not read it. Please someone help.. Thanks
2011/08/31
[ "https://Stackoverflow.com/questions/7254356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/917145/" ]
This is the problem: ``` using (SqlConnection con = new SqlConnection("...")) using (SqlCommand Command = new SqlCommand(SQL, con)) Command.Parameters.Add("@EventName", EventName); { con.Open(); ... } ``` That's equivalent to: ``` using (SqlConnection con = new SqlConnection("...")) { using (SqlCommand Command = new SqlCommand(SQL, con)) { Command.Parameters.Add("@EventName", EventName); } } { con.Open(); ... } ``` At that point I hope it's obvious what's wrong - when you call `con.Open` you're no longer within the `using` statement body. You want: ``` using (SqlConnection con = new SqlConnection("...")) using (SqlCommand Command = new SqlCommand(SQL, con)) { Command.Parameters.Add("@EventName", EventName); con.Open(); ... } ```
3,924,114
I would like to prove that $\int\_{0}^{1}\frac{\log(x))}{1-x^2}\,dx=-\sum\_{n=1}^{\infty}\frac{1}{(2n-1)^2}. $ I know that the RHS is equal to $-\frac{\pi^2}{8} $. Additionally, I have tried to make the substitution $x=\sin(u)$ to the integral, which leaves with $\int\_{u=0}^{\pi/2} \frac{\log(\sin(x))}{\cos(x)}\,dx $ but I can't seem to proceed from here.
2020/11/26
[ "https://math.stackexchange.com/questions/3924114", "https://math.stackexchange.com", "https://math.stackexchange.com/users/826212/" ]
There is no such thing as an "overall winner". Value $v=0.5$, means that (when the two players use the specified "optimal" strategies) then the first player's winnings average $0.5$ per play. Because of the random nature of the play, he wins some and loses some. If one player does not use the optimal strategy, then that $0.5$ will change in the other player's favor.
46,042,456
I have a string matrix ``` stringMatrix = ` 1 0 0 0 1 0 0 0 0 ` ``` And I want to convert it to a double array: `[[1,0,0], [0,1,0], [0,0,1]]`; what the js-y way of doing that? I've tried `matrix = values[0].trim().split('\n');`, but that will only do the outer layer: `["1 0 0", "0 1 0", "0 0 0"]`; I could do a for-loop, but I was wondering if there was a way with lambda expressions/fat arrows? //vanilla js
2017/09/04
[ "https://Stackoverflow.com/questions/46042456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4000964/" ]
Just splitting and mapping it would be the easies ```js var stringMatrix = ` 1 0 0 0 1 0 0 0 0 ` var res = stringMatrix.trim().split("\n").map( x => x.split(/\s+/).map(Number)) console.log(res) ```
7,829,269
Im trying to make a simple interactive flash animation so when you roll over a invisible button a sound plays from the library, then when you roll out the sound stops. So far i have this ``` import flash.events.Event; import flash.media.SoundChannel; stop(); button1.addEventListener(MouseEvent.ROLL_OVER,playSound); function playSound(event:Event) { var mySound:elmosample = new elmosample(); var myCahnnel:SoundChannel = mySound.play(); }` ``` Is there a way to stop the sound playing with ROLL\_OUT or stop the current sound when a new one starts?
2011/10/19
[ "https://Stackoverflow.com/questions/7829269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1004174/" ]
You should make the second button a property of your class. First declare the property in the .h+.m file just like the first one was automatically by xCode. Then at the end of your example code add self.secondButtonPropertyNameHere = button; Once it's a property of the class, any method can set it's properties. Edit: Instead of a UIButton property make an NSMutableArray property. Then just add the new button to the array so you can keep a reference to them. Just remember if you go to remove one call [buttonToRemove removeFromSuperview] and remove from the array. Edit(2): Your initial question was about making a second button and moving it around. The property of UIButton will work well for that. Because you're moving one object on the view receiving the touches\* events. If I were you I would stick with this approach until you are comfortable with the touches\* events. When you are ready to move on. You can manage multiple runtime created UIViews (in your case you want to use buttons) you have to choices: 1) In the touchesBegan: of your view controller iterate thru your array of buttons to see if perhaps the touch fell on one of them and then track the touch until the touchesEnded: call. 2) Subclass the UIView and let it handle it's own touches\* events. The second is much easier to manage. Edit(3): You will need to set `[button setUserInteractionEnabled:NO]` if you wish the superview to handle the touches\* events instead of the buttons.
16,252,210
Can someone suggest a text editor with code highlighting and template engine, or maybe a plugin? I need to edit long html files at my job, but there are a lot of templated actions like: ``` <p><span style="red">Text</span></p> ``` I need change to ``` <h1>Text</h1> ``` etc...and I want to automate them.
2013/04/27
[ "https://Stackoverflow.com/questions/16252210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2180005/" ]
As it says in the `$regex` docs you linked to, the two ways to do this are: ``` Field2: /Value_2/g ``` OR ``` Field2: { $regex: 'Value_2', $options: 'g' } ``` But I also tried your second attempt of `'Field2': { $regex: /Value_2/g }` and that worked as well. BTW, the `g` regex option doesn't make sense in this context as you just need one match anyway. Note that it isn't even listed in the `$regex` docs.
45,859,996
I have an Icon drawn via PaintCode. I need to change his color in XCode, programmatically. On PaintCode, I set a Variable "ChevronColor" to the Stroke Color. [![enter image description here](https://i.stack.imgur.com/uI6vN.png)](https://i.stack.imgur.com/uI6vN.png) [![enter image description here](https://i.stack.imgur.com/WqLpA.png)](https://i.stack.imgur.com/WqLpA.png) For now I have: ``` @IBDesignable class IconClass: UIView { override func draw(_ rect: CGRect) { StyleKit.drawIcon(frame: self.bounds, resizing: .aspectFit) } } ``` But I would like to add kind of this, to be able to set the color of the icon. ``` @IBInspectable var ChevronColor : UIColor { didSet (newColor) { setNeedsDisplay() } } ``` I don't know how to do. After exporting the StyleKit file, I excepted to have this method available in the stylekit file, but it's not the case: ``` StyleKit.drawIcon(frame: self.bounds, resizing: .aspectFit, chevronColor: self.ChevronColor) ```
2017/08/24
[ "https://Stackoverflow.com/questions/45859996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2123039/" ]
> > TL/DR > > > Create an expression that takes `red`, `green`, `blue`, `alpha` (`external parameters` in PaintCode) and generates a color (`makeColor` function in PaintCode). The generated color is then assigned to the `Stroke`, `Fill`, whatever, via that expression. > > PaintCode > > > [![PaintCode](https://i.stack.imgur.com/mz3OF.jpg)](https://i.stack.imgur.com/mz3OF.jpg) > > Custom View > > > ``` import Foundation import UIKit @IBDesignable class TreeView: UIView { /* * * Notice - supported range for colors and alpha: 0 to 1. * Color 0.808, 0.808, 0.808 = gray (starting color in this example). * */ @IBInspectable var redColor: CGFloat = 0.808 { didSet { setNeedsDisplay() } } @IBInspectable var greenColor: CGFloat = 0.808 { didSet { setNeedsDisplay() } } @IBInspectable var blueColor: CGFloat = 0.808 { didSet { setNeedsDisplay() } } @IBInspectable var alphaColor: CGFloat = 1 { didSet { setNeedsDisplay() } } override func draw(_ rect: CGRect) { StyleKit.drawTreeIcon(frame: rect, resizing: .aspectFit, red: redColor, green: greenColor, blue: blueColor, alpha: alphaColor) } } ``` > > Changing color example > > > ``` @IBAction func colorButtonPressed(_ sender: UIButton) { // Get color references. let red = CIColor(color: sender.backgroundColor!).red let green = CIColor(color: sender.backgroundColor!).green let blue = CIColor(color: sender.backgroundColor!).blue let alpha = CIColor(color: sender.backgroundColor!).alpha // Update the PaintCode generated icon. treeView.redColor = red treeView.greenColor = green treeView.blueColor = blue treeView.alpha = alpha } ``` > > Demo > > > ![Example](https://github.com/backslash-f/paintcode-tests/raw/master/Resources/Screenshots/dynamicColorsExample.gif) > > Reference > > > The project can be [cloned from my GitHub repo.](https://github.com/backslash-f/paintcode-tests) Also take a look at [the PaintCode Expression Language guide.](https://www.paintcodeapp.com/documentation/expressions)
102,116
Consider a hypothetical scenario with an 18 year old living in the state of Maryland in the United States, in his freshman year of college studying for a four-year degree in an engineering field. He solely depends on his father (mother is not in the picture anymore), who makes a respectably above-average salary for the area. Consider said father has just passed away, leaving the teen with >$500,000 from his retirement fund alone, along with a car (leaving the teen with having two vehicles now) and other inheritances that do not include any land. They were originally renting a 2-bedroom apartment and the teen commuting to college, but now the teen needs to figure out how to live on his own without a large income. The apartment is too expensive for him to justify continuing to live in alone. He has the skills to make ~$30k-$35k per year in full-time work as-is, but only currently makes ~$8k per year in part time work. The way I see it, he has two major options: **Minimize cost of living and finish college:** If he moves all the things he doesn't need into storage and lives on-campus or in a cheap studio apartment close to the campus he can minimize the amount of money he spends until he graduates, and use the inheritance to finish debt-free and can get a job that pays over $60k-$80k per year to start. He can use the money that's left to purchase a house later. **Enter the workforce immediately:** If he gets a reasonable job and uses the inheritance to purchase a home close to his place of work, he should be able to stabilize himself enough that he can resume studies to finish his degree over a longer period of time (debt-free). Are there better options for a young adult surviving the loss of all his providers, or is there something I'm not considering? Answers should be purely in terms of economic viability in any general scenario similar to the one above (though specific examples are not discouraged as they can be useful in illustrating your point), and the teen continuing life without wasting what he has to work with and staying above the poverty line.
2018/11/15
[ "https://money.stackexchange.com/questions/102116", "https://money.stackexchange.com", "https://money.stackexchange.com/users/78882/" ]
Consider the difference between this situation and that of a student financing their education through loans. The size of this inheritance is more than sufficient for a student to graduate from a 4-year university debt free, as opposed to with debt of $30k or more (depends on the school, obviously). I would strongly recommend the student finish their education before joining the workforce full-time. Many people find it difficult to motivate themselves to finish their education while making money, even when the amount they could be making with a degree like engineering is multiple times more. If the plan before the death of the father was to attend college, the plan should remain to attend college.
68,690
> > (Psalm 119:94-96  NASB1995 ) > > > 94 I am Yours, save me; For I have sought > Your precepts. 95 The wicked wait for me to destroy me; I shall > diligently consider Your testimonies. 96 I have seen a limit to all > perfection; Your commandment is exceedingly broad. > > > > > (Psalm 119:94-96 New King James Version) > > > 94 I am Yours, save me; For I > have sought Your precepts. 95 The wicked wait for me to destroy me, > But I will consider Your testimonies. 96 I have seen the consummation > of all perfection, But Your commandment is exceedingly broad. > > > > > 119:94-96 The Westminster Leningrad Codex > > > 94 לְֽךָ־אֲ֭נִי הוֹשִׁיעֵ֑נִי כִּ֖י פִקּוּדֶ֣יךָ דָרָֽשְׁתִּי׃ > > > 95 לִ֤י קִוּ֣וּ רְשָׁעִ֣ים לְאַבְּדֵ֑נִי עֵ֝דֹתֶ֗יךָ אֶתְבּוֹנָֽן׃ > > > 96 לְֽכָל תִּ֭כְלָה רָאִ֣יתִי קֵ֑ץ רְחָבָ֖ה מִצְוָתְךָ֣ מְאֹֽד׃ > > > As we try to read & understand Psalm 119:94-96 , what is the author of Psalm 119 trying to convey in terms of meaning with the term/phrase "limit to all perfection"/"consummation of all perfection"  ? Furthermore, could someone please evaluate/assess the Old Testament Hebrew translation of the aforementioned term/phrase, and post an elaborate response on what it means?
2021/09/13
[ "https://hermeneutics.stackexchange.com/questions/68690", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/15888/" ]
Sabaoth is the transliteration of *tsavaot*, which is the plural form of the hebrew word *tsava*. This word is the denominative of the verb *tsiva*, which means “go into battle, fight”[1] When taken as a noun, it means *the units* that go into battle and fight, and thus it can refer to armies, companies, *groups of men that are going into battle.* From that basic militaristic usage you can form metaphors that give rise to other meanings. E.g. when I say "I will send a brigade of lawyers to your door", I don't mean that the lawyers are part of a military unit sent to kill you. What I do mean is that those lawyers are there to attack you in some metaphorical sense. There is a militarism to my choice of the word "brigade of lawyers" that is not present if I merely said "group of lawyers", but nevertheless the sense of this usage is as a collection, not an actual military unit. Now if that phrase "brigade of lawyers" becomes commonly used over time, that militaristic aspect can fade from consciousness and people might come to think of it more as "group of lawyers". For example, "a troop of boyscouts" or "Salvation Army" have pretty much lost any militaristic connotation, but when these terms were first coined, that sense *was* intentionally there as both groups had a militaristic nature. Over time, these things are forgotten and today, one might argue that "troop" has an alternate meaning of "group of boyscouts" and thus is a generic word for "group". This type of semantic drift is especially true with something like a Bible translation, especially the KJV that shaped the English language. Many metaphors used in the KJV have become so common and have been used in so many other contexts that the original context has been lost and people forget that they are metaphors. The KJV changed the meaning of the words themselves so that phrases like "the array of heavenly hosts" have lost their militaristic connotation to modern readers, but the original author of the Bible as well as the King James translators certainly intended to include this connotation when they used military language to describe the groups of stars/angels. In the case of stars, the idea is (most likely) that they are marching in formation and/or deployed to their positions as commanded by their general, the Creator. In this sense, some believe that *tsavaot* does not carry a militaristic sense but is just a generic word for collection or group. For these people, "Jehovah Sabaoth" just means "the Lord of Collections [of men/angels/stars]". But this is incorrect. The meaning is "*Lord of Armies*", or "*The Lord that Leads us into battle"* or "*The Lord that fights for me*" -- and we can see this from the Hebrew usage in the OT: Use of YHWH Sabaot in the book of 1 Samuel: * 1 Sam 1.11 -- To avenge the affliction of the handmaid Hannah, who is in bitterness of soul after being taunted for being barren. * 1 Sam 4.3 -- To help in battle with the Phillistines * 1 Sam 15.1 -- Before waging war on the Amaleks * 1 Sam 17.45 -- When David fights Goliath etc. This is certainly the sense in the passage cited in James, where James is *threatening* those who withhold wages by appealing to Jehovah Sabaoth -- *the God that will fight on behalf of those who are being oppressed*. This is the avenging God. If you erase that militaristic connotation, then you erase an important part of the meaning of the word, and you make the choice of James' language much more mysterious than it needs to be. There is nothing mysterious about Sabaot -- it means that *God will fight* for those who are being robbed and is supposed to invoke fear in the heart of employers. --- [1] Ringgren, H. (2003). צָבָא. G. J. Botterweck & H.-J. Fabry (Eds.), D. W. Stott (Trans.), Theological Dictionary of the Old Testament (Revised Edition, Vol. 12, p. 211). Grand Rapids, MI; Cambridge, U.K.: William B. Eerdmans Publishing Company.which has a primary meaning "army" or other military unit (e.g. company, etc).
28,323,468
At multiple instances, I came across algorithms where first queue head is peeked and then removed. I was wondering if there is any particular reason why poll is not used instead. For example the following algorithm for level order traversal of a binary tree [HERE](http://www.careercup.com/question?id=8635794) 1. Add the root node to the queue. 2. Assign queue size to a variable, say count. Repeat step 3 to 7 count times, where N is the size of the queue. 3. If the queue is not empty, print out the queue. 4. Peek the head node 5. If the head has left child, add it to the queue 6. If the head has right child, add it to the queue 7. Remove the head from the queue. 8. If the queue is not empty, go back to step 2.
2015/02/04
[ "https://Stackoverflow.com/questions/28323468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969107/" ]
Some containers only offer peek and remove, because with a function that does both, it's hard or impossible to give the strong exception guarantee: <http://en.wikipedia.org/wiki/Exception_safety>
33,259,952
How would one run aws lambda locally (java) for testing. I was able to find some information for node, but not for java.
2015/10/21
[ "https://Stackoverflow.com/questions/33259952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133932/" ]
AFAIK there is no magic to actually triggering the lambda function locally. Take a look at: <http://docs.aws.amazon.com/lambda/latest/dg/java-programming-model-req-resp.html> and <http://docs.aws.amazon.com/lambda/latest/dg/java-gs.html> Depending what your lambda code does you need to build the input and (possibly the context) and pass them into the function writing your own small test wrapper. Unless you are doing this for unit testing it does not make sense to go through the trouble though. If you are doing this for testing you will probably need to mock out other external AWS services that your lambda might use.
35,879,790
I have a user search for a school and then tap on the one they want. In cellForRowAtIndexPath I query for the school that was selected and get its objectId. I then set the objectId to the pointer, "school\_name" in within PFUser.currentUser. The pointer goes to the "Schools" class where all of the schools are listed. I am getting an error that says, "invalid type for key school\_name, expected \*Schools, but got string (Code: 111, Version: 1.12.0)". I can't seem to get around it as the objectId is a string. I can even print the objectId getting the right one. ``` func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let spinningActivity = MBProgressHUD.showHUDAddedTo(self.view, animated: true) spinningActivity.labelText = "Just a Moment" spinningActivity.detailsLabelText = "Adding Details" let schoolIndexPath = tableView.indexPathForSelectedRow! let selectedCell = tableView.cellForRowAtIndexPath(schoolIndexPath)! as UITableViewCell let school : String = String(selectedCell.textLabel!.text!) let schoolObjectIdQuery = PFQuery(className:"Schools") schoolObjectIdQuery.whereKey("school_name", matchesRegex: school) let query = PFQuery.orQueryWithSubqueries([schoolObjectIdQuery]) if reachabilityStatus == kNOTREACHABLE { spinningActivity.hide(true) self.displayAlert("No Internet Connection", message: "Please connect to the internet before continuing.") } else { query.findObjectsInBackgroundWithBlock { (results: [PFObject]?, error: NSError?) -> Void in if error != nil { self.displayAlert("Error", message: error!.localizedDescription) } if let objects = results { self.searchResults.removeAll(keepCapacity: false) for object in objects { let schoolObjectId = object.objectId! let addDetails : PFUser = PFUser.currentUser()! // let schoolObjectIdFormatted = PFObject(withoutDataWithClassName: "school_name", objectId: schoolObjectId) addDetails.setObject(schoolObjectId, forKey: "school_name") print(school) print(schoolObjectId) addDetails.saveInBackgroundWithBlock({ (success:Bool, error:NSError?) -> Void in if error != nil { spinningActivity.hide(true) self.displayAlert("Error", message: error!.localizedDescription) } if success { spinningActivity.hide(true) self.dismissViewControllerAnimated(true, completion: nil) print("Success") } }) } } } } } ```
2016/03/08
[ "https://Stackoverflow.com/questions/35879790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5697162/" ]
Try [SQLite](https://www.sqlite.org/). It's a lightweight high-performance database with modern features like indexes, transactions, and so on. There are ADO.NET components for it also. It works great, it's open-source, and it's free. The only downside to SQLite is that it doesn't come with a tool to view and manipulate a database, but you can download [a separate tool](http://sqlitebrowser.org/) for that. You could also use Microsoft Access. You would need to have a copy of Access installed to create a new database, but the OLE DB components needed to modify or access the database are part of Windows. Microsoft Access's database engine isn't as fast or as reliable as SQLite, but if you have Access installed then you have nice tools to view the database, create new tables, and so on.
619,769
I have windows 8.1 64 bit with an on-board network card (\*[LAN: Intel® Gigabit Ethernet Controller driver for Windows 8.1](https://downloadcenter.intel.com/Detail_Desc.aspx?DwnldID=23795)\*\*) Now - please notice : I have created an Acronis IMG right after installing Windows & basic programs (office,antivirus). My computer topology : ``` ----> router ----> computer ``` Ok. **Prior** to logmein installation - I could awake my computer from sleep (S3 IMHO) just by trying to connect to the computer via : `myDynDnsName:3389` ( router redirect port 3389 to my pc) (**notice:** I could do it from WAN / iphone / from-work) The computer would wake up ! and then I could see the login screen. I think it used "wake-on-**link**" as you can [see here](http://driveragent.com/c/archive/17228/image/7-0-92?PHPSESSID=b4rkfhbbhf2cd644h4itrs7fm5): > > Wake on Link Settings > > > Wakes the computer **if the network connection establishes link** while > the computer is in standby mode. You can enable the feature, disable > it, or let the operating system use its default. > > > I believe that's my case. All ok. So where is the problem ? After installing LogMeIn (and after resetting the computer) - the computer stopped from waking up (while sleep..) ! After uninstall LogMeIn - (and restart) - the computer still didn't awake from sleep! Just to make sure it was LogMeIn - I restored(Acronis) my computer to the state before logMeIn installation - and the functionally was back! - I was able to wake the computer while sleep. **Question** What should I do in order to wake my computer like I used to ? ( while keeping logMeIn). nb today it's logmein - tomorrow it can be OtherLogMeIn... Also - there is a checkbox in LogMeIn preferences("wakeOn**Lan**") this is checked in my computer. ( but again- there is no lan here - IMHO). Notice : I don't have the regular powere management screen in device manager but : ![enter image description here](https://i.stack.imgur.com/uBsUu.png)
2014/08/12
[ "https://serverfault.com/questions/619769", "https://serverfault.com", "https://serverfault.com/users/95007/" ]
Use Powershell to Remove Network Boot Devices from the Boot Order ----------------------------------------------------------------- You can use PowerShell to strip the `Network` `BootType`s from the VMs boot order. ### Extract the Current Boot Order Using Powershell you can use this command to extract the current boot order: ``` $old_boot_order = Get-VMFirmware -VMName testvm -ComputerName MyHyperVHost ` | Select-Object -ExpandProperty BootOrder ``` If you inspect `$old_boot_order` You should see the list of boot devices for `testvm`. Something like this: ![enter image description here](https://i.stack.imgur.com/P7PAA.png) ### Strip the Network Boot Devices You can strip the boot devices from the boot list with the `Network` `BootType` using this command: ``` $new_boot_order = $old_boot_order | Where-Object { $_.BootType -ne "Network" } ``` Inspecting `$new_boot_order` should look something like this with no more `Network` boot devices: ![enter image description here](https://i.stack.imgur.com/3cSey.png) ### Set the New Boot Order To set the new boot order for the VM use this command: ``` Set-VMFirmware -VMName testvm -ComputerName MyHyperVHost -BootOrder $new_boot_order ``` ### Confirm the New Boot Order To confirm what you did use that first `Get-VMFirmware` command again: ``` Get-VMFirmware -VMName testvm -ComputerName MyHyperVHost ` | Select-Object -ExpandProperty BootOrder ``` --- *Beware: If you use both PowerShell and Hyper-V manager to make changes to the boot order, PowerShell may report erroneous (out-of-date) boot order. See also [this technet thread](http://social.technet.microsoft.com/Forums/en-US/4fcce488-e4f4-41c2-9d15-1eedc89a6f68/why-dont-the-boot-orders-in-powershell-and-hyperv-manager-match).*
27,693,339
So I am building an app, I have a user model managed by devise, and a post model, post belongs\_to user and user has\_many posts, now I have a page where I show all posts ``` <% @posts.each do |post| %> <div id="post"> <%= post.user.name%> <%= post.course_name %> <%= post.course_number %> <%= image_tag post.user.image_string %> <% if post.user == current_user%> <%= link_to "Edit", edit_post_path(post) %> <%= link_to "Delete", post_path(post), method: :DELETE, data: { confirm: 'Are you sure?' } %> <% end %> </div> <% end%> <%= link_to "profile", '/posts/profile' %> ``` What I want to do is click on the image of the user above, and it should take me to his profile. I thought about the following : Create an action: ``` def show_profile end ``` Then in the `show_profile.html.erb` I would say : ``` <%[email protected] %> ``` in my routes I would add : ``` get '/posts/show_profile' ``` then I would add `<%=link_to image_tag post.user.image_string, posts_show_profile_path(post) %>` Would this work? is this the best I can do? Thanks
2014/12/29
[ "https://Stackoverflow.com/questions/27693339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3247496/" ]
`.hasClass('someClass')` will help you to retrieve a *boolean* `true/false` > > [api.jquery.com/hasclass](http://api.jquery.com/hasclass): Determine whether any of the matched elements are assigned the given class. The .hasClass() method will return `true` if the class is assigned to an element > > > ``` $(document).ready(function () { $('[data-toggle="offcanvas"]').click(function () { $('.row-offcanvas').toggleClass('active'); var act = $('.row-offcanvas').hasClass("active"); if(act){ $('.btn').html("HIDE"); }else{ $('.btn').html("SHOW"); } }); }); ``` a shorter way using a [Conditional Operator (AKA Ternary operator)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) would be: ``` $(function() { // DOM ready $('[data-toggle="offcanvas"]').on("click", function () { var $row = $('.row-offcanvas').toggleClass('active'); $('.btn').html($row.hasClass("active") ? "HIDE" : "SHOW"); }); }); ``` Also I have to warn you that by selecting elements like `$(".btn")` will alter **every single** `.btn` element on the page. Make always sure to use the right selectors with the help of `.find()` (or similar Selector methods). for specificity sake.
184,496
I'm thinking of using a LGPLv3 library in a closed source commercial program running in a closed embedded environment. According to what I know from LGPLv3 licensing, I can use it as long as the closed source software dynamically links with the LGPLv3 library and leaves the freedom to the user to change or update the LGPLv3 library by changing the library binaries. Since my software runs in a closed, controlled, validated environment, it would be really odd to respect the part of allowing the user to change the LGPLv3 library. I could add a functionality to my environment allowing to update the library binaries, but it would be odd to present this functionality to our customers since they would have no interest into changing that library and would see that as a security hole, so they'll want us to remove it (or restrict the access to no one). Is adding an update binary functionality the only way to respect LGPLv3 ? If by using it, I require to call my company to give access to it (by a password), Will I still respect the license ?
2013/01/22
[ "https://softwareengineering.stackexchange.com/questions/184496", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/79195/" ]
I am, of course, not a lawyer, so this is just my reading of the relevant licenses. Now, in the LGPL, we're talking section 4.d.1, "Use a suitable shared library mechanism", and 4.e, "Provide Installation Information". Now, 4.e says you have to provide installation info per section 6 of the GPL v3. First off, can your device be upgraded? If it can't, then the 'Installation instructions' are moot and you don't have to do anything - GPL, section 6, third paragraph from the end "But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM)." Assuming your device is upgradable (and so few devices aren't anymore) what happens if your device doesn't fit the definition of a 'User Product'? And is your device a User Product? Because if I'm reading section 6 of the GPL v3 correctly, you only have to provide Installation Instructions for consumer goods - stuff sold to consumers, or for use in houses. My reading of this is that industrial stuff (for instance, the medical monitors that my company makes) wouldn't be covered by the 'Installation Instructions' requirement. If my reading is correct, and if you aren't making consumer goods, then you're in the clear. Obviously you'd want to check that with a lawyer, but I suspect you are good without it.
3,409,582
I need to read the data in an **Access 97** file that has about 400K records. I would like to use either **TurboDelphi Pro** or **dBASE SE**. I only have **Access 2003**. What is the easiest way of proceeding
2010/08/04
[ "https://Stackoverflow.com/questions/3409582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15654/" ]
If you decide to go with TurboDelphi, you can use the ADOConnection component on the [dbGo tab](http://docwiki.embarcadero.com/RADStudio/en/DbGo_Overview). When you Configure the connection string, use the Jet driver and point to your .mdb file. Then use the [ADO controls](http://docwiki.embarcadero.com/RADStudio/en/DbGo_Controls) to get at the data.
150,846
I'm using a great addon called ["Cycle Cameras"](https://blender.stackexchange.com/a/27098/3710) made by @CoDEmanX for *Blender 2.79b* which I'd like to use in *Blender 2.8x* as well. Fortunately there already is an [updated version](https://blender.stackexchange.com/a/137359/3710) by @Matthias & @batFINGER. However, I can't get it to work properly. Everytime I try to install it via *User Preferences > Install from File* the addon doesn't show up in the list. I tried to install it in Blender v2.80 and v2.81 without any success. [![addon install atempt](https://i.stack.imgur.com/FzJHA.jpg)](https://i.stack.imgur.com/FzJHA.jpg) *What am I doing wrong? How to install the updated version properly?*
2019/09/05
[ "https://blender.stackexchange.com/questions/150846", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/63246/" ]
If the name of the directory of the addon contains "."s and "-"s remove them. Rename the directories name in a way, that it only contains characters a-z and A-Z. Close Blender, reopen blender and check for the addon.
73,878,667
I wrote this code in HTML, which is very very long. I used ngSwitch for 3 cases and in the default case I have 4 different small cases. All of these cases used the same structure of icon. How could I make my HTML shorter? How could I remove the business logic from HTML? The rule to show different icons is: **Serviceflag (boolean) > warnflag (boolean) > serviceflag (boolean) > timekey(number)** For Example: If the code includes all of them then the icon of Serviceflag should be shown. If the code includes warnflag and timekey then the icon of warnflag should be shown. ```html <ng-template #defaultModalHeaderTemplate> <app-device-status-information *ngIf="status" [statusInformation]="status" ></app-device-status-information> <app-device-status-information *ngIf="information" [statusInformation]="information" ></app-device-status-information> </ng-template> <div class="fit-h fit-v d-flex d-col" [ngSwitch]=" !(status.warnFlag && !status.serviceFlag && !status.errorFlag) || !(status.errorFlag && !status.serviceFlag) " > <div style="background-color: rgba(241, 90, 34, 0.1)" class="fit-h fit-v d-flex d-col" *ngSwitchCase="status.warnFlag && !status.serviceFlag && !status.errorFlag" > <div class="row" style="padding: 36px 0px 24px 24px"> <div class="col-sm-2"> <ng-container> <i c8yicon="warning" class="text-warning dlt-c8y-icon-warning" style="font-size: 80px" ng-reflect-c8y-icon="warning" ></i> </ng-container> </div> <div class="col-sm-10"> <ng-container *ngTemplateOutlet="defaultModalHeaderTemplate"></ng-container> </div> </div> </div> <div *ngSwitchCase="status.errorFlag && !status.serviceFlag" style="background-color: rgba(217, 30, 24, 0.1)" class="fit-h fit-v d-flex d-col" > <div class="row" style="padding: 36px 0px 24px 24px"> <div class="col-sm-2"> <ng-container style="background-color: bg-dark-warning"> <i c8yicon="exclamation-circle" class="text-danger dlt-c8y-icon-exclamation-circle" style="font-size: 80px" ng-reflect-c8y-icon="exclamation-circle" ></i> </ng-container> </div> <div class="col-sm-10"> <ng-container *ngTemplateOutlet="defaultModalHeaderTemplate"></ng-container> </div> </div> </div> <div *ngSwitchDefault> <div class="row"> <div class="col-sm-2" style="padding-left: 48px"> <ng-container *ngIf="status.serviceFlag"> <i c8yicon="wrench" class="text-complementary dlt-c8y-icon-wrench" style="font-size: 80px" ng-reflect-c8y-icon="wrench" ></i> </ng-container> <ng-container *ngIf=" information.timeKey === 1 && !status.warnFlag && !status.serviceFlag && !status.errorFlag " > <i c8yicon="check-circle" class="text-success dlt-c8y-icon-check-circle" style="font-size: 80px" ng-reflect-c8y-icon="check-circle" ></i> </ng-container> <ng-container *ngIf=" (information.timeKey === 2 || information.timeKey === 3 || information.timeKey === 4 || information.timeKey === 6) && !status.warnFlag && !status.serviceFlag && !status.errorFlag " > <i c8yicon="stop-circle" class="text-info dlt-c8y-icon-stop-circle" style="font-size: 80px" ng-reflect-c8y-icon="stop-circle" ></i> </ng-container> <ng-container *ngIf=" information.timeKey === 5 && !status.warnFlag && !status.serviceFlag && !status.errorFlag " > <i c8yicon="exclamation-circle" class="text-muted dlt-c8y-icon-exclamation-circle" style="font-size: 80px" ng-reflect-c8y-icon="exclamation-circle" ></i> </ng-container> </div> <div class="col-sm-10"> <ng-container *ngTemplateOutlet="defaultModalHeaderTemplate"></ng-container> </div> </div> </div> </div> ```
2022/09/28
[ "https://Stackoverflow.com/questions/73878667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18399818/" ]
```js function MyComponent() { const [state, setState] = useState(""); return <SomeJsx/>; } ``` When you call `setState`, the constant `state` does *not* change. Instead, `MyComponent` is called again, with `useState` now returning the updated value. This value is assigned to the `state` constant but this is part of a different function invocation, so it's actually not the same constant.
13,275,461
I have a problem with an advanced loop, this are my arrays ``` $array1 = array(1,2,3); $array2 = array(4,5); $array3 = array(6,7,8,9); $array4 = array(10,11); ``` I want to loop with the following result: 1. 1,4,6,10 2. 1,4,6,11 3. 1,4,7,10 4. 1,5,7,11 With the last: 3,5,8,11 How can I do that?
2012/11/07
[ "https://Stackoverflow.com/questions/13275461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1037534/" ]
Solution for a variable number of arrays. Can probably be written a bit shorter, but I leave that to you. ;) ``` <?php $array1 = array(1,2,3); $array2 = array(4,5); $array3 = array(6,7,8,9); $array4 = array(10,11); function turboArray() { $arrays = func_get_args(); $indexes = array_fill(0, count($arrays), 0); function turboSubArray(&$arrays, &$indexes, $l){ for ($a = 0; $a < count($arrays[$l]); $a++){ $indexes[$l] = $a; if ($l == count($arrays) - 1) { for ($i = 0; $i < count($indexes); $i++) { echo $arrays[$i][$indexes[$i]]; if ($i == count($indexes) - 1){ echo "\n<br/>"; $indexes[$i] = 0; if ($i == 0) return; } else { echo ', '; } } } else if ($l < count($indexes)) { turboSubArray($arrays, $indexes, $l + 1); } } } $l = 0; turboSubArray($arrays, $indexes, $l); } turboArray($array1, $array2, $array3, $array4); ```
13,198,266
How Can I Create Custom View Like This ? like this ![enter image description here](https://i.stack.imgur.com/aHucA.jpg) Anyone Have Tutorials to make view like left hand side view?
2012/11/02
[ "https://Stackoverflow.com/questions/13198266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1260838/" ]
This is a good tutorial -> <http://www.raywenderlich.com/1768/how-to-make-a-custom-uiview-a-5-star-rating-view> Or just make a google search. You need to subclass UIView and make your own drawing using other UIView subclasses (UILabel, UIImageView, ...) or your own CoreGraphics. For your example you can make one UIView for the exterior rectangle and another for the interior. You can use view.layer border (you will need CG). The other things are simply UILabel's and UIImageView's.
15,778,135
What exactly happens when an int is converted to a long? For example: ``` a = sys.maxint-1 a = a+2 ``` What happened in the statement of `a = a + 2`? How does the Python interpreter handle the overflow ?
2013/04/03
[ "https://Stackoverflow.com/questions/15778135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1839117/" ]
First, > > int and long were "unified" a few versions back. Before that it was possible to overflow an int through math ops. > > > 3.x has further advanced this by eliminating int altogether and only having long. > > > Based on question here, [How does Python manage int and long?](https://stackoverflow.com/questions/2104884/how-does-python-manage-int-and-long) Also, there is no longer a limit on `integers` according to <http://docs.python.org/3.1/whatsnew/3.0.html> > > The sys.maxint constant was removed, since there is no longer a limit > to the value of integers. However, sys.maxsize can be used as an > integer larger than any practical list or string index. It conforms to > the implementation’s “natural” integer size and is typically the same > as sys.maxint in previous releases on the same platform (assuming the > same build options). > > > **Basically**: *Python seamlessly converts a number that becomes too large for an integer to a long.* Docs [here](http://docs.python.org/release/1.4/ref/ref5.html)
41,748,144
I've found answers to do with sums but the only use + or \* in their examples so unsure whether I could do it with the '/4' at the end. Thanks for any feedback.
2017/01/19
[ "https://Stackoverflow.com/questions/41748144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5748426/" ]
Instead of: ``` obj_ex = Model(column=value, column2=value2) ``` Which creates a new instance (and later a new db record) try: ``` o = Model.objects.get(pk=1234) # load instance with id=1234 to memory from db o.column = value o.column2 = value2 o.save() ```
1,245,704
I have a windows mobile app that look like this: ``` class Program { static void Main(string[] args) { RunHook runHook = new RunHook(); } } class RunHook { private HookKeys hook; public RunHook() { hook = new HookKeys(); hook.HookEvent += EventForHook; } private void EventForHook(HookEventArgs e, KeyBoardInfo keyBoardInfo, ref Boolean handled) { if ((keyBoardInfo.scanCode == 4) && (keyBoardInfo.vkCode == 114)) handled = true; } } ``` It will create a hook into the keyboard (I know that is frowned on by some). My issue is that I need the Main method to never return. This is going to run on devices owned by my company and we are using this to disable the phone hardware keys. This seems like it should be simple, but I am stuck on it. On normal .NET I would just call `Console.Readline()`, but that does not work on Windows Mobile Compact Framework. I have also tried `Thread.Sleep(0)`, but it does not work either. Thanks for any feedback.
2009/08/07
[ "https://Stackoverflow.com/questions/1245704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16241/" ]
`Thread.Sleep(0)` sleeps for zero milliseconds. You probably want `Thread.Sleep(Timeout.Infinite)`. You might also consider creating an `EventWaitHandle`: ``` class Program { static public ManualResetEvent StopMain; static void Main(string[] args) { StopMain = new ManualResetEvent(false); RunHook runHook = new RunHook(); StopMain.WaitOne(); // waits until signalled } } ``` Then, if you were ever ready to exit Main(), you could call (from another thread): ``` Program.StopMain.Set(); ```
5,752,897
I need a search box and a submit button that will open my input in multiple tabs as the search result from multiple search engines. Thanks.
2011/04/22
[ "https://Stackoverflow.com/questions/5752897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/720145/" ]
The way you described what you want to do does not require you to use Ajax. Ajax is for loading data from the web and updating parts of the page that the user is on, with Ajax you can update the page without moving to a new page. Since you asked to open new tabs, Ajax has nothing to do with it. ``` <html> <head> <script type="text/javascript"> function performSearch() { var searchTerm = encodeURIComponent(document.getElementById('searchField').value); window.open('http://www.google.com/search?q=' + searchTerm, 'new_window_1'); window.open('http://search.yahoo.com/search?p=' + searchTerm, 'new_window_2'); // open more tabs here ... } </script> </head> <body> <input id="searchField" type="text" /> <input type="button" value="click me" onclick="performSearch();" /> </body> </html> ``` --- > > Can you tell me how to make the search field to perform search after pressing enter? > > > The quick way: if we make our text field a part of an actual HTML form, and make our javascript function run when the user submits the form - that will cause the function to run when the user clicks enter inside the text field, because clicking enter inside a text box that is part of a form submits the form. ``` <html> <head> <script type="text/javascript"> function performSearch() { var searchTerm = encodeURIComponent(document.getElementById('searchField').value); window.open('http://www.google.com/search?q=' + searchTerm, 'new_window_1'); window.open('http://search.yahoo.com/search?p=' + searchTerm, 'new_window_2'); // open more tabs here ... } </script> </head> <body> <form onsubmit="performSearch(); return false;"> <input id="searchField" type="text" /> <input type="submit" value="click me" /> </form> </body> </html> ``` Now the type of the button input is 'submit', so when the user clicks the button the form should get submitted, and we have an event handler on the form - the 'onsubmit' - this runs when the user clicks the button or presses enter inside the search field. We add 'return false;' so that nothing actually happens after our function runs - the form doesn't actually get submitted (because when you submit a form you usually send information somewhere, we don't do that here, it's like a pseudo-form).
73,812,865
I have a basic table inside of a form, but the function addData doesn't seem to run when I click the `Add` button. How can I fix it? I am trying to make an automatic table to keep track of the needed information. ```js document.getElementById('DateField').valueAsDate = new Date(); function addData() { var store_price = document.getElementById("price"); var store_moneyback = document.getElementById("moneyback"); var store_profit = document.getElementById("profit"); var store_date = document.getElementById("DateField"); var store_gametype = document.getElementById("gametype"); var table = document.getElementById("dymanictable"); var rowCount = table.rows.length; var row = table.insertRow(rowCount); row.insertCell(0).innerHTML = store_price.value; row.insertCell(1).innerHTML = store_moneyback.value; row.insertCell(2).innerHTML = store_profit.value; row.insertCell(3).innerHTML = store_date; row.insertCell(4).innerHTML = store_gametype; } ``` ```html <form> <table id='dymanictable'> <tr> <td><label for="price">Price:</label><br></td> <td> <input type="text" id="price" name="price"><br></td> </tr> <tr> <td> <label for="moneyback">Money back:</label><br></td> <td> <input type="text" id="moneyback" name="moneyback"><br></td> </tr> <tr> <td> <label for="profit">Profit:</label><br></td> <td> <input type="number" id="profit" name="profit" min="-100" max="100"><br></td> </tr> <tr> <label for="DateField">Current date:</label> <input type="date" id="DateField" name="DateField" readonly> </tr> <tr> <td> <label for="gametype">Gametype:</label></td> <td> <select id="gametype" name="gametype"> <option value="cashgame">Cash game</option> <option value="twister">Twister</option> <option value="blackjack">Blackjack</option> <option value="sitgo">Sit&Go</option> </select> </td> </tr> </table> <br> <button onclick="addData()">Add</button> </form> ```
2022/09/22
[ "https://Stackoverflow.com/questions/73812865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20060380/" ]
My suggestion is I can see redundancy in your isEmpty function. You can re-write your function like this: > > > ``` > if (!isEmpty(values)) { > if (!isSSH) return true; > if (!isActive) return !card.hidden; // Executed if(isSSH & !isActive) > return false; // Only executed if(isSSH & isActive) > } > > ``` > > See, when you are adding a return inside an if(!something) check, then the further code execution will only happen if it will opposite scenario (like - if(something)). So any check for if(something) in further code is redundant. Edit: I also do not recommend the ternary operator in this case because I believe in the one-line -> one-action philosophy which makes code easier to read and understand during the quick vertical scan. Edit 2: You will need to return true/false (as per your requirement) outside of the if(!isEmpty(){...}) case. As a practice, you should have consistent returns.
44,151,062
I have created a web application. I am using SQL 2012 express as a database. Its working fine when I am running on debug mode. When I deployed that application on local IIS it's throwing an error > > Cannot open database "databaseName" requested by the login. The login failed. > Login failed for user 'IIS APPPOOL\MyApplicationName'. > > > My connection string is `<add name="DefaultConnection" connectionString="Data Source=HAPPY\SQLEXPRESS;uid=sa;password=123;Initial Catalog=dwm;integrated security=sspi;" providerName="System.Data.SqlClient" />` I am able to login with this login detail on my SQL 2012 express. I am attaching a screenshot [![enter image description here](https://i.stack.imgur.com/byDQm.jpg)](https://i.stack.imgur.com/byDQm.jpg).
2017/05/24
[ "https://Stackoverflow.com/questions/44151062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4335742/" ]
You are using `SSPI` Integrated Security, thus it is trying to use Windows authentication. Try setting to `False`: ``` connectionString="Data Source=HAPPY\SQLEXPRESS;uid=sa;password=123;Initial Catalog=dwm;integrated security=False;" providerName="System.Data.SqlClient" ```
27,858,171
``` <plugin> <groupId>com.samaxes.maven</groupId> <artifactId>minify-maven-plugin</artifactId> <version>1.7.2</version> <executions> <execution> <phase>process-resources</phase> <goals> <goal>minify</goal> </goals> </execution> </executions> <configuration> <charset>UTF-8</charset> <skipMerge>true</skipMerge> <webappSourceDir>WebContent</webappSourceDir> <cssSourceDir>/</cssSourceDir> <jsSourceDir>/</jsSourceDir> <nosuffix>false</nosuffix> <webappTargetDir>${project.build.directory}/minify</webappTargetDir> <cssSourceIncludes> <cssSourceInclude>**</cssSourceInclude> </cssSourceIncludes> <cssSourceExcludes> <cssSourceExclude>**/*.min.css</cssSourceExclude> </cssSourceExcludes> <jsSourceIncludes> <jsSourceInclude>**</jsSourceInclude> </jsSourceIncludes> <jsSourceExcludes> <jsSourceExclude>**/*.min.js</jsSourceExclude> </jsSourceExcludes> </configuration> </plugin> ``` I am using maven-minify-plugin to minify js and css files and added above code in pom.xml.Now this works fine but it tries to minufy all files including xml and html files. How can I stop minifying xml and html and other files?
2015/01/09
[ "https://Stackoverflow.com/questions/27858171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33411/" ]
I assume you want to show your element, do this with [`jquery.show`](http://api.jquery.com/show/), you can then delay (if necessary using [`jquery.delay`](http://api.jquery.com/delay/)) and finally you can queue up (using [`jquery.queue`](http://api.jquery.com/queue/)) the removal of the "Yellow" class and addition of the "Green" class. ```js function DoIt() { $('#divState').show(100).delay(1000).queue(function(){ $(this).removeClass("Yellow").addClass("Green"); $.dequeue(this) }); } ``` ```css div { display: none; } div.Green { border: 1px solid black; background-color: #93EEAA; } div.Yellow { border: 1px solid black; background-color: #FFEE99; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="button" class="button" onclick="DoIt()" value="run" /> <div class="Yellow" id="divState">Some Text</div> ```
1,724,191
I have set up replication for MySQL server. I can connect from the slave machine to the master server using the replication user/password. I have got the slave SQL thread running, but the slave [I/O](http://en.wikipedia.org/wiki/Input/output) thread is not running and the slave I/O status comes as empty when checked using 'show slave status'. What could be the problem? How do I solve this? Restarting the slave does not help. This was my bad: Instead of giving a 'replication slave' privilege to `*.*`, I was only giving it for `my_db.*`.
2009/11/12
[ "https://Stackoverflow.com/questions/1724191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/153911/" ]
> > Instead of giving a 'replication > slave' privilege to ., I was only > giving it for my\_db.\*. > > > Replication slave is only a global privilege (i.e. per-user only), this means that a command such as ``` GRANT REPLICATION SLAVE on mydb.* TO 'someuser'@'%'; ``` has no effect as you can't grant it per-database/column/table. The command you need to run is: ``` GRANT REPLICATION SLAVE on *.* TO 'someuser'@'%'; ``` Then do a `START SLAVE`. You might also find it useful to look in the mysql error log. I'd suggest a good read of the [replication setup documentation](http://dev.mysql.com/doc/refman/5.0/en/replication-howto.html), as it explains all of this in detail.
63,740,788
I am getting this message in the console every time I navigate to another screen: ``` [Assert] displayModeButtonItem is internally managed and not exposed for DoubleColumn style. Returning an empty, disconnected UIBarButtonItem to fulfill the non-null contract. ``` Currently I have navigation view set up in the entry point of the app like so ``` NavigationView { KeyboardView(matrixVM: matrixVM, isNavigationBarHidden: $isNavigationBarHidden) .background(Color("background") .edgesIgnoringSafeArea(.all)) .navigationBarTitle("Workspace") .navigationBarHidden(self.isNavigationBarHidden) .onAppear { self.isNavigationBarHidden = true } } ``` And then inside the KeyboardView I have the navigationlink ``` NavigationLink(destination: NotebookView(isNavigationBarHidden: $isNavigationBarHidden, saved: matrixVM), label: { Text("Notebooks") .font(.system(size: 14, design: .rounded)) .fontWeight(.medium) .foregroundColor(Color("text")) .padding(.trailing, 10) }) ``` Inside the NotebookView I have a list of navigation links (each notebook linking to its detail page) ``` ScrollView(showsIndicators: false) { ForEach(notebooks, id: \.self) { notebook in NavigationLink(destination: ExpandedSnippet(matrixVM: saved ,notebook: notebook) .navigationBarTitle("Notebook", displayMode: .inline)) { SnippetCard(notebook: notebook, matrixVM: saved) .frame(width: UIScreen.main.bounds.width) } .padding(.bottom, 30) } } ``` Everything seems to be working but just a few hours ago it didn't (I was using tabbar and it suddenly started crashing after working for weeks). I feel like it's a bit of a mess and I am doing something wrong. Any idea why? Thanks for the help!
2020/09/04
[ "https://Stackoverflow.com/questions/63740788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11387293/" ]
I am getting this with Xcode 12.1 when running on the iPhone or iPhone simulator but not the iPad simulator. Attaching this to the NavigationView fixed it for me. ``` .navigationViewStyle(StackNavigationViewStyle()) ```
25,956,906
I have seen lot of questions like this but none of them helped me I want to see when my span tag get available in DOM, my code looks like this ``` <span id="inviteUpdate">0</span> if(jQuery("#inviteUpdate").html()>0){ alert("Element exists"); } ``` Am I missing something here?
2014/09/21
[ "https://Stackoverflow.com/questions/25956906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4060322/" ]
If you want to test whether an element exists in the DOM, use `.length`: ``` if ($("#inviteUpdate").length > 0) { alert ("Element exists"); } ``` This is because jQuery collections can be used as arrays, returning the original DOM elements that were matched.
36,053,413
I am using this ``` redisManager.redisClient.keys('*example*', function (err, keys) { }) ``` But it only gives keys from only one of the redis cluster. How can I get keys from all cluster?
2016/03/17
[ "https://Stackoverflow.com/questions/36053413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4390898/" ]
You can't get keys for all nodes using a single command. You have to get keys for all nodes and merge them. Reference - <https://github.com/antirez/redis/issues/1962> You can do something like. ``` var redis = require('redis'); redisConfig = new Array( {"port": 1234, "host": "192.168.1.2"}, {"port": 5678, "host": "192.168.1.3"} ); keys = new Array(); allKeys = new Array(); for(i = 0; i < redisConfig.length; i++){ redisClient = redis.createClient(redisConfig[i].port, redisConfig[i].host); keys[i] = redisClient.keys('*example*', function (err, keys) { allkeys = [...new Set([...allKeys ,...keys[i]])]; }) } ```
316,841
I'm trying to learn more about the dig command and have come across the `-x` option which is meant for reverse lookup, i.e. you give an IP address and get back a domain name. I tried doing `dig -x www.google.com` which I guess doesn't really make sense with the `-x` option, but I got back this response: ``` ; <<>> DiG 9.9.4-RedHat-9.9.4-29.el7_2.3 <<>> -x www.google.com ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 2959 ;; flags: qr rd ra ad; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1 ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags:; udp: 4096 ;; QUESTION SECTION: ;com.google.www.in-addr.arpa. IN PTR ;; AUTHORITY SECTION: in-addr.arpa. 3180 IN SOA b.in-addr-servers.arpa. nstld.iana.org. 2015074802 1800 900 604800 3600 ;; Query time: 0 msec ;; SERVER: 128.114.142.6#53(128.114.142.6) ;; WHEN: Sun Oct 16 17:06:24 PDT 2016 ;; MSG SIZE rcvd: 124 ``` Can anybody help me get a better understanding of what this reponse tells us, I thought you weren't supposed to use the `-x` option with a domain name.
2016/10/17
[ "https://unix.stackexchange.com/questions/316841", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/193065/" ]
Notice in the response that you got back `status: NXDOMAIN` and `ANSWER: 0`. This means there was no record found matching your query. The `-x` option to `dig` is merely a convenience for constructing a `PTR` query. It splits on dots, reverses it, appends `in-addr.arpa.`, and sets the type to `PTR`. The information you did get back is the SOA record for the authoritative domain (`in-addr.arpa`), and is for result caching. Negative lookups (queries which have no results) can be cached for a duration as specified in the SOA record. See [RFC-2308](https://www.rfc-editor.org/rfc/rfc2308#section-3): > > Name servers authoritative for a zone MUST include the SOA record of > the zone in the authority section of the response when reporting an > NXDOMAIN or indicating that no data of the requested type exists. > This is required so that the response may be cached. The TTL of this > record is set from the minimum of the MINIMUM field of the SOA record > and the TTL of the SOA itself, and indicates how long a resolver may > cache the negative answer. > > >
14,386,077
I'm trying to create a couple hotstrings using arrow keys to select cells for the formula that is created. ``` :*:=concacane:: send =CONCATENATE({right},{right 2},{right 3}) return ``` The above is the code that I was hoping would work to call the 'CONCATENATE' function and select the three cells to the right of the cell I was typing in. Unfortunately Excel seems to escape the cell I was working in, and I end up with commas and parenthesis spread across a few cells to the right instead of the working formula I was looking for. I tried using 'sendraw' and adding everything after '=CONCATENATE(' on a second 'send' line hoping that the '=' was some kind of modifier that was messing me up, but that didn't seem to help. I also tried using a key combination instead of a hotstring but I couldn't get that script to do anything at all and a key combination would be less than ideal anyway... Does anybody have any idea how I can get this to work? Thanks in advance!
2013/01/17
[ "https://Stackoverflow.com/questions/14386077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1988168/" ]
In class `Number` you define a conversion operator to `int` and your constructor allows converting an `int` to a `Number`. Therefore, when comparing a `Number n` and an `int x` for equality, ambiguity arises: should the compiler invoke the built-in `operator ==` for `int`s and convert `n` to an `int`, or should it rather pick your operator and convert `x` to a `Number`? Both conversions are equally good, and it can't choose one. So yes you have to define three versions, or add a template operator which can perfectly match the type of all arguments and forward to your operator explicitly, like this one (but you most likely want to guard it with some `enable_if` to limit its applicability only to the appropriate `T` and `U`): ``` template<typename T, typename U> // beware: this will match anything. to be constrained bool operator == (T n, U const& u) { return (Number(n) == Number(u)); } ```
108,146
I am trying to include an image on the part title page of my report, so that it looks like this, but shows up correctly in the ToC: ``` \clearpage \newpage {\pagestyle{empty} \enlargethispage{10\baselineskip} {\huge\textbf{Part I: Lorem Ipsum}}\\ \noindent\rule{\textwidth}{0.4pt} \begin{center} \includegraphics[width=\textwidth]{figures/part_1_title.pdf} \end{center} \clearpage} \newpage ``` A similar question has been asked [here](https://tex.stackexchange.com/questions/40602/redefine-memoir-part-to-allow-image), but for me the `\printparttitle` produces an error. Does someone know how to do this? An other similar question was asked in an other forum: [here](http://forum.mathematex.net/latex-f6/personnaliser-la-page-d-une-nouvelle-partie-en-mode-book-t8212.html). I tried to modify the defnition of `\part` from the `report.cls` file to actually get the title of the Part to look different, but it didn't work. (I need the space for the picture). What it looks like: **Part I Lorem Ipsum** What I want it to look like **Part I: Lorem Ipsum** which is obtained by this code: ``` {\pagestyle{empty} \enlargethispage{10\baselineskip} {\huge\textbf{Part I: Lorem ipsum}}\\ \noindent\rule{\textwidth}{0.4pt} \begin{center} \includegraphics[width=\textwidth]{figures/PartI_Loerm.pdf} \end{center} ``` Does someone have an idea?
2013/04/11
[ "https://tex.stackexchange.com/questions/108146", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/31834/" ]
Add the image typesetting to the command `\@endpart`: ``` \makeatletter \newcommand{\imagepart}[1]{\def\@theimagepart{#1}\part} \def\@endpart{% \par\medskip \hrule \begin{center} \includegraphics[width=\textwidth]{\@theimagepart} \end{center} \vfil\newpage \if@twoside \if@openright \null \thispagestyle{empty}% \newpage \fi \fi \if@tempswa \twocolumn \fi} \makeatother ``` Complete example (the `demo` option is just for the example) ``` \documentclass{report} \usepackage[demo]{graphicx} \makeatletter \newcommand{\imagepart}[1]{\def\@theimagepart{#1}\part} \def\@endpart{% \par\medskip \hrule \begin{center} \includegraphics[width=\textwidth]{\@theimagepart} \end{center} \vfil\newpage \if@twoside \if@openright \null \thispagestyle{empty}% \newpage \fi \fi \if@tempswa \twocolumn \fi} \makeatother \begin{document} \imagepart{figures/part_1_title.pdf}{Part title} \end{document} ``` ![enter image description here](https://i.stack.imgur.com/4IILo.png) A possible redefinition also of `\@part`, with some minor modifications to `\@endpart`, in order not to have line breaks in the title. ``` \documentclass{report} \usepackage[demo]{graphicx} \makeatletter \newcommand{\imagepart}[1]{\def\@theimagepart{#1}\part} \def\@endpart{% \par\vskip12pt\hrule\vskip12pt {\centering \includegraphics[width=\textwidth]{\@theimagepart}\par} \vfil\newpage \if@twoside \if@openright \null \thispagestyle{empty}% \newpage \fi \fi \if@tempswa \twocolumn \fi} \def\@part[#1]#2{% \ifnum \c@secnumdepth >-2\relax \refstepcounter{part}% \addcontentsline{toc}{part}{\thepart\hspace{1em}#1}% \else \addcontentsline{toc}{part}{#1}% \fi \markboth{}{}% {\centering \interlinepenalty \@M \normalfont \ifnum \c@secnumdepth >-2\relax \huge\bfseries \partname\nobreakspace\thepart: \fi #2\par} \@endpart} \makeatother \begin{document} \imagepart{figures/part_1_title.pdf}{Part title} \end{document} ``` ![enter image description here](https://i.stack.imgur.com/IK7RS.png) If you want to move up the part title, you have to change the `\vfil` in the definition of `\part`; for instance, by adding ``` \renewcommand\part{% \if@openright \cleardoublepage \else \clearpage \fi \thispagestyle{plain}% \if@twocolumn \onecolumn \@tempswatrue \else \@tempswafalse \fi \null\vspace{\stretch{1}} \secdef\@part\@spart} ``` and changing the `\vfil` in the redefinition of `\@endpart` to `\vspace{\stretch{2}}` you'll have twice as much space at the bottom than at the top. --- Final version ============= Left of the picture the result of `\imagepart`, right your wish. ``` \documentclass{report} \usepackage[demo]{graphicx} \makeatletter \newcommand{\imagepart}[1]{\def\@theimagepart{#1}\part} \def\@endpart{% \par\vskip12pt\hrule\vskip12pt {\centering \includegraphics[width=\textwidth]{\@theimagepart}\par} \vfil\newpage \if@twoside \if@openright \null \thispagestyle{empty}% \newpage \fi \fi \if@tempswa \twocolumn \fi} \renewcommand\part{% \if@openright \cleardoublepage \else \clearpage \fi \thispagestyle{empty}% \if@twocolumn \onecolumn \@tempswatrue \else \@tempswafalse \fi \null\vspace{-2\baselineskip} \secdef\@part\@spart} \def\@part[#1]#2{% \ifnum \c@secnumdepth >-2\relax \refstepcounter{part}% \addcontentsline{toc}{part}{\thepart\hspace{1em}#1}% \else \addcontentsline{toc}{part}{#1}% \fi \markboth{}{}% {\raggedright \interlinepenalty \@M \normalfont \ifnum \c@secnumdepth >-2\relax \huge\bfseries \partname\nobreakspace\thepart: \fi #2\par} \@endpart} \makeatother \begin{document} \imagepart{figures/part_1_title.pdf}{Part title} \clearpage \newpage {\pagestyle{empty} \enlargethispage{10\baselineskip} {\huge\textbf{Part I: Lorem Ipsum}}\\ \noindent\rule{\textwidth}{0.4pt} \begin{center} \includegraphics[width=\textwidth]{figures/part_1_title.pdf} \end{center} \clearpage} \newpage \end{document} ``` ![enter image description here](https://i.stack.imgur.com/Rx2ho.png) ### Addition 2022 How to add some description text below the image? Here's a possibility. ``` \documentclass{report} \usepackage{graphicx} \makeatletter \newcommand{\imagepart}[2]{% \def\@theimagepart{#1}% \def\@thecaptionpart{#2}% \part } \def\@endpart{% \par\medskip \hrule \begin{center} \includegraphics[width=\textwidth]{\@theimagepart} \\ \@thecaptionpart \end{center} \vfil\newpage \if@twoside \if@openright \null \thispagestyle{empty}% \newpage \fi \fi \if@tempswa \twocolumn \fi} \makeatother \begin{document} \imagepart{example-image}{Description}{Part title} \end{document} ``` Apply the formatting you wish around the call of `\@thecptionpart`. [![enter image description here](https://i.stack.imgur.com/JQ8gV.png)](https://i.stack.imgur.com/JQ8gV.png)
26,595,416
As you all know, external resources, like images, can be embedded into the html file using base64 encoding: ``` <img src="data:image/png;base64,iVBORw0KGgoAAAANS..." /> ``` I'm looking for **a pure browser-based javascript** way to traverse an html page and embed all the external resources into the file so when I say `$("html").html()`, it returns all the page's contents. Even including its external resources. Just so it makes sense, I'm trying to download web pages into single files using a headless browser on my server.
2014/10/27
[ "https://Stackoverflow.com/questions/26595416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/866082/" ]
There are tools out there to do that. Examples: * <https://github.com/remy/inliner> * <https://github.com/jgallen23/grunt-inline-css> * <https://github.com/ceee/grunt-datauri> While there are benefits to this approach, remember that a page visited more than once, or site with multiple pages with same JS/CSS files will enjoy client (browser) side caching.
42,972,381
I'm currently working with AngularJs and am filtering an input array with a number of select boxes. On the filtered result, I'm running an ng-repeat to display each element in my now filtered array. Now my question. I want to save the filtered input array as an javascript variable, to later display or print the whole result. I actually only want either the filtered input array saved to a javascript variable or even better, the results of each ng-repeat saved altogether in a variable but updating itself after applying a new filter or a filter again. I'm stuck here. Is there a smooth way to do this. Or do you have a even better idea what would work here? Thank's already. Let's say we have a filter for languages and name: ``` <select class="form-control" ng-options="l.language for l in languages" ng-model="languageModel" ></select> <select class="form-control" ng-options="n.name for n in names" ng-model="nameModel" ></select> <ul ng-repeat="sq in input| filter:languageModel| filter:nameModel> <li>Language: {{sq['Language']}}</li> <li>Name: {{sq['Name']}}</li> </ul> ``` Now I want something like : $scope.var = ... // The filtered result.
2017/03/23
[ "https://Stackoverflow.com/questions/42972381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7755726/" ]
You can directly store the array in your `ng-repeat` ``` <ul ng-repeat="sq in (filteredInput = (input| filter:languageModel| filter:nameModel))> ``` Now you can access `$scope.filteredInput` to get the filtered array
29,722,673
I have a `tabBarController` and two `UINavigationControllers` with `UITableViews` attached to the `tabBarController`. See picture below. ![<code>tabBarController</code> setup](https://i.stack.imgur.com/MXvGH.png) I have subclassed the `tabBarController` so I can pass an array of custom objects between the two tables by reference. Whenever I load the tabs, however, the items are not appearing. They are still able to be selected but you just can't see them. The below picture shows the `tabBar` with none of the `items` showing ![<code>tabBar</code> with <code>items</code> not visible](https://i.stack.imgur.com/ydrJU.png) I have a feeling it is because I am instantiating the `viewControllers` and the `UINavigationController` is not loading. I am just not sure how to go about having the `UINavigationController` to load first. **The code I am using is below:** ``` var table1 : AllPlacesViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("AllPlaces") as AllPlacesViewController var table2:AttendingPlacesTableViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("AttendingPlaces") as AttendingPlacesTableViewController table1.delegate = self table2.delegate = self var navController1 = UINavigationController(rootViewController: table1) var navController2 = UINavigationController(rootViewController: table2) self.viewControllers = [navController1, navController2] ``` The reason I set them up like this is because I want to share data between the `viewControllers` by reference.
2015/04/18
[ "https://Stackoverflow.com/questions/29722673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4233107/" ]
Did you use the "Editor|Embed In" option to embed the Navigation Controllers in the Tabbar? That is very important! Tabbars with Navigation Controllers were a problem in older versions but this XCode function helps to solve issues like this I think.
22,912,158
I'm using Xcode (version 5.3) to compile OpenCL kernels to bitcode, as explained in WWDC 2013 session 508. Xcode generates 4 different files, each with a different extension according to the architecture for which it has been targeted for. The extensions are: cl.gpu\_32.bc , cl.gpu\_64.bc , cl.x84\_64.bc, cl.i386.bc In session 508, they only load a single file (The one with the cl.gpu\_32.bc extension and use it). Is it possible to generate a single cl\_program that support all devices associated with the context? How do I know which architecture to use for each of the available devices? A sample code that reads all files and generate a single cl\_program would be very helpful.
2014/04/07
[ "https://Stackoverflow.com/questions/22912158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/868331/" ]
Use simple check ``` if (usermailid != null) ```
28,245,058
sorry if this is not the right forum for this question but I can't find the answer anywhere. I'm working on a raspberry pi project which requires the SPI module to be loaded. I can't get it to load. Here's what I've done ``` sudo apt-get update sudo apt-get upgrade sudo rpi-update ``` Here's what my blacklist.conf file looks like ``` #blacklist spi and i2c by default (many users don't need them) #blacklist spi-bcm2708 blacklist i2c-bcm2708 ``` I've rebooted several times with no luck. When I run `sudo uname -a` I get ``` Linux raspberrypi 3.18.5+ #744 PREEMPT Fri Jan 30 18:19:07 GMT2015 armv6l GNU/Linux ```
2015/01/30
[ "https://Stackoverflow.com/questions/28245058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2115971/" ]
See <http://www.raspberrypi.org/forums/viewtopic.php?f=28&t=97314> Fixed my i2c and one-wire interfaces. This is required with the new kernal upgrade to 3.18.5 on Jan 21st.
119,335
TrueCrypt and its successors use a file format that has the special property, that it looks *completely random*, there's only a salt (which is random) and the cipher text (which looks random). I like to call this the "TrueCrypt-Paradigm". **Is there *any* advantage to using the TrueCrypt-Paradigm as opposed to introducing non-random data such as key-derivation parameters?** Bonus points if you can find a situation where the (theoretical) advantage actually helps / saves / whatevers you. To be explicit: I do *not* ask about the disadvantages which include, but are not limited to: * Inflexible password based key derivation * Inflexible cipher selection
2016/04/02
[ "https://security.stackexchange.com/questions/119335", "https://security.stackexchange.com", "https://security.stackexchange.com/users/71460/" ]
Yes, there is a very real advantage. Take this hypothetical, but very likely scenario. You are storing something Very Bad(*tm*) that you absolutely do not want the police to find. Your opsec is pretty good, but you make a single mistake online, and the cops are on their way. It's 4 AM in the morning, and they burst in with a fresh warrant for a no-knock raid. You stand by helpless as they take every single device in your house, all of your dozen flash drives and SD cards, your hard drives, laptops, etc. Days later, they confront you again, asking you if any of your flash drives are encrypted with something called "TrueCrypt". They know you are tech savvy enough to use it, but they also know you are tech savvy enough to wipe your flash drives. They have no idea whether or not you encrypted it, or you simply wiped it. They can't force the key out of you, they can't lock you up for refusing to give them the key, and most importantly, they can't spend a long time trying to crack all of your dozen either-wiped-or-encrypted devices because spending too much time on a single case gets investigators in a lot of trouble. Because you used TrueCrypt, the devices which you simply wiped blend in perfectly with the devices you have encrypted. You're let free after the cops are reprimanded by an angry judge who regrets signing the warrant in the first place. This example is especially potent in countries with mandatory key disclosure laws, where if they have evidence that you are hiding encryption, they can lock you up. If you can claim that you simply wiped your hard drive and it's all random data (which is especially plausible if you have a spare CD with DBAN burnt on it lying around), then no matter how much they want you, they'll have a very hard time getting you locked up. But even in countries without such laws, it's still an extremely good idea to prevent your adversary from knowing where to focus their efforts, or even knowing that they have found what they are looking for. Note that this "TrueCrypt-Paradigm" is *much* more effective on entire disks. It is significantly less effective when used as individual volumes, because it's not that easy to explain away a large, random file sitting on your hard drive, especially if TrueCrypt is installed on that system. Not as easy as it is to explain away a hard drive with random data, where even if TrueCrypt is installed on some computer in your house, it still isn't even close to enough evidence to point to *that* specific hard drive being encrypted rather than just wiped.
34,834,897
I was started using bootstrap version 4. And started receiving this error deploying to Heroku. my stylesheet is custom.css.scss. App works in development with not problem. Issued did not start to upgraded to bootstrap v4. When I was using the bootstrap v3 I did not have this problem with deployment ever.I have spend lot of reviewing different suggestions from other posts to no avail. bootstrap.custom.css.scss file ``` @import "bootstrap"; ``` applications.scss ``` /* *= require_tree . *= require_self */ ``` application.js ``` = require jquery = require tether = require bootstrap-sprockets = require jquery_ujs = require turbolinks = require_tree . ``` Error from heroku deployment ``` rake aborted! Sass::SyntaxError:File to import not found or unreadable:bootstrap-sprockets. remote: Load paths: remote: /tmp/build_9899a15a0b71b25c23a9b8dfc6d02e80/app/assets/images remote:/tmp/build_9899a15a0b71b25c23a9b8dfc6d02e80/app/assets/javascripts remote:/tmp/build_9899a15a0b71b25c23a9b8dfc6d02e80/app/assets/stylesheets remote:/tmp/build_9899a15a0b71b25c23a9b8dfc6d02e80/vendor/assets/javascripts remote:/tmp/build_9899a15a0b71b25c23a9b8dfc6d02e80/vendor/assets/stylesheets ``` Gemfile ``` gem 'rails', '4.2.0' gem 'pg' gem 'sass-rails', '>= 5.0' gem 'uglifier', '>= 1.3.0' gem 'coffee-rails', '~> 4.1.0' gem 'jquery-rails' gem 'turbolinks' gem 'jbuilder', '~> 2.0' gem 'sdoc', '~> 0.4.0', group: :doc ``` Installed gems ``` gem 'bootstrap', '~> 4.0.0.alpha3' gem 'sass', '~> 3.4', '>= 3.4.21' gem 'sprockets-rails', '~> 3.0' source 'https://rails-assets.org' do gem 'rails-assets-tether', '>= 1.1.0' end gem 'rails_12factor', group: :production gem 'font-awesome-rails', '~> 4.4.0.0' gem 'pry-rails', :group => :development gem 'autoprefixer-rails', '~> 6.0.3' gem 'devise', '~> 3.5.2' gem 'friendly_id', '~> 5.1.0' gem 'simple_form' ```
2016/01/17
[ "https://Stackoverflow.com/questions/34834897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3905353/" ]
Firstly, your regex would check for `1`, `19`, `199`, `1999` etc., not for "19 or 10". The regex for "starts with 19 or 10" would be `^1[90]`. Secondly, if you quote the regex, it is matched as a string, i.e., literally. You could use ``` if [[ $ip =~ ^1[90] ]]; then ``` It is good practice to store the regex in a separate variable and then use that variable, unquoted, to avoid all quoting issues: ``` re='^1[90]' if [[ $ip =~ $re ]]; then ``` References: * [Bash manual about conditional constructs](https://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs) * BashGuide [page about patterns](http://mywiki.wooledge.org/BashGuide/Patterns) (see regex section) * [Chet's FAQ](http://tiswww.case.edu/php/chet/bash/FAQ) at E14
49,027,248
I have the following df which is at tick level: ``` aud_tick <- data.frame(stringsAsFactors=FALSE, aud_time = c("2018-02-25 21:55:38.098", "2018-02-25 21:55:38.398", "2018-02-25 21:55:41.099", "2018-02-25 21:55:41.398", "2018-02-25 21:55:41.700", "2018-02-25 21:55:42.000", "2018-02-25 21:55:57.308", "2018-02-25 21:55:57.907", "2018-02-25 21:55:57.908", "2018-02-25 21:56:17.418", "2018-02-25 21:56:17.420", "2018-02-25 21:56:18.019", "2018-02-25 21:56:21.621", "2018-02-25 21:56:21.624", "2018-02-25 21:56:47.888", "2018-02-25 21:56:55.696", "2018-02-25 21:56:59.749", "2018-02-25 21:56:59.750", "2018-02-25 21:57:00.349", "2018-02-25 21:57:00.351"), aud_pair = c("AUD/USD", "AUD/USD", "AUD/USD", "AUD/USD", "AUD/USD", "AUD/USD", "AUD/USD", "AUD/USD", "AUD/USD", "AUD/USD", "AUD/USD", "AUD/USD", "AUD/USD", "AUD/USD", "AUD/USD", "AUD/USD", "AUD/USD", "AUD/USD", "AUD/USD", "AUD/USD"), aud_bid = c(0.78461, 0.78461, 0.78429, 0.78429, 0.78418, 0.78418, 0.78429, 0.78418, 0.78418, 0.78429, 0.78429, 0.78418, 0.78418, 0.78418, 0.78417, 0.78417, 0.78429, 0.78429, 0.78445, 0.78445), aud_ask = c(0.78426, 0.78426, 0.78367, 0.78367, 0.78359, 0.78359, 0.78367, 0.78359, 0.78359, 0.78367, 0.78367, 0.78359, 0.78359, 0.78359, 0.7835, 0.7835, 0.78358, 0.78358, 0.78368, 0.78368) ) ``` I would like to roll-up the data to one minute level having these details within that one minute window: * aud\_bid\_high * aud\_bid\_low * aud\_ask\_higk * aud\_ask\_low Alternatively, would anyone know how to round the time to the: * nearest 10 seconds - 21:55:38.098 to 21:55:40 or 21:55:30 I'm completely out of ideas, I've tried several approaches but to no avail. Any ideas to help me with this problem. Thanks in advance.
2018/02/28
[ "https://Stackoverflow.com/questions/49027248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4187056/" ]
``` image: "/src/images/1.png" ``` This is not a relative path, its absolute (starts with slash). If you intend it to be relative, use `./` e.g. `./src/images/1.png`. The bigger issue is that you're providing a path to a local resource to the context of the users browser. It expects this to be a `http(s)://` resource. You need to provide an endpoint that your web server handles and serves up the resource. Either: * Your image needs to go into a location your web server can access, and you need to set the `img` `src` attribute to reference that location * You should look into [webpack](https://webpack.js.org) and a file loader plugin that takes a local image path via `require()`, and copies that to an accessible location.
10,892,373
In my application I have a "Students" partial, that passes a collection of @students to a "student" partial. These are eventually displayed on my index page as images of students. When a user clicks on an image, I'm poping up a box with the student's photo and some text. Now, I have a previous/next button that allows users to cycle through the students. I implemented the cycling w/out a plugin...just a simple ajax call to load the next/previous object. My problem is that I cannot detect when I'm at the last (or first) record. I need a way to probably set a url parameter on the first and last objects. So It would look like this: www.mysite.com/students/15?last=true I couldn't find a clean way to do this. I'm also not sure if I'm thinking about this the right way. Should I be attaching url parameters? Or should I somehow modify the object to add additional attributes after retrieving them from the model? Thank you. [EDIT] Just wanted to make this a little clearer. When I pop up the students lightbox, I have 2 links: *previous* (linking to the previous record) and *next* linking to the next record. I'm using the jquery $.load method to make an ajax request and load in the data I want, into a div in my lightbox, whenever I click previous or next. $('previous').click( $('mydiv').load('url of previous student'); ); I get the 'url of previous/next student' by walking the dom tree on initial pop up. I store these so I can refer to them again. My problem is that I cannot tell when I'm at the first student in the list or the last. I need to know this so I can disable the prev/next button. I'm thinking I can either do this through rails/ruby or through javascript. Initially, I thought that by adding a url parameter on the link or the previous/next student (to indicate whether they were first or last), then I could detect this in rails and do a simple if/else to disable the links. But I got stuck at trying to do this with the way I'm referring to the partials.
2012/06/05
[ "https://Stackoverflow.com/questions/10892373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/176217/" ]
From your link: > > * SWF files written in ActionScript 1.0 or 2.0 cannot load SWF files written in ActionScript 3.0. > > > Unfortunately there's no magical solution for your problem.
4,715,463
I want to create 2 really simple dlls: 1) that will sign an xml document 2) that will check that the xml document hasnt been modified. I tried using the RSACryptoServiceProvider and a key container. But when I move to a different machine this does not work as the key is being stored in the machine. I want to store the key in the dlls im creating (I know this is not reccomended) but I just cannot work out how to write some code to simply sign an xml document and then verify that it hasn't been changed. So do I need to use symmetric key to do what I want is this possible? Pete
2011/01/17
[ "https://Stackoverflow.com/questions/4715463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/223863/" ]
You already mention the problems with storing the private key in the dll, so I won't repeat that. Do this: On your own machine run this code: ``` var key = new RSACryptoServiceProvider(2048); string publicKey = key.ToXmlString(false); string privateKey = key.ToXmlString(true); Console.WriteLine(publicKey); Console.WriteLine(privateKey); ``` this outputs two (long) lines. Copy those into your code: Sign: ``` var privateKey = new RSACryptoServiceProvider(); privateKey.FromXmlString(/* insert the private-key XML string here */ ); privateKey.SignData(/*...*/); ``` Verify: ``` var publicKey = new RSACryptoServiceProvider(); publicKey.FromXmlString(/* insert the public-key XML string here */ ); publicKey.VerifyData(/*...*/); ```
2,591,130
How can we divide the substring from the string Like I have string ``` String mainString="///Trade Time///Trade Number///Amount Rs.///"; ``` Now I have other string ``` String subString="Amount" ``` Then I want to extract the substring `Amount Rs.` with the help of second string named **subString** not by any other method But it should be extracted through two parameters like first is I have index no of Amount string and second is until the next string ///.
2010/04/07
[ "https://Stackoverflow.com/questions/2591130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/227848/" ]
First get the index of the substring: ``` int startIndex = mainString.IndexOf(subString); ``` Then get the index of the following slashes: ``` int endIndex = mainString.IndexOf("///", startIndex); ``` Then you can get the substring that you want: ``` string amountString = mainString.Substring(startIndex, endIndex - startIndex); ```
39,321,807
I'm attempting to write a function that combines two strings using recursion. My code is below but I don't know why the function returns undefined especially when I console.log within the base case and it does not print undefined but instead the correct value. ``` var str3="" function merge(str1,str2){ if(str1.length==0||str2.length==0){ console.log(str3) return str3; } else{ str3=str3+str1.substring(0,1)+str2.substring(0,1); merge(str1.substring(1,str1.length),str2.substring(1,str2.length)) } } merge("AAA","BBB") //--> returns undefined but the console.log(str3) gives correct answer ```
2016/09/04
[ "https://Stackoverflow.com/questions/39321807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6686186/" ]
**Explanation** The problem is that you don't return the recursive call's result, thus it is undefined when the whole call to `merge` is resolved. Let me take you through the execution, step-by-step: 1. With arguments `"AAA"` and `"BBB"`, their lengths are not 0, go to else. Once in else, `str3` is `"AB"`, call `merge("AA", "BB")`. 2. With arguments `"AA"` and `"BB"`, their lengths are not 0, go to else. Once in else, `str3` is now `"ABAB"`, call `merge("A", "B")`. 3. With arguments `"A"` and `"B"`, their lengths are not 0, go to else. Once in else, `str3` is now `"ABABAB"`, call `merge("", "")`. 4. With empty string arguments, length is 0. Now go to the if statement, where `str3` is logged, and returned. 5. Since the `merge("", "")` call has resolved (to `"ABABAB"` as it is returned), we continue where we left off in the call `merge("A", "B")`, thus going "up" the call stack. 6. We start where we left off in call `merge("A", "B")`, in the else branch. There are no more statements or expressions in that call, so it's resolved. **There are no return statements, so by default it returns `undefined`**. We go "up" the call stack to call `merge("AA", "BB")` where we left off. 7. We start where we left off in call `merge("AA", "BB")`, in the else branch. There are no more statements or expressions in that call, so it's resolved. Again, there are no return statements so by default it returns `undefined`. We go "up" the call stack to call `merge("AAA", "BBB")` where we left off.- We start where we left off in call `merge("AAA", "BBB")`, in the else branch. There are no more statements or expressions in that call, so it's resolved. Again, there are no return statements so by default it returns `undefined`. There are no more calls, so everything's resolved - and `merge("AAA", "BBB")` returns `undefined`. TL;DR: The recursive call is not returned on each call in the else branch, so the value of `str3` is returned to the call `merge("A", "B")`. The call `merge("A", "B")` does not return anything, it returns `undefined`. The same goes for all other calls - they have no return statement in the else branch so `undefined` is returned. When all calls are resolved, `undefined` is returned. --- **Solution** The solution is to simply prepend `return` to your recursive calls. That way, the result of each call would be returned, 'delegating' the final returned value of `str3` up the call stack - the call returns `"ABABAB"`, not `undefined`. Since we now *return* the result of the call, steps 6, 7, and 8 above **now have a return statement**. That means we don't return `undefined`, but instead `str3`. This is because `merge("", "")` returned `"ABABAB"`, which is the value of `str3`. That result is then returned in call `merge("A", "B")` because of the new added `return` statement, which is then returned in call `merge("AA", "BB")`, and so on, until the call is completely resolved, and the returns the value of `str3`. Here's the new code: ```js var str3 = ""; function merge(str1, str2) { if(str1.length == 0 || str2.length == 0) { console.log(str3); return str3; } else { str3 = str3 + str1.substring(0, 1) + str2.substring(0, 1); return merge(str1.substring(1, str1.length), str2.substring(1, str2.length)); //we return the recursive call } } var mergedString = merge("AAA","BBB"); //mergedString is "ABABAB" ``` Before, `mergedString` would have received the value `undefined`. Since we now return the recursive calls, everything returned accordingly thus the value of `str3` is returned, being stored into variable `mergeString`.
54,594,827
I want my users to be redirected to a specific view controller when they click on a notification. The view controller they are redirected to depends on the notification data. I am using FCM so I implemented the required functions in the AppDelegate. Then I implemented the redirection to a viewcontroller when clicking on a notification (in the *userNotificationCenter(\_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)* method). My app has a tabBarController with 4 view controllers (Activities -> TableView, Events, On Sale, My City). I managed to display the My City ViewController but I don't know how to pass data. Then, I would also like for some notifications, to display a single activity (Activities VC -> single activity). I managed to display the Activities VC but not a single Activity ``` // Display 'My City' without passing data (something I would like to do) self.window = UIWindow(frame: UIScreen.main.bounds) let storyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let tabBar:UITabBarController = storyboard.instantiateViewController(withIdentifier: "tabBar") as! UITabBarController tabBar.selectedIndex = 4 self.window?.rootViewController = tabBar self.window?.makeKeyAndVisible() // Display Single activity (without the Navigation Controller Top Bar and the bottom Tab Bar; and without passing data => 2 issues) self.window = UIWindow(frame: UIScreen.main.bounds) let storyboard = UIStoryboard(name: "Main", bundle: nil) let viewController = storyboard.instantiateViewController(withIdentifier: "SingleActivityVC") self.window?.rootViewController = viewController self.window?.makeKeyAndVisible() ``` So it works when I click on the notification, these two pages are displayed, but : 1- For 'My City', I can't pass data with my current code 2- For the single activity VC : I can't pass data and I don't know how to keep the navigation elements (top and bottom bars)
2019/02/08
[ "https://Stackoverflow.com/questions/54594827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7856659/" ]
For your second issue, the navigation bar and the tab bar are not being displayed because you are only instantiating the SingleActivityVC and setting it as the root. Instead you need to instantiate the parent tab bar controller, select the index of the tab that contains the activities view controller you want, and then call a method on it that will send you to the SingleActivityVC you are looking for. From your code: ``` let tabBar:UITabBarController = storyboard.instantiateViewController(withIdentifier: "tabBar") as! UITabBarController tabBar.selectedIndex = 4 if let item = tabBar.viewControllers?[tabBar.selectedIndex] as? SomeViewController{ item.goToSingleActivity(with: "some data") } ```
1,263,141
I have a custom attribute that is being filled from a database. This attribute can contain an embedded single quote like this, ``` MYATT='Tony\'s Test' ``` At some pont in my code I use jquery to copy this attribute to a field like this, ``` $('#MY_DESC').val($(recdata).attr('MYATT')); ``` MY\_DESC is a text field in a dialog box. When I display the dialog box all I see in the field is **Tony\** What I need to see is, **Tony's Test** How can I fix this so I can see the entire string?
2009/08/11
[ "https://Stackoverflow.com/questions/1263141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104849/" ]
Try: ``` MYATT='Tony&#x27s Test' ``` I didn't bother verifying this with the HTML spec, but the [wikipedia](http://en.wikipedia.org/wiki/HTML) entry says: > > `The ability to "escape" characters in this way allows for the characters < and & (when written as &lt; and &amp;, respectively) to be interpreted as character data, rather than markup. For example, a literal < normally indicates the start of a tag, and & normally indicates the start of a character entity reference or numeric character reference; writing it as &amp; or &#x26; or &#38; allows & to be included in the content of elements or the values of attributes. The double-quote character ("), when used to quote an attribute value, must also be escaped as &quot; or &#x22; or &#34; when it appears within the attribute value itself. The single-quote character ('), when used to quote an attribute value, must also be escaped as &#x27; or &#39; (should NOT be escaped as &apos; except in XHTML documents) when it appears within the attribute value itself. However, since document authors often overlook the need to escape these characters, browsers tend to be very forgiving, treating them as markup only when subsequent text appears to confirm that intent.` > > >
18,974,621
I am wondering does length of a primary key have a non-trivial effect on performance. For example consider the following table definitions, ``` CREATE TABLE table1 ( id VARCHAR(50) PRIMARY KEY, first_column VARCHAR(50) NULL, second_column VARCHAR(75) NOT NULL ); CREATE TABLE table2( id VARCHAR(250) PRIMARY KEY, first_column VARCHAR(50) NULL, second_column VARCHAR(75) NOT NULL ); ``` Does table1 performs better than table2, why?
2013/09/24
[ "https://Stackoverflow.com/questions/18974621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1506101/" ]
In general, performance will depend more on what is stored than on the length of a varchar column. If both the varchar(50) and varchar(250) columns have a median length of 40 characters, they'll probably have similar performance. In some dbms, the primary key is also a clustered key by default. But if your primary key is unsuitable as a clustered key, you can *usually* tell the dbms to not use a clustered key.
3,660,114
I am rendering around 3000 records, i am using this sorting open source script , When i click the column, my browser getting hang very shortly , i cant able to continue, Is there any solution for this prob. [link text](http://www.kryogenix.org/code/browser/sorttable/)
2010/09/07
[ "https://Stackoverflow.com/questions/3660114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/246963/" ]
**Update 2** I sent my updates to the original author of the above code, but until he decides to post it, [here is my updated version](http://pastebin.com/wVvjfHKH). It speeds up the use of the standard built-in sort() if you decide to do that. It also replaces the stable cocktail sort with a stable merge sort. The merge sort is nearly as fast as using sort() in my tests. I hope that helps. **Update** I no longer think that there is a great discrepancy between browsers as far as the built-in sort() function is concerned. While IE8, for instance, is much slower overall than say Chrome, I don't think that it has to do with just the sorting function. I did some profiling in IE8 using some random data. I found that the original code can be improved quite substantially when the column data is numeric or a date. Putting the regexp searches in the comparison functions for these data types slows things down a lot because they are being every time a comparison is done between elements which for 3000 elements is around 60,000 comparisons. The number of regexp's is twice that. By doing all of this before we start sorting, we do 3,000 regexp's rather than 120,000. This can be about a 50% savings in time. I'll submit my changes to the sorttable code in a little bit. Other than that, most of the time is reordering the DOM elements around, not sorting (unless you are using the shaker sort). If you can find a faster way to do that then you can save some time there, but I don't know of any way to do that. **Original answer:** The problem here may have to do with the actual sort. If you uncommented some of the code there (and commented out some other code), then your code is using a shaker sort to get a stable sort. Shaker sort is essentially a bidirectional bubble sort. Bubble sorts are very slow, O(N^2). If you didn't uncomment that code, then it is using javascript's built-in sort() function with various comparator functions. The problem with this is that this sort() function is [implemented differently in different browsers](https://stackoverflow.com/questions/234683/javascript-array-sort-implementation) so you might want to see if this problem happens in some browsers and not in others. Apparently, the Webkit code still uses a selection, or min, sort which is O(N^2). That almost makes me want to cry. What browser have you been using to test this? If the sort function turns out to be the problem, then you might try changing the above code to sue a merge sort or quicksort which are both O(N log N). Quicksorts are a little bit more tricky to avoid O(N^2) cases so you might want to stick with merge sort. Also, merge sort is a stable sort. [This page](http://www.pcosmos.ca/informatique/mergesort/) has an example to get you started with merge sort.
14,153,895
I have a problem with my **Mojarra 2.1.6** web-application, I'm developing it using `@ViewScoped` managed beans and each bean is attached to an xhtml page. This page is receiving some *view params* and after initializing the bean in that way: ```xml <ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:p="http://primefaces.org/ui" template="/templates/general_template.xhtml"> <ui:define name="metadata"> <f:metadata> <f:viewParam id="user" name="user" value="#{navegableUserData._ParamUser}" /> <f:viewParam id="NavIndex" name="NavIndex" value="#{navegableUserData._QueueIndex}" /> <f:event type="preRenderView" listener="#{navegableUserData.initialize}" /> </f:metadata> <h:message for="user" /> </ui:define> <ui:define name="general_content"> <p:outputPanel autoUpdate="false" id="Datos_Loged" name="Datos_Loged" layout="block"> <h:form id="SystemUserForm"> <ui:include src="/system/manage_user/content/edit_user/system_user_data/system_user.xhtml"> <ui:param name="manager" value="#{navegableUserData}" /> </ui:include> </h:form> </p:outputPanel> </ui:define> ``` As you can see, I have my pages nested into a general template which looks like that: ```xml <?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:p="http://primefaces.org/ui" xmlns:o="http://omnifaces.org/ui"> <h:head> <meta http-equiv="Pragma" CONTENT="no-cache"></meta> <meta http-equiv="cache-control" content="no-cache"></meta> <meta http-equiv="Expires" CONTENT="-1"></meta> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-15" /> <h:outputStylesheet library="css" name="prime_styles.css" /> <h:outputScript library="js" name="prime_translations.js" /> </h:head> <h:body> <ui:insert name="metadata" /> <o:importConstants type="com.company.system.view.beans.NavigationResults" /> <!-- More stuff --> ``` Problem comes when I make an *ajax* request such as a Primefaces table filtering. Although my backing bean is not being created again, **`<f:event type="preRenderView" listener="#{navegableUserData.initialize}" />`** is being called again. I'm doing a data loading based into view params and need that method to execute only when the page is rendered first time. I have been very careful using `<c:xxx>` tags and think that's not the problem because I used them only in general template and my view beans properties are not attached to them. Also I have this problem with all my pages, so I think it is not an issue of an specific backing bean.
2013/01/04
[ "https://Stackoverflow.com/questions/14153895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1199132/" ]
If this occur only during ajax request, try the following: ``` public void initialize() { if (!FacesContext.getCurrentInstance().isPostback()) { // ----------- // ----------- } } ``` Related as BalusC suggested: * [What can f:metadata and f:viewParam be used for?](https://stackoverflow.com/questions/6377798/what-can-fmetadata-and-fviewparam-be-used-for/6377957#6377957)
39,806,227
I run this code: ``` private void notify(String date, int space) throws IOException { String ACCOUNT_SID = "dddddd"; String AUTH_TOKEN = "ggggggg"; String TWILIO_PHONE = "+my twilio project"; String ELAD_PHONE = "+my real number"; TwilioRestClient client; client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN); // Build a filter for the CallList Map<String, String> params = new HashMap<String, String>(); params.put("Url", "http://demo.twilio.com/docs/voice.xml"); params.put("To", ELAD_PHONE); params.put("From", TWILIO_PHONE); CallFactory callFactory = client.getAccount().getCallFactory(); Call call; try { call = callFactory.create(params); call.getSid(); } catch (TwilioRestException e) { String a = e.toString(); // log("******** Failed to call", e); } ``` when I run this line: ``` call = callFactory.create(params); ``` I get this exception: ``` java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.twilio.sdk.AppEngineClientConnection.flush(AppEngineClientConnection.java:204) at org.apache.http.protocol.HttpRequestExecutor.doSendRequest(HttpRequestExecutor.java:258) at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:123) at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:645) at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:464) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:732) at com.twilio.sdk.TwilioRestClient.request(TwilioRestClient.java:404) at com.twilio.sdk.TwilioRestClient.safeRequest(TwilioRestClient.java:534) at com.twilio.sdk.resource.list.CallList.create(CallList.java:68) at Runner.notify(Runner.java:152) at Runner.run(Runner.java:40) at Runner.main(Runner.java:25) Caused by: com.google.apphosting.api.ApiProxy$CallNotFoundException: The API package 'urlfetch' or call 'Fetch()' was not found. at com.google.apphosting.api.ApiProxy.makeSyncCall(ApiProxy.java:109) at com.google.appengine.api.urlfetch.URLFetchServiceImpl.fetch(URLFetchServiceImpl.java:38) ... 18 more Oct 01, 2016 2:39:43 PM org.apache.http.impl.client.DefaultRequestDirector tryExecute INFO: I/O exception (java.io.IOException) caught when processing request: Error flushing content in Google App Engine fetch Oct 01, 2016 2:39:43 PM org.apache.http.impl.client.DefaultRequestDirector tryExecute INFO: Retrying request java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.twilio.sdk.AppEngineClientConnection.flush(AppEngineClientConnection.java:204) at org.apache.http.protocol.HttpRequestExecutor.doSendRequest(HttpRequestExecutor.java:258) ```
2016/10/01
[ "https://Stackoverflow.com/questions/39806227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/311130/" ]
I was answered that: > > It looks like **you are trying to test from your local dev > environment**. > > > With Google App Engine, if you want to test in local dev environment, > I think you need to use App Engine SDK for Java. This should work when > deployed to Google App Engine. Let me know if this solves this issue! > > >
31,626,054
I have a form and want to insert integer data . This is the POJO : IntNumberData.class ``` ... private final IntegerProperty num; public IntNumberData() { this(null); } public IntNumberData(Integer num) { this.num = new SimpleIntegerProperty(num); } public Integer getNum() { return num.get(); } public void setNum(Integer num) { this.num.set(num); } public IntegerProperty numProperty() { return num; } ... ``` Also created the other classes and when I try to add data I get the message : > > Caused by: java.lang.NullPointerException > at net.websimp.numdata.model.Intnumberdata.(Intnumberdata.java:11) at net.websimp.numdata.controller.IntnumberdataController.handleNewNum(IntnumberdataController.java:35) > > > I tested all references , but when change the type Integer to String works. why that?
2015/07/25
[ "https://Stackoverflow.com/questions/31626054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3343068/" ]
The constructor for [`SimpleIntegerProperty`](http://docs.oracle.com/javase/8/javafx/api/javafx/beans/property/SimpleIntegerProperty.html#SimpleIntegerProperty-int-) takes an `int` (i.e. **not an `Integer`**). So your constructor ``` public IntNumberData(Integer num) { this.num = new SimpleIntegerProperty(num); } ``` implicitly unboxes `num`, i.e. it effectively compiles to ``` public IntNumberData(Integer num) { this.num = new SimpleIntegerProperty(num.intValue()); } ``` which will throw a `NullPointerException` if `num` is `null`. You can instead do ``` public IntNumberData(Integer num) { this.num = new SimpleIntegerProperty(); this.num.setValue(num); } ``` but note that the implementation will set this to `0` if `null` is passed in (see the [documentation](http://docs.oracle.com/javase/8/javafx/api/javafx/beans/value/WritableIntegerValue.html#setValue-java.lang.Number-)). If you genuinely want a property of type `Integer` that supports null values, then you should use an [`ObjectProperty<Integer>`](http://docs.oracle.com/javase/8/javafx/api/javafx/beans/property/SimpleObjectProperty.html) instead of an `IntegerProperty`.
164,885
For starters, whenever I face a tiger, game goes windowed mode. After that, whenever I press Z to use the camera (or to take it off) it also changes to windowed mode. I've tried to set the camera key to the key next to 0, but when I press it, it still happens. Is there a fix for that?
2014/04/19
[ "https://gaming.stackexchange.com/questions/164885", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/53543/" ]
If I were to venture a guess, it sounds like your computer is communicating with another program, causing the other program to become the focus, forcing your game into windowed mode. You could try closing other programs, perhaps an overlay program such as Steam or Overwolf could cause this. There are any number of programs that actively listen for hotkeys, such as Skype or Teamspeak.
41,074,687
I need to dynamically create table of object in angular 2/typescript Create array of objects ``` export class AppComponent { gameBoard= GAMEBOARD; } var size=10;//will be for user enter var GAMEBOARD=[]; var x=0; for(var i=0;i<size;i++){ for (var j=0; j < size; j++) { if (!GAMEBOARD[i]) { GAMEBOARD[i] = []; } GAMEBOARD[i][j]=new GameField(x); x++; }} ``` Use in template: ``` <tr *ngFor="let x of gameBoard"> <game-field *ngFor="let field of gameBoard[x]" [field]="field" ></game-field> </tr> ``` Try to input: ``` @Component({ selector: 'game-field', // inputs:['field'], template: '<td >{{field.id}}</td>', styleUrls: ['./app.component.css'] }) export class GameFieldComponent{ @Input() field: GameField; } ``` How to put all object from GAMEBOARD into table? (I'm a newbie in web development and Stackoverflow so please for indulgence)
2016/12/10
[ "https://Stackoverflow.com/questions/41074687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7276099/" ]
As you place `custom-element` inside `tr` tag, it would become invalid html and it will thrown of from table tag. You can only place `td`, `th`,etc(only table element in `tr`) all the other element/ custom element aren't allowed in `tr` Rather you should make repeat `td` and generate content from `game-field` component. It could look something like below. Also correct inner `ngFor` to directive loop over `x` instead of `gameBoard[x]` ``` <tr *ngFor="let x of gameBoard"> <td *ngFor="let field of x"> <game-field [field]="field"></game-field> </td> </tr> ``` game-field component Template ``` template: '{{field.id}}', ```
45,132,422
I wrote a simple document classifier and I am currently testing it on the Brown Corpus. However, my accuracy is still very low (0.16). I've already excluded stopwords. Any other ideas on how to improve the classifier's performance? ``` import nltk, random from nltk.corpus import brown, stopwords documents = [(list(brown.words(fileid)), category) for category in brown.categories() for fileid in brown.fileids(category)] random.shuffle(documents) stop = set(stopwords.words('english')) all_words = nltk.FreqDist(w.lower() for w in brown.words() if w in stop) word_features = list(all_words.keys())[:3000] def document_features(document): document_words = set(document) features = {} for word in word_features: features['contains(%s)' % word] = (word in document_words) return features featuresets = [(document_features(d), c) for (d,c) in documents] train_set, test_set = featuresets[100:], featuresets[:100] classifier = nltk.NaiveBayesClassifier.train(train_set) print(nltk.classify.accuracy(classifier, test_set)) ```
2017/07/16
[ "https://Stackoverflow.com/questions/45132422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7947168/" ]
If that's really your code, it's a wonder you get anything at all. `w.lower` is not a string, it's a function (method) object. You need to add the parentheses: ``` >>> w = "The" >>> w.lower <built-in method lower of str object at 0x10231e8b8> >>> w.lower() 'the' ``` (But who knows really. You need to fix the code in your question, it's full of cut-and-paste errors and who knows what else. Next time, help us help you better.)
7,407,062
I'm working on importing some files and I noticed that some of the email addresses are prefixed with a comma. Eg: `,[email protected]` In a table with 1500 emails, I've found that 700+ of these have this issue. How would I update them so that the comma is removed?
2011/09/13
[ "https://Stackoverflow.com/questions/7407062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/700343/" ]
``` UPDATE dbo.Table SET Email = STUFF(Email, 1, 1, '') WHERE Email LIKE ',%'; ```
29,992,125
i just added AdMob to my app. Everything seem to work well when i debug or install release version of app (HTC m7). The problem occurs on CHUWI VX2 device (esky82\_tb\_cn\_kk, Android 4.4). It is very strange because on this device my App works in debug mode but doesn't works in release version. I try turn of pro-gourd but it doesn't help me. Any one have idea for that? my manifest instruction inside my onCreate method: ``` mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); mAdView.setAdListener(new AdListener() { @Override public void onAdClosed() { super.onAdClosed(); mAdView.setVisibility(View.GONE); } @Override public void onAdOpened() { super.onAdOpened(); mAdView.startAnimation(fade_in); mAdView.setVisibility(View.VISIBLE); } @Override public void onAdFailedToLoad(int errorCode) { super.onAdFailedToLoad(errorCode); mAdView.setVisibility(View.GONE); } @Override public void onAdLoaded() { super.onAdLoaded(); mAdView.startAnimation(fade_in); mAdView.setVisibility(View.VISIBLE); } @Override public void onAdLeftApplication() { super.onAdLeftApplication(); mAdView.setVisibility(View.GONE); } }); mAdView.loadAd(adRequest); ``` code inside layout.xml ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:ads="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <com.google.android.gms.ads.AdView android:id="@+id/adView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" ads:adSize="SMART_BANNER" ads:adUnitId="@string/banner_ad_unit_id" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:visibility="gone"> </com.google.android.gms.ads.AdView> </RelativeLayout> ``` Crash log: ``` 05-01 19:39:16.305 124-124/? I/SurfaceFlinger﹕ Skip composition for [Built-in Screen (type:0)] since dirtyRegion is empty 05-01 19:39:16.321 124-124/? I/SurfaceFlinger﹕ Skip composition for [Built-in Screen (type:0)] since dirtyRegion is empty 05-01 19:39:16.330 2162-2162/? D/AndroidRuntime﹕ Shutting down VM 05-01 19:39:16.330 2162-2162/? W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41d79c98) 05-01 19:39:16.330 2162-2162/? W/dalvikvm﹕ threadid=1: uncaught exception occurred 05-01 19:39:16.331 2162-2162/? W/System.err﹕ java.lang.RuntimeException: Unable to start activity ComponentInfo{freshfrog.pytomat/freshfrog.pytomat.Main}: java.lang.NullPointerException 05-01 19:39:16.332 2162-2162/? W/System.err﹕ at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2338) 05-01 19:39:16.332 2162-2162/? W/System.err﹕ at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390) 05-01 19:39:16.332 2162-2162/? W/System.err﹕ at android.app.ActivityThread.access$800(ActivityThread.java:151) 05-01 19:39:16.332 2162-2162/? W/System.err﹕ at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) 05-01 19:39:16.332 2162-2162/? W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:110) 05-01 19:39:16.332 2162-2162/? W/System.err﹕ at android.os.Looper.loop(Looper.java:193) 05-01 19:39:16.333 2162-2162/? W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5292) 05-01 19:39:16.333 2162-2162/? W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method) 05-01 19:39:16.333 2162-2162/? W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515) 05-01 19:39:16.333 2162-2162/? W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824) 05-01 19:39:16.333 2162-2162/? W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) 05-01 19:39:16.333 2162-2162/? W/System.err﹕ at dalvik.system.NativeStart.main(Native Method) 05-01 19:39:16.334 2162-2162/? W/System.err﹕ Caused by: java.lang.NullPointerException 05-01 19:39:16.334 2162-2162/? W/System.err﹕ at freshfrog.pytomat.Main.onCreate(Main.java:450) 05-01 19:39:16.334 2162-2162/? W/System.err﹕ at android.app.Activity.performCreate(Activity.java:5264) 05-01 19:39:16.334 2162-2162/? W/System.err﹕ at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088) 05-01 19:39:16.334 2162-2162/? W/System.err﹕ at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302) 05-01 19:39:16.335 2162-2162/? W/System.err﹕ ... 11 more 05-01 19:39:16.335 2162-2162/? W/dalvikvm﹕ threadid=1: calling UncaughtExceptionHandler 05-01 19:39:16.336 124-124/? I/SurfaceFlinger﹕ Skip composition for [Built-in Screen (type:0)] since dirtyRegion is empty 05-01 19:39:16.339 2162-2162/? E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: freshfrog.pytomat, PID: 2162 java.lang.RuntimeException: Unable to start activity ComponentInfo{freshfrog.pytomat/freshfrog.pytomat.Main}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2338) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390) at android.app.ActivityThread.access$800(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) at android.os.Handler.dispatchMessage(Handler.java:110) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:5292) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException at freshfrog.pytomat.Main.onCreate(Main.java:450) at android.app.Activity.performCreate(Activity.java:5264) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302)             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)             at android.app.ActivityThread.access$800(ActivityThread.java:151)             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)             at android.os.Handler.dispatchMessage(Handler.java:110)             at android.os.Looper.loop(Looper.java:193)             at android.app.ActivityThread.main(ActivityThread.java:5292)             at java.lang.reflect.Method.invokeNative(Native Method)             at java.lang.reflect.Method.invoke(Method.java:515)             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)             at dalvik.system.NativeStart.main(Native Method) 05-01 19:39:16.341 654-669/? V/Provider/Settings﹕ from settings cache , name = dropbox:data_app_crash , value = null 05-01 19:39:16.342 654-669/? D/dalvikvm﹕ create interp thread : stack size=128KB 05-01 19:39:16.342 654-669/? D/dalvikvm﹕ create new thread 05-01 19:39:16.343 654-669/? D/dalvikvm﹕ new thread created 05-01 19:39:16.343 654-669/? D/dalvikvm﹕ update thread list 05-01 19:39:16.343 916-2188/? D/dalvikvm﹕ create interp thread : stack size=128KB 05-01 19:39:16.343 916-2188/? D/dalvikvm﹕ create new thread 05-01 19:39:16.343 916-2188/? D/dalvikvm﹕ new thread created 05-01 19:39:16.343 916-2188/? D/dalvikvm﹕ update thread list 05-01 19:39:16.343 654-2191/? D/dalvikvm﹕ threadid=82: interp stack at 0x64403000 05-01 19:39:16.343 654-2191/? D/dalvikvm﹕ threadid=82: created from interp 05-01 19:39:16.343 654-669/? D/dalvikvm﹕ start new thread 05-01 19:39:16.343 654-669/? V/Provider/Settings﹕ from settings cache , name = send_action_app_error , value = 1 05-01 19:39:16.343 654-669/? W/ActivityManager﹕ Force finishing activity freshfrog.pytomat/.Main ``` Logcat indicate this line (Main.java:450) ``` mAdView.setAdListener(new AdListener() { ```
2015/05/01
[ "https://Stackoverflow.com/questions/29992125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2273794/" ]
what is this ? ``` android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" ``` what were you expecting? to hit both sides? try this ``` android:layout_alignParentRight="true" android:layout_alignParentEnd="true" ``` and let the rest go
93,415
My problem is that I don't know how to choose the random data from a giving set. For example: I have a Node column which need to produce different inserts but only from these numbers: 16, 17, 18, 22, 24. I have looked at many different posts but couldn't find what I'm looking for. Any tips, hints or very simple sample query would be much appreciate. I'm using SQL Server Management Studio 2014
2015/02/20
[ "https://dba.stackexchange.com/questions/93415", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/40950/" ]
You mean how to pick a random row from the data? This is one way to do it: ``` declare @data table ( value int ) insert into @data values (16), (17), (18), (22), (24) select top 1 value from @data order by newid() ```
8,512,928
I wish to off-screen render a Control to some bitmap so that I have quick access to it. Unfortunately `Control.DrawToBitmap` seems to draw the entire control on which it is called including all it's child controls. Internally it issues a WM\_PRINT message with self-provided DC to a bitmap. This temporary bitmap is then blitted to the user-provided Bitmap. Unacceptable for me, I'd rather have this bitmap updated as needed so my performance hit when the bitmap is needed is minimized. In the ideal scenario I'd want the form to behave as if it were visible on the screen (but it cannot be). That would mean that if, say, some Control has its `Text` property changed, the form would be partially invalidated. Catching the relevant messages/events would then allow me to either specify my own DC for the form to be drawn on, or to simply BitBlt the forms DC to my own. Some directions I have looked in: * The `PaintEventArgs` parameter in `OnPaint` seems to hold a member savedGraphicsState, perhaps it could be used to figure out what doesn't require invalidating * Having the form visible but outside the screen area. Controls then don't get painted, though. * Manually calling RedrawWindow() on the window, same story
2011/12/14
[ "https://Stackoverflow.com/questions/8512928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/153772/" ]
I think there are two problems: 1. finding out the invalid area of the control (without help from windows) 2. rendering only the invalidated portion. For the first issue, I think you are largely on your own. You should keep track which controls change, and have bookkeeping which need updating. For the second issue, you can try to send the WM\_PRINT message yourself, and provide a DC referring to only a small bitmap. The original DC API's allowed you to offset and clip the valid drawing area of a HDC. If you are very lucky, windows will deduce the render region from the HDC, and if it does not, most of the render commands that fall entirely out of the bitmap should be quite cheap as there are no pixels that need to change. You should be able to verify this by printing to a 1x1 bitmap and test if it is faster, and/or verify if the clip region sent in WM\_PAINT is reduced to the bitmap size.
49,546,500
I would like to replace NAs in my data frame with values from another column. For example: ``` a1 <- c(1, 2, 4, NA, 2, NA) b1 <- c(3, NA, 4, 4, 4, 3) c1 <- c(NA, 3, 3, 4, 2, 3) a2 <- c(2, 3, 5, 5, 3, 4) b2 <- c(1, 2, 4, 5, 6, 3) c2 <- c(3, 3, 2, 3, 4, 3) df <- as.data.frame(cbind(a1, b1, c1, a2, b2, c2)) df > df a1 b1 c1 a2 b2 c2 1 1 3 NA 2 1 3 2 2 NA 3 3 2 3 3 4 4 3 5 4 2 4 NA 4 4 5 5 3 5 2 4 2 3 6 4 6 NA 3 3 4 3 3 ``` I would like replace the NAs in `df$a1` with the values from the corresponding row in `df$a2`, the NAs in `df$b1` with the values from the corresponding row in `df$b2`, and the NAs in `df$c1` with the values from the corresponding row in `df$c2` so that the new data frame looks like: ``` > df a1 b1 c1 1 1 3 3 2 2 2 3 3 4 4 3 4 5 4 4 5 2 4 2 6 4 3 3 ``` How can I do this? I have a large data frame with many columns, so it would be great to find an efficient way to do this (I've already seen [Replace missing values with a value from another column](https://stackoverflow.com/questions/36151572/replace-missing-values-with-a-value-from-another-column)). Thank you!
2018/03/29
[ "https://Stackoverflow.com/questions/49546500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9514097/" ]
An extensible option: ``` df2 <- df[c('a1','b1','c1')] df2[] <- mapply(function(x,y) ifelse(is.na(x), y, x), df[c('a1','b1','c1')], df[c('a2','b2','c2')], SIMPLIFY=FALSE) df2 # a1 b1 c1 # 1 1 3 3 # 2 2 2 3 # 3 4 4 3 # 4 5 4 4 # 5 2 4 2 # 6 4 3 3 ``` It's easy enough to extend this to arbitrary column pairs: the first column in the first subset (`df[c('a1','b1','c1')]`) is paired with the first column of the second subset; second column first subset, second column second subset; etc. It can even be generalized with `df[grepl('1$',colnames(df))]` and `df[grepl('2$',colnames(df))]`, assuming they don't mis-match.
22,274,528
I am trying to connect asterisk to Google talk, however I kept on receiving an error saying that the Motif channel is absent. I then realised that res\_xmpp.so is not loading. all the dependencies are installed and res\_xmpp.so as well as chan\_motif are selected to be compiled. However, after compiling I get the following error if I try to load res\_xmpp.so: ``` [Mar 8 15:08:15] WARNING[2802]: loader.c:824 inspect_module: Module 'res_xmpp.so' was not compiled with the same compile-time options as this version of Asterisk. [Mar 8 15:08:15] WARNING[2802]: loader.c:825 inspect_module: Module 'res_xmpp.so' will not be initialized as it may cause instability. [Mar 8 15:08:15] WARNING[2802]: loader.c:915 load_resource: Module 'res_xmpp.so' could not be loaded. ``` Does anyone know ho to solve this problem??????
2014/03/08
[ "https://Stackoverflow.com/questions/22274528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3317524/" ]
Correcting the answer from BLiu1: ``` var fadeDivs = document.getElementsByClassName('fade'); for (var i=0, i<fadeDivs.length, i++){ // do stuff to all fade-divs by accessing them with "fadeDivs[i].something" } ```
51,220,256
On an Access 2016 Switchboard I converted the macro behind the form to VBA but it wouldn't compile. A band-aid solution I found was to add **.Value** to **TempVars.Add "CurrentItemNumber", ItemNumber** and change both instances of **Call Argument & "()"** to **Call Eval(Argument & "()")**. This solved the compile error. I then added another button "Reports Menu" to the Switchboard but when I click on the new button I get this error. [![enter image description here](https://i.stack.imgur.com/sbg3B.jpg)](https://i.stack.imgur.com/sbg3B.jpg) When I click Debug it highlights this line **TempVars.Add "SwitchboardID", Argument**. When I added **.Value** to the end of this line **TempVars.Add "SwitchboardID", Argument.Value** it solved the breakpoint issue and the new button works but now the Report Menu does not fill in properly. [![enter image description here](https://i.stack.imgur.com/ZnwV6.jpg)](https://i.stack.imgur.com/ZnwV6.jpg) I can click Return To Main to get back to the Main Menu and all other buttons on the Main Menu work fine except the new Reports Menu Button. Here is the code behind the switchboard... ``` Option Compare Database '------------------------------------------------------------ ' Form_Current ' '------------------------------------------------------------ Private Sub Form_Current() On Error GoTo Form_Current_Err 'TempVars.Add "CurrentItemNumber", ItemNumber TempVars.Add "CurrentItemNumber", ItemNumber.Value Form_Current_Exit: Exit Sub Form_Current_Err: MsgBox Error$ Resume Form_Current_Exit End Sub '------------------------------------------------------------ ' Form_Open ' '------------------------------------------------------------ Private Sub Form_Open(Cancel As Integer) On Error GoTo Form_Open_Err TempVars.Add "SwitchboardID", DLookup("SwitchboardID", "Switchboard Items", "[ItemNumber] = 0 AND [Argument] = 'Default'") DoCmd.SetProperty "Label1", acPropertyCaption, DLookup("ItemText", "Switchboard Items", "[SwitchboardID] = " & TempVars("SwitchboardID")) DoCmd.SetProperty "Label2", acPropertyCaption, DLookup("ItemText", "Switchboard Items", "[SwitchboardID] = " & TempVars("SwitchboardID")) DoCmd.Requery "" Form_Open_Exit: Exit Sub Form_Open_Err: MsgBox Error$ Resume Form_Open_Exit End Sub '------------------------------------------------------------ ' Option1_Click ' '------------------------------------------------------------ Private Sub Option1_Click() On Error GoTo Option1_Click_Err On Error GoTo 0 If (Command = 1) Then 'TempVars.Add "SwitchboardID", Argument TempVars.Add "SwitchboardID", Argument.Value DoCmd.SetProperty "Label1", acPropertyCaption, DLookup("ItemText", "Switchboard Items", "[SwitchboardID] = " & TempVars("SwitchboardID")) DoCmd.SetProperty "Label2", acPropertyCaption, DLookup("ItemText", "Switchboard Items", "[SwitchboardID] = " & TempVars("SwitchboardID")) DoCmd.Requery "" Exit Sub End If If (Command = 2) Then DoCmd.OpenForm Argument, acNormal, "", "", acAdd, acNormal Exit Sub End If If (Command = 3) Then DoCmd.OpenForm Argument, acNormal, "", "", , acNormal Exit Sub End If If (Command = 4) Then DoCmd.OpenReport Argument, acViewReport, "", "", acNormal Exit Sub End If If (Command = 5) Then DoCmd.RunCommand acCmdSwitchboardManager TempVars.Add "SwitchboardID", DLookup("SwitchboardID", "Switchboard Items", "[ItemNumber] = 0 AND [Argument] = 'Default'") DoCmd.SetProperty "Label1", acPropertyCaption, DLookup("ItemText", "Switchboard Items", "[SwitchboardID] = " & TempVars("SwitchboardID")) DoCmd.SetProperty "Label2", acPropertyCaption, DLookup("ItemText", "Switchboard Items", "[SwitchboardID] = " & TempVars("SwitchboardID")) DoCmd.Requery "" Exit Sub End If If (Command = 6) Then DoCmd.CloseDatabase Exit Sub End If If (Command = 7) Then DoCmd.RunMacro Argument, , "" Exit Sub End If If (Command = 8) Then 'Call Argument & "()" Call Eval(Argument & "()") Exit Sub End If Beep MsgBox "Unknown option.", vbOKOnly, "" Option1_Click_Exit: Exit Sub Option1_Click_Err: MsgBox Error$ Resume Option1_Click_Exit End Sub '------------------------------------------------------------ ' OptionLabel1_Click ' '------------------------------------------------------------ Private Sub OptionLabel1_Click() On Error GoTo OptionLabel1_Click_Err On Error GoTo 0 If (Command = 1) Then 'TempVars.Add "SwitchboardID", Argument TempVars.Add "SwitchboardID", Argument.Value DoCmd.SetProperty "Label1", acPropertyCaption, DLookup("ItemText", "Switchboard Items", "[SwitchboardID] = " & TempVars("SwitchboardID")) DoCmd.SetProperty "Label2", acPropertyCaption, DLookup("ItemText", "Switchboard Items", "[SwitchboardID] = " & TempVars("SwitchboardID")) DoCmd.Requery "" Exit Sub End If If (Command = 2) Then DoCmd.OpenForm Argument, acNormal, "", "", acAdd, acNormal Exit Sub End If If (Command = 3) Then DoCmd.OpenForm Argument, acNormal, "", "", , acNormal Exit Sub End If If (Command = 4) Then DoCmd.OpenReport Argument, acViewReport, "", "", acNormal Exit Sub End If If (Command = 5) Then DoCmd.RunCommand acCmdSwitchboardManager TempVars.Add "SwitchboardID", DLookup("SwitchboardID", "Switchboard Items", "[ItemNumber] = 0 AND [Argument] = 'Default'") DoCmd.SetProperty "Label1", acPropertyCaption, DLookup("ItemText", "Switchboard Items", "[SwitchboardID] = " & TempVars("SwitchboardID")) DoCmd.SetProperty "Label2", acPropertyCaption, DLookup("ItemText", "Switchboard Items", "[SwitchboardID] = " & TempVars("SwitchboardID")) DoCmd.Requery "" Exit Sub End If If (Command = 6) Then DoCmd.CloseDatabase Exit Sub End If If (Command = 7) Then DoCmd.RunMacro Argument, , "" Exit Sub End If If (Command = 8) Then 'Call Argument & "()" Call Eval(Argument & "()") Exit Sub End If Beep MsgBox "Unknown option.", vbOKOnly, "" OptionLabel1_Click_Exit: Exit Sub OptionLabel1_Click_Err: MsgBox Error$ Resume OptionLabel1_Click_Exit End Sub ``` Any suggestions would be appreciated.. Thanks in advance.
2018/07/07
[ "https://Stackoverflow.com/questions/51220256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6471192/" ]
I really appreciate the responses but due to time constrains I threw in the towel trying to fix this code that was generated by Access 2016 (when it converted the macros) and grabbed Switchboard from code from an older database that works. I believe that code was created with Access 2003 but it still works perfectly (see below) It has a limit of 8 buttons per switchboard but it should be enough for most applications. ``` Option Compare Database Private Sub Form_Open(Cancel As Integer) ' Minimize the database window and initialize the form. ' Move to the switchboard page that is marked as the default. Me.Filter = "[ItemNumber] = 0 AND [Argument] = 'Default' " Me.FilterOn = True End Sub Private Sub Form_Current() ' Update the caption and fill in the list of options. Me.Caption = Nz(Me![ItemText], "") FillOptions End Sub Private Sub FillOptions() ' Fill in the options for this switchboard page. ' The number of buttons on the form. Const conNumButtons = 8 Dim con As Object Dim RS As Object Dim stSql As String Dim intOption As Integer ' Set the focus to the first button on the form, ' and then hide all of the buttons on the form ' but the first. You can't hide the field with the focus. Me![Option1].SetFocus For intOption = 2 To conNumButtons Me("Option" & intOption).Visible = False Me("OptionLabel" & intOption).Visible = False Next intOption ' Open the table of Switchboard Items, and find ' the first item for this Switchboard Page. Set con = Application.CurrentProject.Connection stSql = "SELECT * FROM [Switchboard Items]" stSql = stSql & " WHERE [ItemNumber] > 0 AND [SwitchboardID]=" & Me![SwitchboardID] stSql = stSql & " ORDER BY [ItemNumber];" Set RS = CreateObject("ADODB.Recordset") RS.Open stSql, con, 1 ' 1 = adOpenKeyset ' If there are no options for this Switchboard Page, ' display a message. Otherwise, fill the page with the items. If (RS.EOF) Then Me![OptionLabel1].Caption = "There are no items for this switchboard page" Else While (Not (RS.EOF)) Me("Option" & RS![ItemNumber]).Visible = True Me("OptionLabel" & RS![ItemNumber]).Visible = True Me("OptionLabel" & RS![ItemNumber]).Caption = RS![ItemText] RS.MoveNext Wend End If ' Close the recordset and the database. RS.Close Set RS = Nothing Set con = Nothing End Sub Private Function HandleButtonClick(intBtn As Integer) ' This function is called when a button is clicked. ' intBtn indicates which button was clicked. ' Constants for the commands that can be executed. Const conCmdGotoSwitchboard = 1 Const conCmdOpenFormAdd = 2 Const conCmdOpenFormBrowse = 3 Const conCmdOpenReport = 4 Const conCmdCustomizeSwitchboard = 5 Const conCmdExitApplication = 6 Const conCmdRunMacro = 7 Const conCmdRunCode = 8 Const conCmdOpenPage = 9 ' An error that is special cased. Const conErrDoCmdCancelled = 2501 Dim con As Object Dim RS As Object Dim stSql As String On Error GoTo HandleButtonClick_Err ' Find the item in the Switchboard Items table ' that corresponds to the button that was clicked. Set con = Application.CurrentProject.Connection Set RS = CreateObject("ADODB.Recordset") stSql = "SELECT * FROM [Switchboard Items] " stSql = stSql & "WHERE [SwitchboardID]=" & Me![SwitchboardID] & " AND [ItemNumber]=" & intBtn RS.Open stSql, con, 1 ' 1 = adOpenKeyset ' If no item matches, report the error and exit the function. If (RS.EOF) Then MsgBox "There was an error reading the Switchboard Items table." RS.Close Set RS = Nothing Set con = Nothing Exit Function End If Select Case RS![Command] ' Go to another switchboard. Case conCmdGotoSwitchboard Me.Filter = "[ItemNumber] = 0 AND [SwitchboardID]=" & RS![Argument] ' Open a form in Add mode. Case conCmdOpenFormAdd DoCmd.OpenForm RS![Argument], , , , acAdd ' Open a form. Case conCmdOpenFormBrowse DoCmd.OpenForm RS![Argument] ' Open a report. Case conCmdOpenReport DoCmd.OpenReport RS![Argument], acPreview ' Customize the Switchboard. Case conCmdCustomizeSwitchboard ' Handle the case where the Switchboard Manager ' is not installed (e.g. Minimal Install). On Error Resume Next Application.Run "ACWZMAIN.sbm_Entry" If (Err <> 0) Then MsgBox "Command not available." On Error GoTo 0 ' Update the form. Me.Filter = "[ItemNumber] = 0 AND [Argument] = 'Default' " Me.Caption = Nz(Me![ItemText], "") FillOptions ' Exit the application. Case conCmdExitApplication CloseCurrentDatabase ' Run a macro. Case conCmdRunMacro DoCmd.RunMacro RS![Argument] ' Run code. Case conCmdRunCode Application.Run RS![Argument] ' Open a Data Access Page Case conCmdOpenPage DoCmd.OpenDataAccessPage RS![Argument] ' Any other command is unrecognized. Case Else MsgBox "Unknown option." End Select ' Close the recordset and the database. RS.Close HandleButtonClick_Exit: On Error Resume Next Set RS = Nothing Set con = Nothing Exit Function HandleButtonClick_Err: ' If the action was cancelled by the user for ' some reason, don't display an error message. ' Instead, resume on the next line. If (Err = conErrDoCmdCancelled) Then Resume Next Else MsgBox "There was an error executing the command.", vbCritical Resume HandleButtonClick_Exit End If End Function ``` Hope this can help someone else...
25,223
I know there are many Physics enthusiasts on Math SE. I would invite them to have a look at the [new site proposal on Area 51](http://area51.stackexchange.com/proposals/103955/physics-problem-solving/103964#103964) Presently Physics SE isn't meant for problem-solving. It is more about specific physics concepts. The new site wishes to be what Physics SE isn't i.e. a platform to discuss various ways of solving a problem and helping users find out their mistakes while solving. [See the meta post on Physics SE to get a better idea.](https://physics.meta.stackexchange.com/questions/9303/new-site-proposal-specifically-for-problem-solving-in-physics-on-area-51) At the moment we lack followers on the proposal. But I think it can be a successful site. Do have a look and leave your suggestions on the meta post. Thank you. **UPDATE:** <http://meta.math.stackexchange.com/a/25253/220382>
2016/10/29
[ "https://math.meta.stackexchange.com/questions/25223", "https://math.meta.stackexchange.com", "https://math.meta.stackexchange.com/users/-1/" ]
**UPDATE:** Well, a whole lot of things have happened, but in a nutshell: * Our proposal was closed as a duplicate. * We got an offer from Physics Overflow to host the site. But due to some differences with Physics SE we had to decline the offer. * @Mew is building the new site by hand outside Stack Exchange network. (Prototype: <http://physicsproblems.nfshost.com/?qa=questions>) We want the relations between our new site, Physics Problems Q&A, and Physics.SE to be friendly. Hopefully, once our site is firmly established, we can establish some sort of protocol for migrating questions between sites, or at the very least recommending the other site to users. We certainly do not want a relationship like that between Physics Overflow and Physics.SE. We would be glad to welcome any users to our site; please see our first draft of our scope and guidelines to know what we expect. Moderators on the site are [@heather](https://physics.stackexchange.com/users/121464/heather), [@S007](https://physics.stackexchange.com/users/131786/s007?tab=profile) , and [@Mew](https://physics.stackexchange.com/users/12350/mew) (username Einstein on the new site). Our site is coming along quite well although there are still improvements to be made, both in the construction of the site and in the general guidelines. If you have any questions, the chatroom on the new site is still under construction, so please ping one of us at the Physics Stack Exchange chatrooms. Thank you!
63,517,139
in the html i have 3 buttons with id="button" that correspond to different sections with their ids Here is the script, ``` $(document).ready(function(){ $("#button").on('click', function(event) { if (this.hash !== "") { event.preventDefault(); var hash = this.hash; $('html, body').animate({ scrollTop: $(hash).offset().top }, 1500, function(){ window.location.hash = hash; }); } }); }); ```
2020/08/21
[ "https://Stackoverflow.com/questions/63517139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13237679/" ]
Overview ======== By using `Scikit-Learn` library, one can consider different Decision Trees to forecast data. In this example, we'll be using an `AdaBoostRegressor`, but alternatively, one can switch to `RandomForestRegressor` or any other tree available. Thus, by choosing trees one should we aware of removing the trend to the data, in this way, we illustrate the example of controlling the mean and variance of the time series by differencing and applying logarithm transform respectively to the data. Preparing the data ------------------ A time series has two basic components, it's mean and it's variance. Ideally, we would like to control this components, for the variability, we can simply apply a logarithm transformation on the data, and for the trend we can differentiate it, we will see this later. Additionally, for this approach, we're considering that the actual value y\_t can be explained by the two prior value y\_t-1 and y\_t-2. You can play around with these lags values by modifying the input to the `range` function. ``` # Load data tsdf = pd.read_csv('tsdf.csv', sep="\t") # For simplicity I just take the target variable and the date tsdf = tsdf[['sales_index', 'dates']] # Log value tsdf['log_sales_index'] = np.log(tsdf.sales_index) # Add previous n-values for i in range(3): tsdf[f'sales_index_lag_{i+1}'] = tsdf.sales_index.shift(i+1) # For simplicity we drop the null values tsdf.dropna(inplace=True) tsdf[f'log_sales_index_lag_{i+1}'] = np.log(tsdf[f'sales_index_lag_{i+1}']) tsdf[f'log_difference_{i+1}'] = tsdf.log_sales_index - tsdf[f'log_sales_index_lag_{i+1}'] ``` Once our data is ready, we get to a result similar to the one on the image below.[![enter image description here](https://i.stack.imgur.com/qQyZZ.png)](https://i.stack.imgur.com/qQyZZ.png) Is data stationary? ------------------- To control the mean component of the time series, we should perform some differencing on the data. In order to determine whether this step is required we can perform a unit root test. There are several test for this that make different assumptions, a list of some unit root tests can be found [here](https://arch.readthedocs.io/en/latest/unitroot/unitroot_examples.html#). For simplicity, we're going to consider the KPSS test, by this we assumme as null hypothesis that the data is stationary, particularly, it assumess stationarity around a mean or a linear trend. ``` from arch.unitroot import KPSS # Test for stationary kpss_test = KPSS(tsdf.sales_index) # Test summary print(kpss_test.summary().as_text()) ``` [![enter image description here](https://i.stack.imgur.com/RBcXX.png)](https://i.stack.imgur.com/RBcXX.png) We see that the `P-value = .280` is greater than the usual convention of `0.05`. Therefore, we would need to apply a first difference to the data. As a side note, one can iteratively perform this test to know how many differences should be applied to the data. In the graph below, we see a comparison of the original data vs the log first difference of it, notice there is a sudden change in these last values of the time series, this appears to be a structural change but we are not going to deep dive on it. If you want to dig more on this topic these [slides](https://es.scribd.com/document/235247462/Advanced-Time-Series-and-Forecasting-Lecture-5) from Bruce Hansen are useful. ``` plt.figure(figsize=(12, 6)) plt.subplot(1,2,1) plt.plot(tsdf.sales_index) plt.title('Original Time Series') plt.subplot(1,2,2) plt.plot(tsdf.log_difference_1) plt.title('Log first difference Time Series') ``` [![enter image description here](https://i.stack.imgur.com/hWLRE.png)](https://i.stack.imgur.com/hWLRE.png) Decision Tree Model ------------------- As we've previously said, we're considering Decision Tree Models, when using them one should be aware of removing the trend from the time series. For example, if you have an upward trend, tress are not good at predicting a downward trend. In the code example below, I've choose the `AdaBoostRegressor`, but you're free to choose other tree model. Additionnaly, notice that `log_difference_1` is consider to be explained by `log_difference_2` and `log_difference_3`. > > **Note**. Your dataset has other covariates as `aus_avg_rain` or `slg_adt_ctl`, so to consider them for predicting you could apply as well lag values on them. > > > ``` from sklearn.model_selection import train_test_split from sklearn.ensemble import AdaBoostRegressor # Forecast difference of log values X, Y = tsdf[['log_difference_2', 'log_difference_3']], tsdf['log_difference_1'] # Split in train-test X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, shuffle=False, random_state=0) # Initialize the estimator mdl_adaboost = AdaBoostRegressor(n_estimators=500, learning_rate=0.05) # Fit the data mdl_adaboost.fit(X_train, Y_train) # Make predictions pred = mdl_adaboost.predict(X_test) test_size = X_test.shape[0] ``` Evaluating the prediction ------------------------- ``` test_size = X_test.shape[0] plt.plot(list(range(test_size)), np.exp(tsdf.tail(test_size).log_sales_index_lag_1 + pred), label='predicted', color='red') plt.plot(list(range(test_size)), tsdf.tail(test_size).sales_index, label='real', color='blue') plt.legend(loc='best') plt.title('Predicted vs Real with log difference values') ``` [![enter image description here](https://i.stack.imgur.com/ZnHrJ.png)](https://i.stack.imgur.com/ZnHrJ.png) It seems that Decision Tree model is accurately predicting the real values. However, to evaluate the model performance we should consider an evaluation metric, a good intro to this topic can be found on this [article](https://towardsdatascience.com/how-good-are-your-forecasts-a37cb9cf5c1d), feel free to pick the one that is more convenient to your approach. I'm just going to go with the `TimeSeriesSplit` function from `scikit-learn` to assess model's error through the mean absolute error. ``` from sklearn.model_selection import TimeSeriesSplit from sklearn.metrics import mean_absolute_error X, Y = np.array(tsdf[['log_difference_2', 'log_difference_3']]), np.array(tsdf['log_difference_1']) # Initialize a TimeSeriesSplitter tscv = TimeSeriesSplit(n_splits=5) # Retrieve log_sales_index and sales_index to unstransform data tsdf_log_sales_index = np.array(tsdf.copy().reset_index().log_sales_index_lag_1) tsdf_sales_index = np.array(tsdf.copy().reset_index().sales_index_lag_1) # Dict to store metric value at every iteration metric_iter = {} for idx, val in enumerate(tscv.split(X)): train_i, test_i = val X_train, X_test = X[train_i], X[test_i] Y_train, Y_test = Y[train_i], Y[test_i] # Initialize the estimator mdl_adaboost = AdaBoostRegressor(n_estimators=500, learning_rate=0.05) # Fit the data mdl_adaboost.fit(X_train, Y_train) # Make predictions pred = mdl_adaboost.predict(X_test) # Unstransform predictions pred_untransform = [np.exp(val_test + val_pred) for val_test, val_pred in zip(tsdf_log_sales_index[test_i], pred)] # Real value real = tsdf_sales_index[test_i] # Store metric metric_iter[f'iter_{idx + 1}'] = mean_absolute_error(real, pred_untransform) ``` Now we see that the average `MAE` error is quite low. ``` print(f'Average MAE error: {np.mean(list(metric_iter.values()))}') >>> Average MAE error: 17.631090959806535 ```
31,099,034
I have [this implementation](https://dotnetfiddle.net/5ITzD5) of a tree recursive function. It gets all possible paths from A to D. The recursive function is: ``` private static List<Path> GetPath(int depth, Path path) { if (depth == nodes.Length) { return new List<Path> { path }; } else { var result = new List<Path>(); foreach(var link in nodes[depth].Links) { Node node = new Node { Name = nodes[depth].Name, Links = new[] { link } }; path.Add(node); result.AddRange( GetPath( depth+1, path)); } return result; } } ``` The expected results should be: ``` A1-B2->C3->D4 A1-B5->C3->D4 ``` However, the paths returned are the same and they include all possible nodes twice. What's wrong with the function?
2015/06/28
[ "https://Stackoverflow.com/questions/31099034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/524861/" ]
`list.remove(i);` moves the indices of all the elements that follow the removed element. Therefore, after calling `list.remove(0)`, the previous element at position 1 would move to position 0, and your loop will never remove it, since i is incremented. As you saw, your loop will remove only half of the elements. This loop will remove all the elements : ``` while(list.size()>0) { list.remove(0); } ```
9,986,808
I would like to use this simple script with my form to make sure I have at least 1 box checked but I have a feeling something is wrong, most likely at the getElementsByName tag. I always get the pop up box no matter if I have items checked or not. ``` <script language="javascript"> function validate() { var chks = document.getElementsByName('id[][]'); var hasChecked = false; for (var i = 0; i < chks.length; i++) { if (chks[i].checked) { hasChecked = true; break; } } if (hasChecked == false) { alert("Please select at least one."); return false; } return true; } </script> ``` and the form, which may or may not end up with more checkboxes in the end: ``` <form enctype="multipart/form-data" method="post" action="formsubmission.php" name="form_type" onSubmit="return validate()"> <input id="attrib-8-10" type="checkbox" value="10" name="id[8][10]"> <label class="Checkbox" for="attrib-8-10">thick</label> <input id="attrib-8-11" type="checkbox" value="11" name="id[8][11]"> <label class="Checkbox" for="attrib-8-11">medium</label> <input id="attrib-8-12" type="checkbox" value="12" name="id[8][12]"> <label class="Checkbox" for="attrib-8-12">thin</label> ```
2012/04/03
[ "https://Stackoverflow.com/questions/9986808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1193544/" ]
This line is the culprit: ``` var chks = document.getElementsByName('id[][]'); ``` The `id` attribute of an HTML element is meant to be unique, which yours are. The `name` attribute is meant to logically group elements together (especially in the case of checkboxes and radio buttons). In order to group them together, the name must be the same. `id[8][10]` is not the same as `id[8][11]`, and your call to `document.getElementsByName('id[][]')` is literally looking for elements named "id[][]". You must change the name of the elements to be something that matches, i.e. "checkboxGroup" and then use `document.getElementsByName('checkboxGroup')`
1,213,131
Let $\vec{u}$, $\vec{v}$, $\vec{w}$ belong to a vector space V over the real numbers $\def\sp{\operatorname{span}}\Bbb R$. Is the statement $\sp\{ \vec{u} , \vec{v} , \vec{w} \} = \sp\{ \vec{u} ,\vec{u} + \vec{v}, \vec{u} + \vec{v} + \vec{w} \}$ always true? I'am having trouble with this problem. Any help would be appreciated.
2015/03/30
[ "https://math.stackexchange.com/questions/1213131", "https://math.stackexchange.com", "https://math.stackexchange.com/users/218172/" ]
If $x=\alpha u+\beta v+\gamma w\in\mathrm{span}\{u,v,w\}$, then $$ x=(\alpha-\beta) u+(\beta-\gamma)(u+v)+\gamma(u+v+w)\in\mathrm{span}\{u,u+v,u+v+w\}. $$ Hence $\mathrm{span}\{u,v,w\}\subset\mathrm{span}\{u,u+v,u+v+w\}$. The reversed inclusion is trivial.
1,793,109
I'm using a ListBox to maintain a list of items in a WPF application. The ListBox data source is a HashSet wrapped in an ObservableCollection. ie, I have the following code : ``` this.shackSet = new ObservableCollection<Shack>(new HashSet<Shack>()); this.shackListing.ItemsSource = this.shackSet; ``` ... where shackListing is a ListBox control, and shackSet in an ICollection. However, whenever I add anything to shackSet after the addition of the first item, I see multiple items in the ListBox. ie It's like newly added items are getting added to the list regardless of whether they're added to the set. When I look at the signatures of ICollection#Add : ``` void Add(T obj); ``` ... and HashSet#Add : ``` bool Add(T obj); ``` ... this leads me to believe there's a bug that affects wrapped HashSets where newly added items get added to the ListBox regardless because the ObservableCollection has no way of telling whether the object was actually added to the underlaying collection because the return type of ICollection#Add is void. Can anybody else confirm this ?
2009/11/24
[ "https://Stackoverflow.com/questions/1793109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32232/" ]
When you create a new ObservableCollection with another collection you are not wrapping that collection, you create a new one where all items of the passed collection are copied to the ObservableCollection. If you want to use an ObservableCollection for the sole purpose of DataBinding, look no further, you can bind to any IEnumerable in WPF. This unfortuantely has the drawback that WPF will not always correctly pickup changes to the bound collection. If this is an issue you'd probably have to create your own obeservable hashset: ``` public class ObservableHashSet<T> : ObservableCollection<T> { protected override void InsertItem(int index, T item) { if (Contains(item)) { throw new ItemExistsException(item); } base.InsertItem(index, item); } protected override void SetItem(int index, T item) { int i = IndexOf(item); if (i >= 0 && i != index) { throw new ItemExistsException(item); } base.SetItem(index, item); } } ``` EDIT: AS already has been pointed out, you can not inherit from HashSet to implement INotifyCollectionChanged. However if you look at the code (using Reflector) for the HashSet class it is pretty simple it should be too hard to mimic that functionality yourself.
31,102
With the obvious exception (for the most part) of the 2012 film, Star Trek movies and TV series generally stay pretty true to canon in terms of in-universe history. So I began to wonder, as I'm now watching through the Enterprise series, if any of the people, places, or things from the prequel series were ever talked about in earlier works? Was there ever mention of Jonathan Archer, the NX-01, a Temporal Cold War, or any other foundational elements of the Enterprise series before that series was produced? Or were all these pieces covered solely within the Enterprise timeline? NOTE: I'm not looking for any crossover episodes where Enterprise just happens to cover some well-known element of Star Trek universe history. I'm looking for anything to show that the Star Trek universe had historical information about core series components like the NX-01, Jonathan Archer, et. al. *before* Enterprise was created - something that shows, for example, that "Jonathan Archer" wasn't just pulled from a hat when the creators were looking to name the captain of Starfleet's first Enterprise.
2013/01/28
[ "https://scifi.stackexchange.com/questions/31102", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/1639/" ]
NX-01 never appeared in any other series before it. While the 2009 reboot movie and *Star Trek Beyond* later referenced Enterprise-era events, before the series "Star Trek: Enterprise" the NX-01 did not exist.
41,616,072
I have a number of images in Google Drive and I am wanting to use them in various ways via the direct link style: <https://drive.google.com/uc?id=DOCID> In Chrome I am logged into three different Google accounts, my corporate one, my personal one, and one other. If I navigate through the Google Drive interface to my files in the corporate account I can see them fine. If I use the form <https://drive.google.com/open?id=DOCID> then the Google Drive interface opens properly with the image displayed. However, when I try to access the file directly using the uc?id= URL style above I get a 403 error. *"403. That’s an error. We're sorry, but you do not have access to this page. That’s all we know."* I have tracked this down to being because when I use this URL form, for some reason Chrome or Google Drive are using the wrong authentication credentials - i.e. the ones from my personal account even though this file is in my corporate account. I've proved this by firing up Firefox, which isn't authenticated to any account, logging in as my corporate user, and then using the URL above: bingo, the image is displayed. So my question: is there any way to force the URL style above to use the correct set of credentials when accessing the file?
2017/01/12
[ "https://Stackoverflow.com/questions/41616072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2572362/" ]
You can use `drive.google.com/u/1/uc?id=DOCID` or `drive.google.com/a/mycorporatedomain.com/uc?id=DOCID` However, do not rely on these URL's not changing in the future.
15,499,689
I have 10 files containing anywhere from 50 to 250 rows each. I need to be able to pull 1 or more random rows from different files. I currently do this... ``` $lines = file($filePath); if ($number == "1") { return $lines[array_rand($lines)]; } else { shuffle($lines); return array_slice($lines, 0, $number); } ``` However, I just read of a way to do the same thing using MySQL here: <https://stackoverflow.com/a/4329447/390480> Would I really have that much of a performance gain moving these 10 files to a MySQL database and doing that query instead? Thanks!
2013/03/19
[ "https://Stackoverflow.com/questions/15499689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/390480/" ]
From my experience, when you don't have too much information, it's quicker to retrieve info from a file than from a database. In my case I have files where I store arrays with types of houses for example, and it was faster to get it from files. The files were about 10kb only, and the performance was 10 times faster, maybe I'm wrong with the performance improvement but definetively it was fast enough to make me delete those tables containing those rows and use the text files xD. The best way to ensure the performance is to make use of the function `microtime()` and do it both ways. Then you can see the performance through your own benchmark. I use this a lot: ``` $start = microtime(true); // my code; // If it's not a very long script, you should always put it inside a loop, let's say thousands times or more, depending on the script, because sometimes just the resources used by the system could vary the benchmark, as suggested by @Colin Morelli . echo microtime(true) - $start; ``` You get the output of the microseconds elapsed.
39,339,266
I'm coding a program in c#. I have 2 `ListView` controls. `listview1` is getting `TagName` and `TagID` from mysql database. `listview2` is getting `TagName` from an external device. I would like to compare the `TagName` fields from the 2 `listviews` and display a `MessageBox` with the missing items if `listview2` has missing items that are shown in `listview1`. How do I go around doing this? So far i've tried this: ``` LstView.Sort(); ListViewDatabase.Sort(); if (ListViewDatabase.Items.Count > 0) { for (int i = 0; i < ListViewDatabase.Items.Count; i++) { string t = ListViewDatabase.Items[i].SubItems[1].Text; for (int j = 0; j < LstView.Items.Count; j++) { if (t != LstView.Items[j].SubItems[1].Text) { MessageBox.Show("Missing Tag" + LstView.Items[j].SubItems[1].Text); } } } } ``` But this just shows all the tags in `listview2` and not the ones that are missing. Any help will be much appreciated.
2016/09/06
[ "https://Stackoverflow.com/questions/39339266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6341319/" ]
You can use such linq query to get items which are present in `listView1` but are absent in `listView2`: ``` var diff = listView1.Items.Cast<ListViewItem>().Select(x => x.Text) .Except(listView2.Items.Cast<ListViewItem>().Select(x => x.Text)); MessageBox.Show(string.Format("{0} Missing.", string.Join(",", diff))); ```
42,610,708
``` <div class='parent'> <div class='children'>1234</div> <div class='children'>5678</div> <div class='children'>9101</div> <div class='children'>I WANT TO BE FIRST</div> </div> ``` **js** ``` $('.parent').sortable({ axis: "y", containment: "parent" }); ``` There is a problem dragging an element to the first position if `containment` is set to `parent`. I need this settings but I also need to move some elements to the top. But it seams that there is no space enough to do it. Sometimes it is possible but mainly - it's not. I tried with adding top/bottom padding/margin to the `parent` - without success. Any workaround? Here is [jsfiddle](https://jsfiddle.net/bonaca/r4pbvo21/2/)
2017/03/05
[ "https://Stackoverflow.com/questions/42610708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3044737/" ]
`setColor` function will receive `event` attribute as last argument by default. ``` onChange={{action 'setColor' value="target.value"}} ``` so `value` attribute will be retrieved from `event`. so this will work as expected. but ``` onChange={{action 'setColor' model value="target.value"}} ``` `value` attribute will try to get `target.value` from `model` property as we sent `model` as first argument, and default `event` argument will be passed as second argument. so combining won't work. Solution would be ``` onChange={{action 'setColor' model}} ``` and inside actions, ``` actions: { setColor(model, event) { let value = event.target.value; } } ```
64,206,533
Overflow! I tried to transfer my docker-compose script from my ubuntu-workstation to my fedora laptop. when hitting ``` docker-compose up ``` I get following exception; ``` [polito@localhost dev]$ docker-compose up Traceback (most recent call last): File "urllib3/connectionpool.py", line 677, in urlopen File "urllib3/connectionpool.py", line 392, in _make_request File "http/client.py", line 1252, in request File "http/client.py", line 1298, in _send_request File "http/client.py", line 1247, in endheaders File "http/client.py", line 1026, in _send_output File "http/client.py", line 966, in send File "docker/transport/unixconn.py", line 43, in connect FileNotFoundError: [Errno 2] No such file or directory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "requests/adapters.py", line 449, in send File "urllib3/connectionpool.py", line 727, in urlopen File "urllib3/util/retry.py", line 403, in increment File "urllib3/packages/six.py", line 734, in reraise [...] ``` What I tried: After googleing I found: deleting and reinstalling - did not work either. Any idea how to fix? Greetings!
2020/10/05
[ "https://Stackoverflow.com/questions/64206533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10330348/" ]
Please, follow these steps: <https://docs.docker.com/engine/install/linux-postinstall/>. It helped me.
43,268,344
How do I create an Azure WebJob targeting .NET Core 1.1? In Visual Studio 2017, the only option I'm seeing for Azure WebJob targets .NET Framework -- see below. [![enter image description here](https://i.stack.imgur.com/AEkzW.jpg)](https://i.stack.imgur.com/AEkzW.jpg) Under .NET Core, I don't see Azure WebJob listed. [![enter image description here](https://i.stack.imgur.com/SfJpw.jpg)](https://i.stack.imgur.com/SfJpw.jpg)
2017/04/07
[ "https://Stackoverflow.com/questions/43268344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1705266/" ]
The VS 2017 tooling for .NET Core does not exist yet, although it is planned. It's still possible to write a Core based WebJob and deploy it manually to your Web App. But do note that the WebJob **SDK** (which is a whole other topic) does not yet support .NET Core (related issue [here](https://github.com/Azure/Azure-Functions/issues/98)).
22,839
Let X be locally compact and Hausdorff, and let $f:X\rightarrow\mathbb R$ be a function. Suppose that for all finite regular (positive) Borel measures $\mu$, we know that $f$ is $\mu$-measurable. Does it follow that $f$ is Borel? If not, what's a good counter-example? Definitions: The Borel sigma-algebra is generated by the open sets. So $f$ is Borel if $f^{-1}(U)$ is Borel for each open $U\subseteq\mathbb R$. I think the definition of $\mu$-measurable is that for each open $U\subseteq\mathbb R$, we have that $f^{-1}(U)$ is in the completed sigma-algebra for $\mu$. That is, we can find Borel sets $A$ and $B$ with $A \subseteq f^{-1}(U) \subseteq B$ with $\mu(B\setminus A)=0$. Remark: The "obvious" measures are the point mass measures, but then the completed sigma-algebra is $2^X$, so all functions are measurable! So the question is, in some sense, whether $X$ supports "enough" finite regular Borel measures. Vague motivation: This old paper of Barry Johnson: Separate continuity and measurability. Proc. Amer. Math. Soc. 20 1969 420--422 see <http://www.jstor.org/stable/2035668> But Barry's paper clearly gives me enough for what I want, so really this question is out of curiosity, not an attempt to understand the paper better!
2010/04/28
[ "https://mathoverflow.net/questions/22839", "https://mathoverflow.net", "https://mathoverflow.net/users/406/" ]
Let $f: \mathbb{R} \to \mathbb{R}$ be the characteristic function of a subset $A \subseteq \mathbb{R}$ which is analytic but not Borel. Then $f$ is universally measurable but not Borel.
63,812,272
im trying to execute Javascript in my Xamarin.Forms WebView by using the tutorial described here: <https://www.xamarinhelp.com/xamarin-forms-webview-executing-javascript/> Android works really good but I have problems setting this up on iOS. In the iOS custom renderer I basically return the js execute result by return Task.FromResult(this.EvaluateJavascript(js)); Since last year the iOS api changed and this line throws an error when debugging. It turns out that I should use WkWebViewRenderer instead of WebViewRenderer. I tried to change but EvaluateJavascript() method now wants two arguments... one is the js string and one is a WKJavascriptEvaluationResult handler ... I dont know how to adapt the code in the tutorial... can someone help?
2020/09/09
[ "https://Stackoverflow.com/questions/63812272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11528146/" ]
I just changed ``` return Task.FromResult(this.EvaluateJavascript(js)); ``` to: ``` var x = await webView.EvaluateJavascriptAsync(js); return x; ``` and now it works
15,875,665
I have problem (i think for you is simple to solve) with PHP and MySQL. I have database, that call "tekst". There is 3 column: 1. id (autoincrement), 2. date (timestamp), 3. tresc (text) and the site: index.html. I want to paste code like that `<?php echo "$id1"; ?>` into index.html to display a column "treść" assigned to some "id". Now I do like that: `$w = mysql_fetch_array(mysql_query("SELECT * FROM tekst WHERE id=5"));` `echo $w['tresc'];` but when I have many records, it will be troublesome. How to create MySQL Query to display what i want ? In one page i will have many ID's. Please help Thanks
2013/04/08
[ "https://Stackoverflow.com/questions/15875665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2190042/" ]
Try using `mysql_fetch_row`. **example** ``` mysql_fetch_row(mysql_query("SELECT * FROM tekst WHERE id=1")); ``` ### [`Official Document`](http://php.net/manual/en/function.mysql-fetch-row.php)
54,474,689
In my flutter app, I have a future that handles http requests and returns the decoded data. But I want to be able to send an error if the `status code != 200` that can be gotten with the `.catchError()` handler. **Heres the future:** ``` Future<List> getEvents(String customerID) async { var response = await http.get( Uri.encodeFull(...) ); if (response.statusCode == 200){ return jsonDecode(response.body); }else{ // I want to return error here } } ``` and when I call this function, I want to be able to get the error like: ``` getEvents(customerID) .then( ... ).catchError( (error) => print(error) ); ```
2019/02/01
[ "https://Stackoverflow.com/questions/54474689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4083636/" ]
### Throwing an error/exception: You can use either `return` or `throw` to throw an error or an exception. * ##### Using `return`: ```dart Future<void> foo() async { if (someCondition) { return Future.error('FooError'); } } ``` * ##### Using `throw`: ```dart Future<void> bar() async { if (someCondition) { throw Exception('BarException'); } } ``` --- ### Catching the error/exception: You can use either `catchError` or `try-catch` block to catch the error or the exception. * ##### Using `catchError`: ```dart foo().catchError(print); ``` * ##### Using `try-catch`: ```dart try { await bar(); } catch (e) { print(e); } ```
2,236,179
[![enter image description here](https://i.stack.imgur.com/XCd2q.jpg)](https://i.stack.imgur.com/XCd2q.jpg) I know n+1 = number of digits in $3^{2020}$ but how to find number of digits . How can we solve it **without using a calculator** . --- can we not solve it using binomial $3^{2020}=9^{1010}=(10-1)^{1010}$ after that I am stuck
2017/04/16
[ "https://math.stackexchange.com/questions/2236179", "https://math.stackexchange.com", "https://math.stackexchange.com/users/298843/" ]
Let $x=3^{2020}$ $$\lg x = 2020 \lg 3 \approx 2020(0.477)=963.7$$ $$x=10^{963.7}$$ Hence there are $964$ digits.
110,131
I'm considering creating a fictional multi-national black ops unit called S.W.O.R.D [(Special Worldwide Offensive Resolution Division)](http://tvtropes.org/pmwiki/pmwiki.php/Main/FunWithAcronyms) designed in a highly organized and militarized manner such as you might find with [Ancient](http://tvtropes.org/pmwiki/pmwiki.php/Main/FantasyCounterpartCulture) [Sparta](http://www.ancientmilitary.com/spartan-military.htm)... if the [Spartans used tanks, guns and cutting-edge technology](http://tvtropes.org/pmwiki/pmwiki.php/Main/DisSimile) supplied by DARPA. *Spartiates* (soldiers under the command of S.W.O.R.D) wear futuristic fully enclosed combat helmets modelled after helmets worn by the real-life *Spartiates* with an incorporated skull motif and resembling scowling faces. One such helmet includes the Corinthian-Type Helmet, which is worn by rank and file *Spartiates*. This helmet is vacuum-sealed and equipped with a variety of features such as large almond-shaped polarised lenses, small lights mounted to their lower halves and a pair of tubes connected to a re-breather in the wearer's armour. Just like their namesake, these helmets can be pushed up to on rest on the back of a *Spartiate*'s head. How practical would such a combat helmet be? ***Visual References*** [![Skeleton Warrior](https://i.stack.imgur.com/2taSc.jpg)](https://i.stack.imgur.com/2taSc.jpg) [![enter image description here](https://i.stack.imgur.com/vTLdP.jpg)](https://i.stack.imgur.com/vTLdP.jpg) [![enter image description here](https://i.stack.imgur.com/XnWLg.jpg)](https://i.stack.imgur.com/XnWLg.jpg) [![enter image description here](https://i.stack.imgur.com/vdH98.jpg)](https://i.stack.imgur.com/vdH98.jpg)
2018/04/21
[ "https://worldbuilding.stackexchange.com/questions/110131", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/-1/" ]
A heavy helmet makes it hard to turn your head ============================================== This might seem trivial, and it is in most situations, but if you don't need a heavy helmet, you shouldn't wear one. The more armor and electronics are packed into the helmet, the harder it is to move your head; that much is obvious. There is only so heavy a helmet can get, even on a Leonidas-neck. This is just something to keep in mind as you pack more and more gear into the helmet. The [real helmets used by SpecOps](https://www.hardheadveterans.com/products/ballistic-helmet?utm_medium=cpc&utm_source=googlepla&gclid=CjwKCAjwwuvWBRBZEiwALXqjw0QXTlY1TbTNgwwgMHo6glMb6immIduKpcNQ1p2WDX9SVbyPaMVhhxoCQCcQAvD_BwE) are barely over 1 kg. Why are you restricting the ability to breathe? =============================================== Do these soldiers expect to be attacked with chemical or biological weapons? Do they expect to go into the vacuum of space? If not, why would you so heavily restrict their respiration? I don't know if you've ever put a gas mask on, but if you run around in the desert with one one for a few days, it is very uncomfortable. On the one hand, moisture and bacteria from your exhaled breath will build up in the helmet. This can have a deleterious effect on your lungs after a long period of time. On the other hand, your exhaled breath will also collect inside your helmet and make it generally hot and uncomfortable. If you want a faceplate for protection, then consider making sure that there it is not sealed (all your pictures look sealed to me) so that there is adequate ventilation. Is it hot? ========== Speaking of running around in the desert with a gas mask on, there is a practical vision problem with that, too. Sweat from your forehead is naturally deflected by your eyebrows to the side of your face, away from your eyes. But contact between your forehead and the helmet and/or condensation within the mask can allow seat to get around that and impede your vision. And if it is hot out, a dark colored can on your head doesn't help the sweating situation. Even Darth Helmet [switched to khaki](https://www.google.com/search?biw=1600&bih=785&tbm=isch&sa=1&ei=bFbbWozSLO3p_Qao0pqIBw&q=darth%20helmet%20desert&oq=darth%20helmet%20desert&gs_l=psy-ab.3..0.3102.3825.0.4210.6.4.0.2.2.0.57.199.4.4.0....0...1c.1.64.psy-ab..0.6.204...0i8i30k1.0.fyWYAZKJY_o#imgrc=_) in the desert. This one isn't immediately solvable by ventilation. Any faceplate will run into sweat concerns in high temperatures. If you do all your fighting in Norway, then this is probably not a big deal. Don't differentiate by rank =========================== That gets senior officers shot. Even in tank combat in WWII, tanks with radio antennas looked more important and got shot more. One helmet should fit all. Can this mask stop anything important? Is it usable after one hit? ================================================================== The point of a faceplate is to prevent damage to the face, presumably. Can this faceplate stop a bullet? Maybe 5.56, probably not 7.62 or anything larger (it all depends on angle of impact). No face plate lightweight enough to not stress your neck is going to reasonably stop such an energetic round. So your faceplate is still useful for stopping shrapnel if you run into a lot of grenades. Do you run into a lot of grenades? Another thing to consider is what your faceplate looks like if you do stop a grenade. I imagine the see-through glass part is now completely damaged, and the helmet will have to be removed. This is the downside of a faceplate: a damaged helmet (penetrated, cracked, etc) is still mostly as useful as an intact helmet. A damaged faceplate that you can't see through is just deadweight. The real reason for a mask is information ========================================= The reason the modern army would consider a faceplate is to put information right in front of the operator's face. SpecOps in particular may find themselves chasing bad guys around town while on the phone with satellite operators who are using powerful tools to track the bad guy's movement. This is a thing that happens in real life. But here the faceplate damage thing comes to the fore. If you have a cracked faceplate, then you can't even wear it and use the information displays any more. If you depend on the information to do your job, this is bad. Better off to use something like Google Glasses and keep a spare in your pack. Cheap and lightweight means you have a backup option in place. Conclusion ========== There is a reason that the modern military doesn't use such things. I can't see any reason to wear such a mask, given the downsides, unless there was an expectation of operating in an environment where you can't breathe (chemical weapons or space).
8,355,945
I have a db file Resided in Flex Air Bindebug Folder,Here i want to Move/save this db File at another location let say In mydocument/or any Folder, I am not able to do it's programatically..Please help me out here. Thanks in advance.
2011/12/02
[ "https://Stackoverflow.com/questions/8355945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/430803/" ]
You can do a constant AJAX poll using the components shown here <http://www.primefaces.org/showcase/ui/ajaxPollHome.jsf>.
356
Well, almost a year since our conception and 'tis the season for community ads again! On all graduated sites, there are **Community Promotion Ads** which provide an opportunity for *relevant, useful* sites and tools to promote themselves with small ads. Last year, we created 2 ads and simply posted them everywhere. That was ... not a correct or appropriate use of ads. Ads should be relevant to the community in which they appear, and so dumping the same ad everywhere **is not OK**. For more details, see [this answer on last years ads post](https://cseducators.meta.stackexchange.com/a/136/58). All that said, I've created this post to track our community ads as we create them and post them on other sites. Here's how the system will work: Below, there will be a list of sites that we'd like to make ads for, and a list of posted ads. Anyone can volunteer to make an ad for a site, possibly one on the list or possibly a different site. *Remember: Taking the same ad and posting it for every site **is not permitted***. Once an ad is created, it should be posted as an answer on this question (**not** on the other sites community ad post). Once it's score is > 1, it will be posted on the target site. If there are multiple suggestions for a target site, only the highest voted will be posted. Sites which need ads -------------------- I've taken this list from last year: * [Raspberry Pi](https://raspberrypi.stackexchange.com) * [Mathematica](https://mathematica.stackexchange.com) * [Ask Ubuntu](https://askubuntu.com) * [Physics](https://physics.stackexchange.com) * [Info Sec](https://security.stackexchange.com) * [Unix and Linux](https://unix.stackexchange.com) * [Chemistry](https://chemistry.stackexchange.com) * [Academia](https://academia.stackexchange.com) * [Computer Science](https://cs.stackexchange.com) * [Theoretical CS](https://cstheory.stackexchange.com) * [Tex](https://tex.stackexchange.com) * [Mathematics](https://math.stackexchange.com) * [Crypto](https://crypto.stackexchange.com) Sites which have ads -------------------- * [Software Engineering](https://softwareengineering.meta.stackexchange.com/a/8696/199039) * [Computer Science](https://cs.meta.stackexchange.com/a/1464/72990) (Both of last years ads were posted by a moderator. See [1](https://cs.meta.stackexchange.com/a/1457/72990), [2](https://cs.meta.stackexchange.com/a/1458/72990)) * Cryptography [moderator reposted last years ad](https://crypto.meta.stackexchange.com/a/1006) * [Mathematica](https://mathematica.meta.stackexchange.com/a/2302/54822) (current score of 1) * [Mathematics](https://math.meta.stackexchange.com/a/27879/386000) (current score -1) Sites which have active ads (score >= 6) ---------------------------------------- * [None right now] Ad Requirements --------------- These are the **requirements** imposed by Stack Exchange for any community ads: * The image that you create must be 300 x 250 pixels, or double that if high DPI. * Must be hosted through our standard image uploader (imgur) * Must be GIF or PNG * No animated GIFs * Absolute limit on file size of 150 KB * If the background of the image is white or partially white, there must be a 1px border (2px if high DPI) surrounding it.
2018/01/29
[ "https://cseducators.meta.stackexchange.com/questions/356", "https://cseducators.meta.stackexchange.com", "https://cseducators.meta.stackexchange.com/users/58/" ]
[![We'd be happy to welcome you!](https://i.stack.imgur.com/pPRHs.png)](https://cseducators.stackexchange.com)
41,070
I have installed **android-sdk-linux** on my ubuntu 12.04 netbook and I see that the commands *android* (which opens the AVD Manager) and *emulator* (to which on appending the name of a specific AVD, the AVD boots) are not found! It suggested *qemulator* But that turned out to have nothing to do with the android-sdk-linux. I do know how to boot it via **eclipse**, where you open the AVD list and then select an AVD and click Start and then Launch. But I don't want to go through these many stages. Instead I would like Launch it using a single command line viz. the *emulator* command, which I found on the website developer.android.com. I followed installation instructions. Yet I didn't get success. UPDATE: As our friend suggested, I updated the $PATH variable and had partial success. However there is still an error and I have to get that rectified. Here is what panned out. ``` aneesh@nb-14:~$ export PATH=$PATH:android-sdk-linux/tools aneesh@nb-14:~$ emulator @Andreud emulator: ERROR: This AVD's configuration is missing a kernel file!! ```
2013/03/08
[ "https://android.stackexchange.com/questions/41070", "https://android.stackexchange.com", "https://android.stackexchange.com/users/24020/" ]
First step is finding out the OEM (manufacturer) of your handset. Coincidentally, the specs and body closely resembles that of [Cherry Mobile Titan](http://www.ilonggotechblog.com/2012/10/cherry-mobile-w500-titan-price-specs.html#.UTl_9uSUHI8) compared to [yours](http://www.muthofon.com/phonespecification/symphony-w90-2692.php). This is the [original version](http://www.gsmarena.com/spice_mi_500_stellar_horizon-5052.php). There is only a guide on how to root [here](http://www.droidiser.com/2012/10/spice-mi500-clockworkmod-guide.html). Can see no custom ROM available as of now/
46,157,145
I am trying to list GCS folders that start with a fixed string followed by alphanumeric character. I don't want to do a recursive listing. When I tried following Lets say we have following folder structure (I know there is no concept internally there is no concept of folder. It is just path prefix) ``` gs://somebucket/monitor/a gs://somebucket/monitor/a/a1.log.gz gs://somebucket/monitor/a/a2.log.gz gs://somebucket/monitor/b gs://somebucket/monitor/b/b1.log.gz gs://somebucket/monitor/b/b2.log.gz gs://somebucket/monitor/c gs://somebucket/monitor1/x gs://somebucket/monitor1/y gs://somebucket/monitor1/z ``` In output what I want is ``` gs://somebucket/monitor gs://somebucket/monitor1 ``` I have tried following ``` $ gsutil ls gs://somebucket/monitor* ``` And ``` $ gsutil ls gs://somebucket/monitor** ``` But neither give the required output Is there a way in gsutil to achieve the desired output
2017/09/11
[ "https://Stackoverflow.com/questions/46157145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8442593/" ]
In EVReflecdtion a Realm Object will now implement the EVCustomReflectable protocol by default so that it's able to get the realm properties. Please update to the latest version. Be aware that it will now also use Realm 3.
57,803,089
I need to get the selected item in a select property. This is how I get it ``` <div class="form-group"> <label>Plaza</label> <select formControlName="plaza" class="browser-default custom-select mb-4" (change)="onPlazaChange($event)" > <option value="" disabled>Plaza</option> <option *ngFor="let plaza of plazas" [ngValue]="plaza" >{{plaza.name}}</option> </select> </div> onPlazaChange(event: any) { console.log(event.target.value); } export class Plaza { id?: string; name: string; code: number; lanes: Lane[]; } export class Lane { number: number; type: string; } ``` I don't know what's wrong but I should get the object plaza not just the id alone. All I get is "Object".
2019/09/05
[ "https://Stackoverflow.com/questions/57803089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3825246/" ]
Based on the comments, I'm not entirely sure what the issue is but I hope this code could provide some assistance. Using .album rather than .smartAlbum could also be part of the issue. ``` private var fetchResult: PHFetchResult<PHAsset>! func fetchOptions(_ predicate: NSPredicate?) -> PHFetchOptions { let options = PHFetchOptions() options.sortDescriptors = [ NSSortDescriptor(key: "creationDate", ascending: false) ] options.predicate = predicate return options } } if let userLibraryCollection = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: nil).firstObject { self.fetchResult = PHAsset.fetchAssets(in: userLibraryCollection, options: fetchOptions(NSPredicate(format: "mediaType = \(PHAssetMediaType.image.rawValue)"))) } else { self.fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions(nil)) } ```
93,092
Is there a limit on number of criteria nodes that we can use process builder. Limit information on what I could find is: <https://help.salesforce.com/apex/HTViewHelpDoc?id=process_limits.htm&language=en_US>
2015/09/21
[ "https://salesforce.stackexchange.com/questions/93092", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/20859/" ]
The limit of process builder criteria nodes is 200
5,216,565
I'm trying to apply the object properties from objA to objB but I realised Ext.apply is flawed (or blessing?) in a way where it only applies first level objects together. Example: ``` var objA = { name: 'objA', baseParams: { cols: [1,2,3,4,5] } }; //used in subclass var objB = { name: 'objB', baseParams: { limit: 50, sort: 'name' } }; //used in baseclass var objC = { name: 'objC', baseParams: { as_hash: true, limit: 20 } }; Ext.apply(objB,objA); //used in subclass Ext.apply(objC,objB); //used in baseclass ``` Example will output: ``` obj = { name: 'objA', baseParams: { cols: [1,2,3,4,5] } }; ``` I'd like this output instead (expected output): ``` obj = { name: 'objA', baseParams: { cols: [1,2,3,4,5], as_hash: true, limit: 50, sort: 'name' } }; ``` How can I achieve this without doing this? ``` // subclass: var bpTemp = {}; bpTemp.baseParams = Ext.apply(objB.baseParams, objA.baseParams); Ext.apply(objB,objA); Ext.apply(objB,bpTemp); // base class: var bpTemp = {}; bpTemp.baseParams = Ext.apply(objC.baseParams, objB.baseParams); Ext.apply(objC,objB); Ext.apply(objC,bpTemp); ```
2011/03/07
[ "https://Stackoverflow.com/questions/5216565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/484578/" ]
You can change up the way Ext.apply() works so that a 4th argument can be a boolean implying "deep" apply -- this will work with your example (deep defaults to true): ``` Ext.apply = function(o, c, defaults, deep){ deep = deep!==false; // no "this" reference for friendly out of scope calls if(defaults){ Ext.apply(o, defaults); } if(o && c && typeof c == 'object'){ for(var p in c){ o[p] = (deep && Ext.isObject(o[p]) && Ext.isObject(c[p])) ? Ext.apply(o[p], c[p]) : c[p]; } } return o; }; ```
121,425
Take a non-empty matrix / numeric array containing positive integers as input. Return, in this order, the sums of the first row and column, then the second row and column and continue until there aren't any more rows or columns. Suppose the input is: ``` 2 10 10 2 4 9 7 7 2 9 1 7 6 2 4 7 1 4 8 9 ``` Then the output should be: ``` 45, 33, 16, 17 ``` Because: `2+9+1+7+10+10+2+4=45, 7+7+1+7+2+9=33, 6+4+2+4=16, 8+9=17`. Test cases: ----------- Test cases are on the following format: ``` Input --- Output ``` ``` 5 --- 5 .......... 1 4 ---- 5 .......... 7 2 --- 9 .......... 8 3 7 10 3 7 10 1 10 7 5 8 4 3 3 1 1 6 4 1 3 6 10 1 2 3 8 2 8 3 4 1 --- 62 40 33 18 .......... 30 39 48 1 10 19 28 38 47 7 9 18 27 29 46 6 8 17 26 35 37 5 14 16 25 34 36 45 13 15 24 33 42 44 4 21 23 32 41 43 3 12 22 31 40 49 2 11 20 --- 320 226 235 263 135 26 20 .......... 7 10 1 4 4 2 6 3 4 1 4 10 5 7 6 --- 34 20 20 ``` As arrays: ``` [[5]] [[1,4]] [[7],[2]] [[8,3,7,10,3,7,10,1],[10,7,5,8,4,3,3,1],[1,6,4,1,3,6,10,1],[2,3,8,2,8,3,4,1]] [[30,39,48,1,10,19,28],[38,47,7,9,18,27,29],[46,6,8,17,26,35,37],[5,14,16,25,34,36,45],[13,15,24,33,42,44,4],[21,23,32,41,43,3,12],[22,31,40,49,2,11,20]] [[7,10,1],[4,4,2],[6,3,4],[1,4,10],[5,7,6]] ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest solution in each language wins.
2017/05/18
[ "https://codegolf.stackexchange.com/questions/121425", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/31516/" ]
[CJam](https://sourceforge.net/p/cjam), ~~23~~ 18 bytes ======================================================= ``` {[{(:+\z}h;]2/::+} ``` Anonymous block expecting the argument on the stack and leaving the result on the stack. [Try it online!](https://tio.run/nexus/cjam#K6z7Xx1drWGlHVNVm2Eda6RvZaVd@7@u4H90tIKFAhAYgwhzIDY0wMI1jOWKhrBAYgqmIAKszQSu2BimTsEQxDKDyxrCZc1QzFMwgkuAjTKCs4wRemNjAQ "CJam – TIO Nexus") ### Explanation ``` [ e# Begin working in an array. { e# Do: (:+ e# Remove the first row of the matrix and sum it. \z e# Bring the matrix back to the top and transpose it. }h e# While the matrix is non-empty. ; e# Discard the remaining empty matrix. ] e# Close the array. 2/ e# Split it into consecutive pairs of elements (possibly with a singleton on the end). ::+ e# Sum each pair. ```
107,205
So here is the context: Three people are talking about a subject. One of them say: "These things happen. I can see Marie's point of view easily, having been around good universities for a lot of my life; I can see Helena' take at least somewhat." What does it mean in this case please ?
2016/10/22
[ "https://ell.stackexchange.com/questions/107205", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/43565/" ]
> > I can see Marie's **point of view** easily, having been around good universities for a lot of my life; I can see Helena's (or Helen's) **take** at least somewhat." > > > The sentence uses *take* to avoid repeating *point of view*. But your sentence needs to use an *apostrophe s* with the second name, just like with the first name: *Marie's*. As a noun **take** can mean *point of view* or *interpretation*. Several online dictionaries do not list this usage, and Collins lists it as "informal, mainly US." As a native speaker of American English, I can say it's informal but quite idiomatic. Even in [Collins](http://www.collinsdictionary.com/dictionary/english/take), you have to go down to the 84th and last entry to find this meaning: *take* (noun) > > a version or interpretation > > > But the first 76 definitions of *take* are for the verb, so it's not as uncommon as one might be led to believe. *At least somewhat* means *to a certain extent*. The speaker doesn't *see* or *understand* "Helena's (?) take" completely.
288,113
I'm building a Lightning Web Component that loads several records, modifies them based on user input then writes them back to to the database. It appears there is no way to instantiate object records in LWC as you can do in APEX. LWC documentation does mention the ability to import references to objects, but they do not appear to be classes. For example, the following code: ``` import { LightningElement } from "lwc"; import ACCOUNT_OBJECT from '@salesforce/schema/Account'; export default class CheckIn extends LightningElement { myAccount = new ACCOUNT_OBJECT(); } ``` Results in this error: > > [n is not a constructor] > > >
2019/12/12
[ "https://salesforce.stackexchange.com/questions/288113", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/53749/" ]
You said the LWC would load records so that's what you have to do. Details can be found here <https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.reference_wire_adapters_record> but basically you just have to use the `getRecord` wire method `import { getRecord} from 'lightning/uiRecordApi';` The full example by the documentation: ``` import { LightningElement, wire } from 'lwc'; import { getRecord, getFieldValue } from 'lightning/uiRecordApi'; import NAME_FIELD from '@salesforce/schema/Account.Name'; import OWNER_NAME_FIELD from '@salesforce/schema/Account.Owner.Name'; import PHONE_FIELD from '@salesforce/schema/Account.Phone'; import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry'; export default class Example extends LightningElement { @wire(getRecord, { recordId: '001456789012345678', fields: [NAME_FIELD, INDUSTRY_FIELD], optionalFields: [PHONE_FIELD, OWNER_NAME_FIELD] }) account; get name() { return getFieldValue(this.account.data, NAME_FIELD); } get phone() { return getFieldValue(this.account.data, PHONE_FIELD); } get industry(){ return getFieldValue(this.account.data, INDUSTRY_FIELD); } get owner() { return getFieldValue(this.account.data, OWNER_NAME_FIELD); } } ``` To update it you'll need to call the `updateRecord` method with the properly formatted parameters ``` updateRecord(recordInput: Record, clientOptions?: Object): Promise<Record> ``` where `recordInput` is ``` { "apiName": "Account", "fields": { "Name": "Universal Containers" } } ```
23,438,547
Example: you have two lists ("categories"): ``` catLow = [1,2,3,4,5] catHigh = [6,7,8,9,10] ``` Using pattern matching, how do you decide whether ``` val x = 7 ``` Is within the first list (category) or the second one? That's the general problem. My specific problem is doing that but in my case X is within a list as in: ``` val l = [1,7,2,4] ``` and I want to match it against something like: ``` case catHigh :: tail // i.e. starts with a "high" number case _ :: catLow :: tail // i.e. second element is a "low" number // where "high" and "low" are example category names implemented as lists ```
2014/05/02
[ "https://Stackoverflow.com/questions/23438547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/331021/" ]
``` val lowSet = Set(1, 2, 3, 4, 5) val highSet = Set(6, 7, 8, 9, 10) someList match { case catHigh :: tail if highSet(catHigh) => ... case _ :: catLow :: tail if lowSet(catLow) => ... } ``` A `Set` can be used as a function that returns whether the passed element is in the `Set`. Then, in the match statement, you can use pattern guards (introduced with `if`) to check whether matched values are in the set.
26,717,156
I want to pack the lowest two bytes of an integer into another in integer, an stuck at this ``` for ( int i = 0; i < 8 ; i ++){ if ((bitmask & ( 1 << i))) result |= 1 >> i; } ```
2014/11/03
[ "https://Stackoverflow.com/questions/26717156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2301022/" ]
Endian-independent solution: ``` x = ((y >> 0) & 0xFF) | ((y >> 8) & 0xFF); ```
22,905,997
Since I need to *refresh* Gradle quite often I wish to use a shortcut for this. Under ``` Settings > Keymaps ``` I just find the Gradle Tool Windows. I use IntellJ IDEA 13.1.
2014/04/07
[ "https://Stackoverflow.com/questions/22905997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/435336/" ]
There's an action in the IDE to "Refresh all external projects" which should kick off a refresh for the Gradle project.