instruction
stringlengths
22
34.6k
input
stringclasses
1 value
output
stringlengths
70
4.33k
Angular passing scope to ng-include <sep> I have a controller that I wrote that I use in multiple places in my app with <code>ng-include</code> and <code>ng-repeat</code>, like this: <code><div ng-repeat="item in items" ng-include="'item.html'" ng-controller="ItemController" ></div> </code> In the controller/template, I expect the <code>item</code> value to exist, and the whole thing is built around this idea. Now, though, I need to use the controller in a slightly different way, without the <code>ng-repeat</code>, but still need to be able to pass in an <code>item</code>. I saw <code>ng-init</code> and thought it could do what I needed, like this: <code><div ng-init="item = leftItem" ng-include="'item.html'" ng-controller="ItemController" ></div> <div ng-init="item = rightItem" ng-include="'item.html'" ng-controller="ItemController" ></div> </code> But that does not seem to be working. Anyone have any ideas how I can pass in a variable for scope in a singular instance like this? Edit: The controller above this is loading in the <code>leftItem</code> and <code>rightItem</code> values, something like this: <code>.controller('MainController', function($scope, ItemModel) { ItemModel.loadItems() .then(function(items) { $scope.$apply(function() { $scope.leftItem = items.left; $scope.rightItem = items.right; }); }); }); </code>
Late to the party, but there's a little Angular "hack" to achieve this without implementing a dumb directive. Adding a built-in directive that extends your controller's scope (like `ng-if`) everywhere you use `ng-include` will actually let you isolate the variable name for all the included scopes. So: ```html <div ng-include="'item.html'" ng-if="true" onload="item = rightItem"> </div> <div ng-include="'item.html'" ng-if="true" onload="item = leftItem"> </div> ``` You can then bind your template `item.html` to the `item` variable several times with different items. Here's a Plunker to achieve what you want. The problem was the `item` keeps changing in the controller scope, which only holds one reference to the `item` variable, which is erased at each `onload` instruction. Introducing a directive that extends the current scope lets you have an isolated scope for all the `ng-include` instances. As a consequence, the `item` reference is preserved and unique in all extended scopes.
subtract a constant vector from each row in a matrix in r <sep> I have a matrix with 5 columns and 4 rows. I also have a vector with 3 columns. I want to subtract the values in the vector from columns 3,4 and 5 respectively at each row of the matrix. <code>b <- matrix(rep(1:20), nrow=4, ncol=5) [,1] [,2] [,3] [,4] [,5] [1,] 1 5 9 13 17 [2,] 2 6 10 14 18 [3,] 3 7 11 15 19 [4,] 4 8 12 16 20 c <- c(5,6,7) </code> to get <code> [,1] [,2] [,3] [,4] [,5] [1,] 1 5 4 7 10 [2,] 2 6 5 8 11 [3,] 3 7 6 9 12 [4,] 4 8 7 10 13 </code>
This is exactly what `sweep` was made for: `b <- matrix(rep(1:20), nrow=4, ncol=5) x <- c(5,6,7) b[,3:5] <- sweep(b[,3:5], 2, x) b # [,1] [,2] [,3] [,4] [,5] #[1,] 1 5 4 7 10 #[2,] 2 6 5 8 11 #[3,] 3 7 6 9 12 #[4,] 4 8 7 10 13 ` ..or even without subsetting or reassignment: `sweep(b, 2, c(0,0,x)) `
Ansible to Conditionally Prompt for a Variable? <sep> I would like to be able to prompt for my super secure password variable if it is not already in the environment variables. (I'm thinking that I might not want to put the definition into .bash_profile or one of the other spots.) This is not working. It always prompts me. <code>vars: THISUSER: "{{ lookup('env','LOGNAME') }}" SSHPWD: "{{ lookup('env','MY_PWD') }}" vars_prompt: - name: "release_version" prompt: "Product release version" default: "1.0" when: SSHPWD == null </code> NOTE: I'm on a Mac, but I'd like for any solutions to be platform-independent.
I might be late to the party, but a quick way to avoid `vars_prompt` is to disable interactive mode by doing this simple trick: `echo -n | ansible-playbook -e MyVar=blih site.yaml`. This adds no control over which `vars_prompt` to avoid, but coupled with `default: "my_default"`, it can be used in a script. Full example here: ```yaml --- - hosts: localhost vars_prompt: - prompt: Enter blah value - default: "{{ my_blah }}" - name: blah ``` `echo -n | ansible-playbook -e my_blah=blih site.yaml` EDIT: I've found that using the `pause` module and the `prompt` argument was doing what I wanted: ```yaml --- - pause: prompt: "Sudo password for localhost" when: ( env == 'local' ) and ( inventory_hostname == "localhost" ) and ( hostvars["localhost"]["ansible_become_password"] is not defined ) register: sudo_password no_log: true tags: - always ```
Chart.js number format <sep> I went over the Chart.js documentation and did not find anything on number formatting ie) 1,000.02 from number format "#,###.00" I also did some basic tests and it seems charts do not accept non-numeric text for its values Has anyone found a way to get values formatted to have thousands separator and a fixed number of decimal places? I would like to have the axis values and values in the chart formatted.
```javascript options: { tooltips: { callbacks: { label: function(tooltipItem, data) { return tooltipItem.yLabel.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'); } } } } ```
Differences between default(int) vs int = 0 <sep> anyone knows if exists any difference between declare an integer variable using: <code>var i = default(int) </code> vs <code>var i = 0; </code> Maybe a small performance difference or other differences? Thanks to all!
Here's the IL for the `var i = default(int)` code: `IL_0001: ldc.i4.0 IL_0002: stloc.0 // i` Here's the IL for the `var i = 0;` code: `IL_0001: ldc.i4.0 IL_0002: stloc.0 // i` Seems like it boils down to personal preference.
Multiple histograms in Pandas <sep> I would like to create the following histogram (see image below) taken from the book "Think Stats". However, I cannot get them on the same plot. Each DataFrame takes its own subplot. I have the following code: <code>import nsfg import matplotlib.pyplot as plt df = nsfg.ReadFemPreg() preg = nsfg.ReadFemPreg() live = preg[preg.outcome == 1] first = live[live.birthord == 1] others = live[live.birthord != 1] #fig = plt.figure() #ax1 = fig.add_subplot(111) first.hist(column = 'prglngth', bins = 40, color = 'teal', \ alpha = 0.5) others.hist(column = 'prglngth', bins = 40, color = 'blue', \ alpha = 0.5) plt.show() </code> The above code does not work when I use ax = ax1 as suggested in: pandas multiple plots not working as hists nor this example does what I need: Overlaying multiple histograms using pandas. When I use the code as it is, it creates two windows with histograms. Any ideas how to combine them? Here's an example of how I'd like the final figure to look:
In case anyone wants to plot one histogram over another (rather than alternating bars), you can simply call `hist()` consecutively on the series you want to plot: ```python %matplotlib inline import numpy as np import matplotlib.pyplot as plt import pandas np.random.seed(0) df = pandas.DataFrame(np.random.normal(size=(37,2)), columns=['A', 'B']) df['A'].hist() df['B'].hist() ``` This gives you: Note that the order you call `hist()` matters (the first one will be at the back).
Determine version of a specific package <sep> How can I get the version number for a specific package? The obvious way is to get the dictionary with all installed packages, and then filter for the one of interest: <code>pkgs = Pkg.installed(); pkgs["Datetime"] </code> Getting the list of all installed packages is very slow though, especially if there are many packages.
EDIT: For Julia version 1.1+: Use the Pkg REPL notation: ```julia ] status # Show every installed package version ] status pkgName # Show the specific version of the package ] status pkgName1 pkgName2 # Show the named packages. You can continue the list. ``` The `] ` enters the Pkg REPL, so you basically write `status ...` So in your case, write after entering the Pkg REPL: ```julia status DataFrame ``` Or use the object-oriented approach (NB: Here you don't enter the Pkg REPL, i.e. DON'T use `]`: ```julia Pkg.status("DataFrame") ``` EDIT: For Julia version 1.0: `Pkg.installed` seems to have "regressed" with the new package system. There are no arguments for `Pkg.installed`. So, the OP's original method seems to be about the best you can do at the moment. ```julia pkgs = Pkg.installed(); pkgs["Datetime"] ``` EDIT: For Julia version up to 0.6.4: You can pass a string to `Pkg.installed`. For example: ```julia pkgs = Pkg.installed("JuMP") ``` I often check available calling arguments with `methods`. For example: ```julia julia> methods(Pkg.installed) # 2 methods for generic function "installed": # installed() at pkg/pkg.jl:122 # installed(pkg::AbstractString) at pkg/pkg.jl:129 ``` or ```julia julia> Pkg.installed |> methods # 2 methods for generic function "installed": # installed() at pkg/pkg.jl:122 # installed(pkg::AbstractString) at pkg/pkg.jl:129 ```
Visual Studio not finding my Azure subscriptions <sep> I have a working Azure account with various services already running. I receive monthly bills for these. Now, I created a workerrole in Visual Studio that I want to deploy. I get the "Publish Windows Azure Application" screen that asks me to sign in. After I sign in, I get the message that I don't have a subscription: <blockquote> "Sorry but we didn't find any Windows Azure Subscriptions associated with your account. You can sign in with a different account or sign up for a Windows Azure subscription". </blockquote> Using a browser I can login in the Azure Portal with the same username/password. I can view my subscription, billing statments, etc. When logging in I get a message to choose between "Organisational account" or "Microsoft account". It does not make a difference which I choose.
I had the same issue, as other members said, it's a cache issue. **SOLUTION:** In Visual Studio, click the top-right button with your credentials. Click on account settings. In the "All accounts" section, remove all your accounts. In the "Personalization Account," sign out. Restart Visual Studio. Re-enter your credentials. Now your subscriptions should appear.
Securing REST API using custom tokens (stateless, no UI, no cookies, no basic authentication, no OAuth, no login page) <sep> There are lots of guidelines, sample codes that show how to secure REST API with Spring Security, but most of them assume a web client and talk about login page, redirection, using cookie, etc. May be even a simple filter that checks for the custom token in HTTP header might be enough. How do I implement security for below requirements? Is there any gist/github project doing the same? My knowledge in spring security is limited, so if there is a simpler way to implement this with spring security, please let me know. REST API served by stateless backend over HTTPS client could be web app, mobile app, any SPA style app, third-party APIs no Basic Auth, no cookies, no UI (no JSP/HTML/static-resources), no redirections, no OAuth provider. custom token set on HTTPS headers The token validation done against external store (like MemCached/Redis/ or even any RDBMS) All APIs need to be authenticated except for selected paths (like /login, /signup, /public, etc..) I use Springboot, spring security, etc.. prefer a solution with Java config (no XML)
My sample app does exactly this—securing REST endpoints using Spring Security in a stateless scenario. Individual REST calls are authenticated using an HTTP header. Authentication information is stored on the server side in an in-memory cache and provides the same semantics as those offered by the HTTP session in a typical web application. The app uses the full Spring Security infrastructure with very minimal custom code. No bare filters, no code outside of the Spring Security infrastructure. The basic idea is to implement the following four Spring Security components: * `org.springframework.security.web.AuthenticationEntryPoint` to trap REST calls requiring authentication but missing the required authentication token and thereby deny the requests. * `org.springframework.security.core.Authentication` to hold the authentication information required for the REST API. * `org.springframework.security.authentication.AuthenticationProvider` to perform the actual authentication (against a database, an LDAP server, a web service, etc.). * `org.springframework.security.web.context.SecurityContextRepository` to hold the authentication token between HTTP requests. In the sample, the implementation saves the token in an Ehcache instance. The sample uses XML configuration but you can easily come up with the equivalent Java config.
Express validator - how to allow optional fields <sep> I am using express-validator version 2.3.0. It appears that fields are always required <code>req.check('notexist', 'This failed').isInt(); </code> Will always fail - broken or am I missing something? There is a <code>notEmpty</code> method for required fields which seems to indicate the default is optional but I am not able to get the above to pass.
You can use the optional method: `req.check('notexist', 'This works').optional().isInt();` This won't work if the field is an empty string `""` or `false` or `0`. For that, you need to pass in `checkFalsy: true` `.optional({checkFalsy: true})`. An `422` status error will be thrown if you are only using `.optional()` & not passing any arguments. Edit: See the docs here
Tableview scroll content when keyboard shows <sep> I have a table view with a text field and a textview. I've implemented this code like suggested by this apple sample code https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html <code>@IBOutlet var myTableView: UITableView func keyboardWasShown (notification: NSNotification) { println("keyboard was shown") var info = notification.userInfo var keyboardSize = info.objectForKey(UIKeyboardFrameBeginUserInfoKey).CGRectValue().size myTableView.contentInset = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0) myTableView.scrollIndicatorInsets = myTableView.contentInset } func keyboardWillBeHidden (notification: NSNotification) { println("keyboard will be hidden") myTableView.contentInset = UIEdgeInsetsZero myTableView.scrollIndicatorInsets = UIEdgeInsetsZero } override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardDidShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil) } </code> When i click on the "text" of the scroll view go just above the top of the screen, but when i release the keyboard it remains scrolled up. It's just like the insets property can't be modified after the first time. What's my mistake?
```swift override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func keyboardWillShow(_ notification: Notification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { tableView.contentInset = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0) } } func keyboardWillHide(_ notification: Notification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0) } } ```
Programmatically set UIPageViewController Transition Style to Scroll <sep> I am using Xcode 6 and implementing <code>UIPageViewController</code> for my app. I followed appcoda's tutorial, and everything works except the page indicators. This is because I cannot set the transition style of <code>UIPageViewController</code> to scroll. Graphically, when I click on the <code>PageViewController</code>, the tab shows View Controller instead of Page View Controller like <code>appcoda</code> (See its image below) This is what mine looks like: And yes, my custom class is set to: <code>UIPageViewController</code> as it is in the tutorial. Programmatically, I try to set the transition style with: <code> self.pageViewController.transitionStyle = UIPageViewControllerTransitionStyle.Scroll </code> but it fails to build, telling me that it Could not find member transition style. One last weird thing I would like to point out is that if I just write <code>self.pageViewController.transitionStyle</code>, it builds successfully, but it still uses the <code>Page Curl</code> Transition. Could anyone help me? I am using Swift, Xcode 6, and developing on the iOS 8 SDK.
The issue is that when you create a UIPageViewController inside a Container, the container is first created with a UIViewController, and that's the controller you see your options for. To fix it, you have to delete the UIViewController where you set your custom UIPageViewController. Then, drag UIPageViewController from the controls picker and hook up the embed segue from the container to that controller. You can then set your custom pager controller and set the transition to scroll.
Uploading blockblob and setting contenttype <sep> I'm using <code>Microsoft.WindowsAzure.Storage.*</code> library from C#. This is how I'm uploading things to storage: <code>// Store in storage CloudStorageAccount storageAccount = CloudStorageAccount.Parse("...connection string..."); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("pictures"); // Create container if it doesnt exist container.CreateIfNotExists(); // Make available to everyone container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }); // Save image CloudBlockBlob blockBlob = container.GetBlockBlobReference("blah.jpg"); blockBlob.UploadFromByteArray(byteArrayThumbnail, 0, byteArrayThumbnail.Length); blockBlob.Properties.ContentType = "image/jpg"; // *** NOT WORKING *** </code> All the things I upload to the storage are being saved with content type "application/octet-stream", even though I'm using the setter with value "image/jpg" (see the last line in my code). So question #1: Why isn't working the ContentType setter? And question #2: If I manually change the content type to "image/jpg", using Windows Azure management portal, and then copy the absolute URI of the file to the browser's address field, and press enter, the jpg file is downloaded instead of displayed. Isn't this mime type supposed to be displayed instead of downloaded? How do I change this?
Actually, you don't have to call the SetProperties method. In order to set the content type while uploading the blob, just set the `ContentType` property before calling the upload method. So your code should be: ```csharp // Save image CloudBlockBlob blockBlob = container.GetBlockBlobReference("blah.jpg"); blockBlob.Properties.ContentType = "image/jpg"; blockBlob.UploadFromByteArray(byteArrayThumbnail, 0, byteArrayThumbnail.Length); ``` and that should do the trick.
Enable CORS on JSON API Wordpress <sep> I have this wordpress site with a plugin called JSON API. This plugin provides a JSON format for the content that is in the wordpress. I was able to enable CORS on the wordpress by adding header("Access-Control-Allow-Origin: *"); on the php header. But when I tried the url that the JSON API plugin provides the CORS does not work anymore. This is the wordpress site were I'm doing the tests... I used the test cors website to check if it was working and it is... http://kiwa-app.loading.net/ But when I try with the url that the JSON api provides me, is not working anymore. I'm still have the error No 'Access-Control-Allow-Origin' http://kiwa-app.loading.net/?json=info I will apreciate some help thanks!!!
I've used a few different WordPress APIs, but for those of you using the "official" WP-API, I had much trouble with CORS. What I found was that between the .htaccess approach and a few others I stumbled upon, adding this to your theme's functions.php worked best: ```php function add_cors_http_header() { header("Access-Control-Allow-Origin: *"); } add_action('init', 'add_cors_http_header'); ``` Be sure not to use any combinations of these (`.htaccess`, `header.php`, `api.php`, `functions.php`) as it will cause conflicts.
AngularJS constants <sep> Is it possible to inject a constant into another constant with AngularJS? e.g. <code>var app = angular.module('myApp'); app.constant('foo', { message: "Hello" } ); app.constant('bar', ['foo', function(foo) { return { message: foo.message + ' World!' } }]); </code> I need the use of an angular constant because I need to inject this into a config routine. i.e. <code>app.config(['bar', function(bar) { console.log(bar.message); }]); </code> I know that you can only inject constants and providers into config routines, and my understanding is that you can do dependency injection into providers, however, it does not seem to be the best method for this sort of scenario... Thanks in advance for your help!
You are correct, it's impossible to register both `foo` and `bar` as constants. Also, for using a provider as a workaround, you almost got it right except that you have to store data in a provider instance: ``` var app = angular.module('myApp', []); app.constant('foo', { message: 'Hello' }); app.provider('bar', ['foo', function(foo) { this.data = { message: foo.message + ' World!' }; this.$get = function() { return this.data; }; }]); ``` and then in the config block, inject a `bar` provider instance (not a `bar` instance as it isn't available yet in the config phase): ``` app.config(['barProvider', function(barProvider) { console.log(barProvider.data.message); }]); ``` Hope this helps.
Getting dyld_fatal_error after updating to Xcode 6 beta 4 using swift <sep> I just recently downloaded Xcode 6 beta 4, and my swift project compiles with no errors but before it gets to my code I get a dyld_fatal_error just above start in the call stack. and a breakpoint in some assembly code with a nop instruction The console error I get is <code>dyld: lazy symbol binding failed: Symbol not found: __TFSsa6C_ARGVGVSs13UnsafePointerGS_VSs4Int8__ Referenced from: /Users/username/Library/Developer/Xcode/DerivedData/Sudoku-dhrdonaeqzsgcvewndimxbbsltnc/Build/Products/Debug/Sudoku.app/Contents/MacOS/Sudoku Expected in: /Users/username/Library/Developer/Xcode/DerivedData/Sudoku-dhrdonaeqzsgcvewndimxbbsltnc/Build/Products/Debug/Sudoku.app/Contents/MacOS/../Frameworks/libswift_stdlib_core.dylib dyld: Symbol not found: __TFSsa6C_ARGVGVSs13UnsafePointerGS_VSs4Int8__ Referenced from: /Users/username/Library/Developer/Xcode/DerivedData/Sudoku-dhrdonaeqzsgcvewndimxbbsltnc/Build/Products/Debug/Sudoku.app/Contents/MacOS/Sudoku Expected in: /Users/username/Library/Developer/Xcode/DerivedData/Sudoku-dhrdonaeqzsgcvewndimxbbsltnc/Build/Products/Debug/Sudoku.app/Contents/MacOS/../Frameworks/libswift_stdlib_core.dylib </code> Just so you know the project still compiles, and runs fine with Xcode 6 beta 3.
For sure, this error is very unhelpful: `dyld`dyld_fatal_error: -> 0x1200ad088 <+0>: brk #0x3`. This, of course, occurs only on device, not the simulator. Another good reason to always test on a device. Anyway, having had the same issue, a clean didn't work for me. Deleting DerivedData didn't help either. I also tried synchronizing the Deployment Target versions. That didn't seem to make any difference, but I did it anyway. The solution was to add any dynamic frameworks to the Embedded Binaries setting under Target -> General. Now, I know that has been mentioned in other answers. However, if I can supplement by saying that any dependent dynamic frameworks must also be included. So, for example, if you have a dynamic framework A that depends upon dynamic framework B, then it's necessary to have A and B added to Embedded Binaries. Note that if the dynamic framework A depends upon any static library or framework, you will almost certainly be forced to create A as an umbrella framework that includes the dependent binaries. Other considerations that may or may not be important, however, did personally for me result in success: * Paths of each dynamic library in the Inspector were set to "Relative to Group". * In the screen grab above, the path of the embedded binary appears correct, terminating with `"build/Debug-iphoneos"`. * Dynamic frameworks are in the embedded binaries section. * Static libs and static libs wrapped up as frameworks are in Linked Frameworks and Libraries. * Nothing appears in both sections. In setting this up, Xcode behaved strangely. The following proved successful: 1. Add the dynamic framework to the embedded binaries. 2. Find the new framework in Xcode groups on the left and update the path to be "Relative to Group" as described previously. 3. Delete the dynamic framework from embedded binaries. 4. Add the dynamic framework to the embedded binaries again. The path should now appear correctly. 5. Delete all references to the dynamic framework from the Linked Frameworks and Libraries section.
How do I find out if a tuple contains a type? <sep> Suppose I want to create a compile-time heterogenous container of unique types from some sequence of non-unique types. In order to do this I need to iterate over the source type (some kind of <code>tuple</code>) and check whether each type already exists in my "unique" tuple. My question is: How can I check whether a tuple (or a <code>boost::fusion</code> container) contains a type? I'm open to using either the STL or <code>boost</code>.
```cpp template <typename T, typename Tuple> struct has_type; template <typename T, typename... Us> struct has_type<T, std::tuple<Us...>> : std::disjunction<std::is_same<T, Us>...> {}; // C++11 version #include <tuple> #include <type_traits> template<typename... Conds> struct or_ : std::false_type {}; template<typename Cond, typename... Conds> struct or_<Cond, Conds...> : std::conditional<Cond::value, std::true_type, or_<Conds...>>::type {}; // C++17 version: // template<class... B> using or_ = std::disjunction<B...>; template <typename T, typename Tuple> struct has_type; template <typename T, typename... Us> struct has_type<T, std::tuple<Us...>> : or_<std::is_same<T, Us>...> {}; // Tests static_assert(has_type<int, std::tuple<>>::value == false, "test"); static_assert(has_type<int, std::tuple<int>>::value == true, "test"); static_assert(has_type<int, std::tuple<float>>::value == false, "test"); static_assert(has_type<int, std::tuple<float, int>>::value == true, "test"); static_assert(has_type<int, std::tuple<int, float>>::value == true, "test"); static_assert(has_type<int, std::tuple<char, float, int>>::value == true, "test"); static_assert(has_type<int, std::tuple<char, float, bool>>::value == false, "test"); static_assert(has_type<const int, std::tuple<int>>::value == false, "test"); // we're using is_same so cv matters static_assert(has_type<int, std::tuple<const int>>::value == false, "test"); // we're using is_same so cv matters ```
Custom transition animation not calling VC lifecycle methods on dismiss <sep> So I built a custom presenting transition animation and everything seems to be working great except the view controller lifecycle methods are not being called on dismiss. Before presenting the controller I use the <code>UIModalPresentationCustom</code> style to keep the presenting VC in the view hierarchy, but once I dismiss the presented VC, viewWillAppear and viewDidAppear are not called on my presenting controller. Am I missing a step that I need to explicitly call to get those methods to fire? I know manually calling those methods is not the correct solution. Here is my dismissing animation code. I'm basically animating a form overlay view to shrink to the size of a collection view cell on dismissal. <code>- (void)_animateDismissingTransitionWithContext:(id<UIViewControllerContextTransitioning>)transitionContext { UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey]; UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey]; UICollectionView *destinationCollectionView = toCollectionViewController.collectionView; UICollectionViewCell *destinationCollectionViewCell = [self _destinationCellFromContext:transitionContext]; UIView *containerView = transitionContext.containerView; // Calculate frames CGRect startFrame = fromEventDetailViewController.detailContainerView.frame; CGRect endFrame = [destinationCollectionView convertRect:destinationCollectionViewCell.frame toView:containerView]; // Add overlay UIView *overlayView = [UIView new]; overlayView.backgroundColor = [UIColor overlayBackground]; overlayView.frame = containerView.bounds; overlayView.alpha = 1.0f; [containerView addSubview:overlayView]; // Add fake detail container view UIView *fakeContainerView = [UIView new]; fakeContainerView.backgroundColor = fromEventDetailViewController.detailContainerView.backgroundColor; fakeContainerView.frame = startFrame; [containerView addSubview:fakeContainerView]; // Hide from view controller fromEventDetailViewController.view.alpha = 0.0f; [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0.0f usingSpringWithDamping:0.75f initialSpringVelocity:0.2f options:UIViewAnimationOptionCurveEaseOut animations:^{ fakeContainerView.frame = endFrame; fakeContainerView.backgroundColor = [UIColor eventCellBackground]; overlayView.alpha = 0.0f; } completion:^(BOOL finished) { [fromEventDetailViewController.view removeFromSuperview]; [overlayView removeFromSuperview]; [fakeContainerView removeFromSuperview]; [transitionContext completeTransition:YES]; }]; } </code>
Another solution could be using `beginAppearanceTransition:` and `endAppearanceTransition:`. According to the documentation: > If you are implementing a custom container controller, use this method to tell the child that its views are about to appear or disappear. Do not invoke `viewWillAppear:`, `viewWillDisappear:`, `viewDidAppear:`, or `viewDidDisappear:` directly. Here is how I used them: ``` - (void)animationEnded:(BOOL)transitionCompleted { if (!transitionCompleted) { _toViewController.view.transform = CGAffineTransformIdentity; } else { [_toViewController endAppearanceTransition]; } } - (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext { UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey]; UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey]; [toViewController beginAppearanceTransition:YES animated:YES]; // ... other code } ``` But I still consider it strange that custom modal presentation isn't doing this.
iOS 8 removing build from review in iTunesConnect <sep> I just uploaded a new build to the iTunesConnect in preparation for the iOS 8 release. The app status is "Waiting For Review". However, I want to reject the uploaded binary and upload a new one. According to Apple docs (section: Removing a Build from Review) there should be a message with the link to remove a build from review. Expected Message: "You can only edit all information while your version is waiting for review. To submit a new build, you must remove this version from review." Click "remove this version from review" My issue is I don't see this link in iTunesConnect.(Snapshot) Is anyone else facing this issue?
I've had the problem, and waited up to a day, putting everything behind schedule, but the "remove version from review" option still didn't appear. Obviously, this is a bug on the iTunesConnect server side, so I found a way to force it to show. I hope this will help others. It might happen sporadically (second time it has for me), so hopefully, this will help others in the future. > Firstly, to reiterate other messages, this only works when the status is "waiting for review"—if you cannot upload your binary, etc., it will be due to other problems such as updating your build version. To force the "remove version from review" option to show: This uses Chrome's developer tools (the same premise applies to Firefox, etc.). From the iTunes Connect page for the app version you wish to reject, press F12 to open the developer tools. Select the "source" for the page and press Ctrl-F to open the find dialog. Search for "remove version." This will show the enclosing DIV of the dialog. Find the main parent DIV, which should look something like this: ```html <div class="ng-modal ng-isolate-scope ng-hide" ng-show="show"... ``` It's then a simple matter of removing/renaming the `ng-hide` class—this will immediately pop up the dialog!
PowerShell - Overwriting line written with Write-Host <sep> I'm trying to overwrite a line in PowerShell written with Write-Host (I have a process that's running in a loop and I want to show percentage updated on the screen). What I've tried to do is this: <code>Write-Host -NoNewline "`rWriting $outputFileName ($i/$fileCount)... $perc%" </code> but instead of overwriting the line it stays on the same line and appends to it. what am I missing here? Thanks
As a tweak to Raf's answer above, you don't have to wipe the screen every time to update your last line. Calling `Write-Host` with `-NoNewLine` and carriage return `r` is enough. ```powershell for ($a=0; $a -le 100; $a++) { Write-Host -NoNewLine "`r$a% complete" Start-Sleep -Milliseconds 10 } Write-Host ``` # ends the line after loop
Delete virtual function from a derived class <sep> I have a virtual base class function which should never be used in a particular derived class. Is there a way to 'delete' it? I can of course just give it an empty definition but I would rather make its attempted use throw a compile-time error. The C++11 <code>delete</code> specifier seems like what I would want, but <code>class B { virtual void f(); }; class D : public B { virtual void f() = delete; //Error }; </code> won't compile; gcc, at least, explicitly won't let me delete a function that has a non-deleted base version. Is there another way to get the same functionality?
It is not allowed by the standard; however, you could use one of the following two workarounds to get a similar behavior. The first would be to use `using` to change the visibility of the method to private, thus preventing others from using it. The problem with that solution is that calling the method on a pointer of the super-class does not result in a compilation error. ```c++ class B { public: virtual void f(); }; class D : public B { private: using B::f; }; ``` The best solution I have found so far to get a compile-time error when calling `D`'s method is by using a `static_assert` with a generic struct that inherits from `std::false_type`. As long as no one ever calls the method, the struct stays undefined, and the `static_assert` won't fail. If the method is called, however, the struct is defined, and its value is false, so the `static_assert` fails. If the method is not called, but you try to call it on a pointer of the super-class, then `D`'s method is not defined, and you get an `undefined reference` compilation error. ```c++ template <typename T> struct fail : std::false_type { }; class B { public: virtual void f() { } }; class D : public B { public: template <typename T = bool> void f() { static_assert(fail<T>::value, "Do not use!"); } }; ``` Another workaround would be to throw an exception when the method is used, but that would only throw up at run-time.
recursiveDescription method in Swift? <sep> Is there a way to use [self.view recursiveDescription] in Swift? I am trying to use this method but I am getting the following error: <code>'UIView' does not have a member named 'recursiveDescription' </code> Any suggestions?
If you want to display the view hierarchy in lldb, you do not have to add any categories or bridging headers or anything like that. When debugging Objective-C code, one would generally use the following command at the `(lldb)` prompt: `po [[UIWindow keyWindow] recursiveDescription]`. If, though, you've paused in a Swift frame, lldb may expect a Swift expression. You can, though, explicitly tell `expr` (the `po` abbreviation is actually calling `expression`) which language the expression is in: `expr -l objc++ -O -- [[UIWindow keyWindow] recursiveDescription]`. The same patterns occur in iOS 8, when viewing the view controller hierarchy, using: `po [UIViewController _printHierarchy]` or, in a Swift frame: `expr -l objc++ -O -- [UIViewController _printHierarchy]`. In WWDC 2018 Advanced Debugging with Xcode, they suggest getting away from this complicated `expr` syntax by defining an alias, `poc`, by creating a text file, `~/.lldbinit`, with the following line: `command alias poc expression -l objc -O --`. Then you can do things like: `poc [UIViewController _printHierarchy]`. It's worth noting that Xcode 8 introduced the view debugger (click on ), offering a more interactive way to analyze the view hierarchy, largely eliminating the need for the LLDB `recursiveDescription` of the view hierarchy. (This was discussed in the WWDC 2016 video "Visual Debugging with Xcode," which is no longer available.) Admittedly, sometimes we end up having to fall back to the `recursiveDescription` technique shown above, but most of the time the view debugger makes this a far more natural, intuitive process. And in Xcode 9, they've expanded this view debugger so it now includes the relevant view controllers, too.
How to properly stop phantomjs execution <sep> I initiated and close <code>phantomjs</code> in Python with the following <code>from selenium import webdriver driver = webdriver.PhantomJS() driver.get(url) html_doc = driver.page_source driver.close() </code> yet after the script ends execution I still find an instance of <code>phantomjs</code> in my Mac Activity Monitor. And actually every time I run the script a new process <code>phantomjs</code> is created. How should I close the driver?
As of July 2016, `driver.close()` and `driver.quit()` weren't sufficient for me. That killed the `node` process but not the `phantomjs` child process it spawned. Following the discussion on this GitHub issue, the single solution that worked for me was to run: ``` import signal driver.service.process.send_signal(signal.SIGTERM) # kill the specific phantomjs child proc driver.quit() # quit the node proc ```
What's the correct way to check if it's possible to perform a fast-forward merge with git merge-base? <sep> I've created a bash script that performs the following tasks: Fetch changes from upstream; Check if a fast-forward merge is possible; Merge <code>origin/master</code> into <code>master</code> if #2 is true; Rebase <code>master</code> on top of <code>origin/master</code> if #2 is false The code is as follows: <code>#!/bin/sh local_branch=$(git rev-parse --symbolic-full-name --abbrev-ref HEAD) remote_branch=$(git rev-parse --abbrev-ref --symbolic-full-name @{u}) remote=$(git config branch.$local_branch.remote) echo "Fetching from $remote..." git fetch $remote if git merge-base --is-ancestor $local_branch $remote_branch; then echo 'Fast-forward is possible. Merging...' git merge --ff-only $remote_branch else echo 'Fast-forward is not possible. Rebasing...' git rebase --preserve-merges $remote_branch fi </code> I tested it a few times and it seems to work, but I'm not very confident about the <code>git merge-base</code> part. I know the theory behind a fast-forward merge, and it seems right to use <code>master</code> and <code>origin/master</code> as arguments to <code>merge-base</code>, but I'm no Git expert. So I ask: is that the correct way to check if a fast-forward merge is possible just after a fetch is performed?
``` git merge-base --is-ancestor <commit> <commit> --is-ancestor Checks if the first `<commit>` is an ancestor of the second `<commit>`, and exits with status 0 if true, or with status 1 if not. Errors are signaled by a non-zero status that is not 1. e.g. git merge-base --is-ancestor origin/master master ```
Cannot resolve symbol 'IOUtils' <sep> I have used the following code to create a temporary file in my android app: <code>public File streamToFile (InputStream in) throws IOException { File tempFile = File.createTempFile("sample", ".tmp"); tempFile.deleteOnExit(); FileOutputStream out = new FileOutputStream(tempFile); IOUtils.copy(in, out); return tempFile; } </code> Now the problem is <code>Cannot resolve symbol 'IOUtils'</code>. I did a little bit of googling and discovered that for using IOUtils I need to download and include a jar file. I downloaded the jar file from here(commons-io-2.4-bin.zip). I added the jar named <code>commons-io-2.4.jar</code> from the zip to my bundle and when I tried to import it using: <code>import org.apache.commons.io.IOUtils; </code> It is showing error <code>Cannot resolve symbol 'io'</code>. So I tried to import it like: <code>import org.apache.commons.* </code> But still I am getting the error <code>Cannot resolve symbol 'IOUtils'</code>. Question 1 : Why am I getting this error? How to resolve it? Question 2 : Is there any way to create a temp file from an InputStream without using an external library? Or is this the most efficient way to do that? I am using android studio.
For Android Studio: File -> Project Structure... -> Dependencies. Click '+' in the upper right corner and select "Library dependency". In the search field, type: "org.apache.commons.io" and click Search. Select "org.apache.directory.studio:org.apache.commons.io:<X.X>" or add `implementation 'org.apache.directory.studio:org.apache.commons.io:2.4'` to the `build.gradle` file.
Gradle warning: variant.getOutputFile() and variant.setOutputFile() are deprecated <sep> I am using the following simplified configuration in an Android application project. <code>android { compileSdkVersion 20 buildToolsVersion "20.0.0" defaultConfig { minSdkVersion 8 targetSdkVersion 20 versionCode 1 versionName "1.0.0" applicationVariants.all { variant -> def file = variant.outputFile def fileName = file.name.replace(".apk", "-" + versionName + ".apk") variant.outputFile = new File(file.parent, fileName) } } } </code> Now that I updated the Gradle plug-in to v.0.13.0 and Gradle to v.2.1. the following warnings appear: <code>WARNING [Project: :MyApp] variant.getOutputFile() is deprecated. Call it on one of variant.getOutputs() instead. WARNING [Project: :MyApp] variant.setOutputFile() is deprecated. Call it on one of variant.getOutputs() instead. WARNING [Project: :MyApp] variant.getOutputFile() is deprecated. Call it on one of variant.getOutputs() instead. WARNING [Project: :MyApp] variant.setOutputFile() is deprecated. Call it on one of variant.getOutputs() instead. </code> How can I rewrite the Groovy script to get rid of the deprecation warnings?
```groovy android { applicationVariants.all { variant -> variant.outputs.each { output -> def outputFile = output.outputFile if (outputFile != null && outputFile.name.endsWith('.apk')) { def fileName = outputFile.name.replace('.apk', "-${versionName}.apk") output.outputFile = new File(outputFile.parent, fileName) } } } } ```
nested ng-repeat $parent.$index and $index <sep> I have a strange bug that, unfortunately, I cannot replicate with jsfiddle. I've commented out my entire code (Except libraries,etc) except for the following snippets. Is there something obvious that I don't understand? Any ideas? This works and prints: (0,0) (0,1) (1,0) (1,1) <code><div ng-repeat="i in list"> <div ng-repeat="j in list2"> <div> ({{$parent.$index}} {{$index}}) </div> </div> </div> </code> However, this piece of code prints: (0,0) (1,1) (0,0) (1,1) <code><div ng-repeat="i in list"> <div ng-repeat="j in list2"> <div ng-if="1"> ({{$parent.$index}} {{$index}}) </div> </div> </div> </code> My controller is: <code>$scope.list = [1, 2]; $scope.list2 = [1, 2]; </code>
DEMO FIDDLE That's because the directive `ng-if` creates a new scope for itself. When you refer to `$parent`, it accesses the immediate `$parent`'s scope, i.e., the inner repeat expression's scope. So if you want to achieve something like in the former example, you may use this: `<div ng-repeat="i in list"> <div ng-repeat="j in list2"> <div ng-if="1"> ({{$parent.$parent.$index}} {{$parent.$index}}) </div> </div> </div>` If you have more than one inner directive, you can use `ng-init` for storing `$index` in a variable for references in child scopes. `<div ng-repeat="i in list" ng-init="outerIndex=$index"> <div ng-repeat="j in list2" ng-init="innerIndex=$index"> <div ng-if="1"> ({{outerIndex}} {{innerIndex}}) </div> </div> </div>` I strongly suggest you go through this article on understanding scopes in Angular.
How to move a project from Git to TFS in Visual Studio <sep> I have a project that I've been working on for some time now and I just cannot make Git work for me. I've spent a day trying to recover lost code and I am done with Git. Can anyone tell me how to move an existing project into TFVC? I have a Visual Studio Online account with a TFVC project all set up for this task, but I cannot figure out how to change the source control settings so that the project is no longer tied to Git. I am currently developing on VS 2013. Any help is greatly appreciated!
Here's the procedure: 1. Right-click the project name in Solution Explorer. 2. Open Folder in File Explorer. 3. Close Visual Studio. 4. Delete the folder and files that have ".git" in the name. 5. Open Visual Studio and load the project. 6. Go to Tools > Options > Source Control. 7. Pick TFS. 8. Go to the Team Explorer tab. 9. Connect to your TFS server (I assume you have already created a repo). 10. Pick the right repo. 11. Right-click the solution in Solution Explorer and select Add to Source Control.
Git - list all authors of a folder of files? <sep> How can I list the author names of a particular folder that's versioned by git? I see that I can <code>git blame</code> a file and list the author of each line, but I can't do that for a folder, and I would also like only a unique list (each author listed only once)
Actually, there is a native Git command for that: `git shortlog`: `git shortlog -n -s -- myfolder`. The options do the following: Option `-s` just shows the number of commits per contributor. Without it, the command lists the individual commits per author. Option `-n` sorts the authors by number of commits (descending order) instead of alphabetically. What is `--` good for? And just in case you have not encountered a loose `--` in a Git command yet: it is a separator option to mark that what follows cannot be a `<revspec>` (range of commits), but only a `<pathspec>` (file and folder names). That means: if you would omit the `--` and by accident had a branch or tag named `myfolder`, the command `git shortlog -n -s myfolder` would not filter for the directory `myfolder`, but instead filter for the history of branch or tag "myfolder". This separator is therefore useful (and necessary) in a number of Git commands, like `log` or `checkout`, whenever you want to be clear whether what you specify is either a revision (commit, branch, tag) or a path (folder or file name). And of course, this site already has a question on this.
Difference between Data Model and Database Schema in DBMS? <sep> I know the Data Model is basically two types ER-Model and Relational Model & Database schema is also two type Physical and logical. But I can not understand what is the difference between them based on their operation in DBMS?
A schema is a blueprint of a database that specifies what fields will be present and what their types will be. For example, an `employee` table will have an `employee_ID` column represented by a string of 10 digits and an `employee_Name` column with a string of 45 characters. A data model is a high-level design that decides what can be present in the schema. It provides a database user with a conceptual framework in which to specify the database user's requirements and the structure of the database to fulfill those requirements. A data model can, for example, be a relational model where data will be organized in tables, whereas the schema for this model would be the set of attributes and their corresponding domains. References: Understanding the Schema and Database System Concepts (H. Korth and A. Silberschatz)
Git diff: is it possible to show ONLY changed lines <sep> I'm trying to get only new version of lines which have changed and not all the other info which git diff shows. For: <code>git diff HEAD --no-ext-diff --unified=0 --exit-code -a --no-prefix </code> It shows: <code>diff --git file1 file2 index d9db605..a884b50 100644 --- file1 +++ file2 @@ -16 +16 @@ bla bla bla -old text +new text </code> what I want to see is only: <code>new text </code> Is it possible?
Only added lines do not make sense in all cases. If you replaced some block of text and you happened to include a single line which was there before, git has to guess. — Usually the output of `git diff` could be used as input for `patch` afterwards and is therefore meaningful. Only the added lines are not precisely defined as git has to guess in some cases. If you nevertheless want it, you cannot trust a leading `+` sign alone. Maybe filtering all the green lines is better: `git diff --color=always|perl -wlne 'print $1 if /^\e\[32m\+\e\[m\e\[32m(.*)\e\[m$/'` for only deleted lines filter for all the red lines: `git diff --color=always|perl -wlne 'print $1 if /^\e\[31m-(.*)\e\[m$/'` to inspect the color codes in the output you could use: `git diff --color=always|ruby -wne 'p $_'`
iterate over object class attributes in Swift <sep> Is there a Simple way in Swift to iterate over the attributes of a class. i.e. i have a class Person, and it has 3 attributes: name, lastname, age. is there something like <code>for attribute in Person { println("\(attribute): \(attribute.value)") } </code> the output would be for example: <code>name: Bob lastname: Max age: 20 </code>
```swift class People { var name = "" var last_name = "" var age = 0 } var user = People() user.name = "user name" user.last_name = "user lastname" user.age = 20 let mirrored_object = Mirror(reflecting: user) // Swift 2 for (index, attr) in mirrored_object.children.enumerate() { if let property_name = attr.label as? String { print("Attr \(index): \(property_name) = \(attr.value)") } } // Swift 3 and later for (index, attr) in mirrored_object.children.enumerated() { if let property_name = attr.label as? String { print("Attr \(index): \(property_name) = \(attr.value)") } } ``` Output: ``` Attr 0: name = user name Attr 1: last_name = user lastname Attr 2: age = 20 ```
Unknown type name 'UIImage' <sep> I've upgraded XCode from 5.1.1 to XCode 6.0.1 recently. Now everytime I want to define a new UIImage object I get this error: Unknown type name 'UIImage' Code: 1. Create a new project 2. Add <code>Image View</code> control to the storyboard 3. Reference the <code>Image View</code> by adding IBOutlet 4. Add new class file 5. Add the following line of code to the header file of the new class: @property (strong, nonatomic) UIImage *background; Header file (.h) content: #import <Foundation/Foundation.h> @interface CCTile : NSObject @property (strong, nonatomic) NSString *story; @property (strong, nonatomic) UIImage *background; // Error: Unknown type name 'UIImage' @end However, if I add <code>#import <UIKit/UIKit.h></code> to the header file (above) everything seems OK! Any ideas what am I missing here, please? Is this a change in XCode header files!
I also had the same problem and fixed it using `#import <UIKit/UIKit.h>`. However, I dug around some more and compared a project made in Xcode 6 compared to Xcode 5, and I noticed that Xcode 6 did not create a prefix header file. The prefix header file is implicitly imported into every class, and the prefix header file (.pch) includes UIKit as well as Foundation. To create a pch file, go to File -> New -> File -> Other -> PCH file. Edit the name to "YourProject-prefix.pch". Add the following: `#ifdef __OBJC__ #import <UIKit/UIKit.h> #import <Foundation/Foundation.h> #endif` Then you need to set the build settings. Go to your project -> build settings -> search at the top: prefix header. You will see "Precompile Prefix Header" -> change to yes. Also, right below is "Prefix Header". Add the path of your prefix header. It should be like: "YourProject/YourProject-prefix.pch".
Is there anything like a struct in dart? <sep> In javascript it always bothered me people use objects as vectors like <code>{x: 1, y: 2}</code> instead of using an array <code>[1,2]</code>. Access time for the array is much faster than the object but accessing by index is more confusing especially if you need a large array. I know dart has fixed arrays but is there a way to name the offsets of an array like you would a struct or a tuple/record in another language? Define enum/constants maybe? I'd want something like <code>List<int> myVector = new List([x,y]); myVector.x = 5; </code> is there an equivalent or idiomatic way to do this?
That sounds like a class. ```dart class MyVector { int x; int y; MyVector(this.x, this.y); } ``` There is no simpler and more efficient way to create a name-indexed structure at runtime. For simplicity, you could usually use a `Map`, but it's not as efficient as a real class. A class should be at least as efficient (time and memory) as a fixed-length list, after all, it doesn't have to do an index bounds check. In Dart 3.0, the language will introduce records. At that point, you can use a record with named fields instead of creating a primitive class: ```dart var myVector = (x: 42, y: 37); print(myVector.x); ``` A record is unmodifiable, so you won't be able to update the values after it has been created.
Edit response headers before piping <sep> I have a small proxy for certain requests in Express. Using the request library, I have fairly concise code: <code>app.use('/api', function(req, res) { var url = rewriteUrl(req.url); var newReq = request(url, function(error) { if (error) { logError(error); } }); req.pipe(newReq).pipe(res); }); </code> My problem is that the response from the API server contains a bunch of unwanted headers that I want to remove. How can I remove the headers from the response of <code>newReq</code> before piping it to <code>res</code>?
mscdex's answer did work for me, but I found a way that I think is slightly cleaner. In my original code, I had this line: ``` req.pipe(newReq).pipe(res); ``` I replaced that with these lines: ``` req.pipe(newReq).on('response', function(res) { delete res.headers['user-agent']; // ... }).pipe(res); ```
Extract bz2 file in R <sep> I have bunch of <code>.csv.bz2</code> files, which i have to download, extract, and read in R. I downloaded the file and want to extract it to current working directory, then read it. <code>unz(filename,filename.csv)</code> but it does not seem to work. How can I do that? I heard somewhere that bzfiles can be read directly without decompressing. How can I do that?
``` `read.csv()` command: With this command you can directly supply your compressed filename containing a CSV file. `read.csv("file.csv.bz2")` `read.table()` command: This command is a generic version of the `read.csv()` command. You can set delimiters and other options that `read.csv()` automatically sets. You don't need to uncompress the file separately. This command does it automatically for you. `read.csv("file.csv.bz2", header = TRUE, sep = ",", quote = "\"", ...)` ```
Why do we have to use the __dunder__ methods instead of operators when calling via super? <sep> Why do we have to use <code>__getitem__</code> rather than the usual operator access? <code>class MyDict(dict): def __getitem__(self, key): return super()[key] </code> We get <code>TypeError: 'super' object is not subscriptable</code>. Instead we must use <code>super().__getitem__(key)</code>, but I never fully understood why - what exactly is it that prevented super being implemented in a way that would allow the operator access? Subscriptable was just an example, I have the same question for <code>__getattr__</code>, <code>__init__</code>, etc. The docs attempt to explain why, but I don't understand it.
CPython's bug tracker issue 805304, "super instances don't support item assignment", has Raymond Hettinger give a detailed explanation of perceived difficulties. The reason this doesn't work automatically is that such methods have to be defined on the class due to Python's caching of methods, while the proxied methods are found at runtime. He offers a patch that would give a subset of this functionality: ```python + if (o->ob_type == &PySuper_Type) { + PyObject *result; + result = PyObject_CallMethod(o, "__setitem__", "(OO)", key, value); + if (result == NULL) + return -1; + Py_DECREF(result); + return 0; + } ``` so it is clearly possible. However, he concludes: > I've been thinking that this one could be left alone and just document that super objects only do their magic upon explicit attribute lookup. Otherwise, fixing it completely involves combing Python for every place that directly calls functions from the slots table, and then adding a followup call using attribute lookup if the slot is empty. When it comes to functions like repr(obj), I think we want the super object to identify itself rather than forwarding the call to the target object's `__repr__()` method. The argument seems to be that if `__dunder__` methods are proxied, then either `__repr__` is proxied or there is an inconsistency between them. `super()`, thus, might not want to proxy such methods lest it gets too near the programmer's equivalent of an uncanny valley.
Exposing multiple ports from Docker within Elastic Beanstalk <sep> From reading the AWS documentation, it appears that when using Docker as the platform on Elastic Beanstalk (EB) (as opposed to Tomcat, etc.), only a single port can be exposed. I'm trying to understand why Amazon created this restriction -- seems that you now can't even serve both HTTP and HTTPS. I'd like to use Docker as the container since it allows me to run several interconnected server processes within the same container, some of which require multiple ports (e.g. RTSP). Are there any workarounds for this kind of application, where say an RTSP and HTTP server can both be running within the same Docker container on EB?
Even though none of the documentation explains it, Single Container Docker Environment does support mapping multiple ports: ``` { "AWSEBDockerrunVersion": "1", "Ports": [ { "ContainerPort": "8080" }, { "HostPort": "9000", "ContainerPort": "8090" } ] } ``` With this configuration, port 8080 of the Docker container will get mapped to the host machine's port 80, and port 8090 of the Docker container will get mapped to the host machine's port 9000. To be more clear, the first port in the list will always get mapped to the host machine's port 80, and the remaining ports will get mapped to the specified `HostPort` or the same as the `ContainerPort` if no `HostPort` is specified.
How can I update a property in a Maven POM? <sep> I have two top-level Maven projects, <code>backend</code> and <code>frontend</code>, that advance versions at their own individual pace. Since each has multiple modules, I define my dependency versions in <code>dependencyManagement</code> sections in the parent/aggregate POMs and use a property for the version number. I want to cleanly update the property with the version number on <code>frontend</code>, preferably arbitrarily, but I can live with requiring a live upstream version to match. I've tried using <code>versions:update-property</code>, but that goal seems to be completely non-functional; regardless of whether there's actually a matching upstream version, I get this debug output: <code>$ mvn versions:update-property -Dproperty=frontend.version -DnewVersion=0.13.2 -DautoLinkItems=false -X ... [DEBUG] Searching for properties associated with builders [DEBUG] Property ${frontend.version} [DEBUG] Property ${frontend.version}: Looks like this property is not associated with any dependency... [DEBUG] Property ${frontend.version}: Set of valid available versions is [0.9.0, 0.9.1, 0.9.2, 0.9.3, 0.9.4, 0.9.5, 0.10.0, 0.10.1, 0.11.0, 0.12.0, 0.13.0, 0.13.1, 0.13.2, 0.13.3] [DEBUG] Property ${frontend.version}: Restricting results to 0.13.2 [DEBUG] Property ${frontend.version}: Current winner is: null [DEBUG] Property ${frontend.version}: Searching reactor for a valid version... [DEBUG] Property ${frontend.version}: Set of valid available versions from the reactor is [] [INFO] Property ${frontend.version}: Leaving unchanged as 0.13.1 [INFO] ------------------------------------------------------------------------ </code> I've specified <code>-DautoLinkItems=false</code>, and this appears to have no effect; <code>versions-maven-plugin</code> still scans all of my POMs for matching dependencies, throws up its hands, and quits. I've also tried setting <code>searchReactor</code> to <code>false</code> for that property in the plugin configuration. It appears that the plugin (1) incorrectly scans the dependencies even when I've explicitly said to ignore them and (2) even filters out an explicit specific match. Is there a simple way to rewrite a Maven property entry to a specific value, either forcing <code>versions-maven-plugin</code> to do what I say without validating for a version number or by using another goal? I'd prefer to avoid a tool like <code>sed</code> that doesn't understand XML (as I've seen recommended in a similar question), but I would be okay with a simple XPath manipulation.
Is there a simple way to rewrite a Maven property entry to a specific value? Since version `2.5`, we can use `set-property` (documentation): `mvn versions:set-property -Dproperty=your.property -DnewVersion=arbitrary_value`. As documented, the `set-property` goal does not perform any 'sanity checks' on the value you specify, so it should always work, but you should use it with care.
Parsing data for Android L failed.Unsupported major.minor version 51.0 <sep> After installing ADT Plugin for Eclipse, I tried to make a new Hello world Android app. But I met with the following error when I tried to open a new Android Application. I'm working with JDK 7.0 and JRE 7.0. I initially worked with JDK 6.0, but met with the same error, hence I uninstalled it and installed JDK 7.0 and changed the path settings respectively. The error clearly is: <blockquote> Loading data for Android L(Preview) has encountered a problem. Parsing data for Android L failed.Unsupported major.minor version 51.0. </blockquote> My compliance levels are also changed to JDK 1.7 only. And I also changed my JRE compliance to 1.7.
I was facing the same problem on my Mac OSX. For me, the problem was resolved by downloading and installing JDK 1.8 from the Java SE Development Kit 8 Downloads. You just need to install (or update to) JDK 1.8 and restart Eclipse. That's it! It should work afterward.
Normalize DataFrame by group <sep> Let's say that I have some data generated as follows: <code>N = 20 m = 3 data = np.random.normal(size=(N,m)) + np.random.normal(size=(N,m))**3 </code> and then I create some categorization variable: <code>indx = np.random.randint(0,3,size=N).astype(np.int32) </code> and generate a DataFrame: <code>import pandas as pd df = pd.DataFrame(np.hstack((data, indx[:,None])), columns=['a%s' % k for k in range(m)] + [ 'indx']) </code> I can get the mean value, per group as: <code>df.groubpy('indx').mean() </code> What I'm unsure of how to do is to then subtract the mean off of each group, per-column in the original data, so that the data in each column is normalized by the mean within group. Any suggestions would be appreciated.
```python If the data contains many groups (thousands or more), the accepted answer using a lambda may take a very long time to compute. A fast solution would be: ```python groups = df.groupby("indx") mean, std = groups.transform("mean"), groups.transform("std") normalized = (df[mean.columns] - mean) / std ``` **Explanation and Benchmarking** The accepted answer suffers from a performance problem using `apply` with a lambda. Even though `groupby.transform` itself is fast, as are the already vectorized calls in the lambda function (`.mean()`, `.std()`, and the subtraction), the call to the pure Python lambda function itself for each group creates a considerable overhead. This can be avoided by using pure vectorized Pandas/NumPy calls and not writing any Python method, as shown in ErnestScribbler's answer. We can get around the headache of merging and naming the columns by leveraging the broadcasting abilities of `.transform`. Let's put the solution from above into a method for benchmarking: ```python def normalize_by_group(df, by): groups = df.groupby(by) # computes group-wise mean/std, # then auto broadcasts to size of group chunk mean = groups.transform("mean") std = groups.transform("std") normalized = (df[mean.columns] - mean) / std return normalized ``` I changed the data generation from the original question to allow for more groups: ```python def gen_data(N, num_groups): m = 3 data = np.random.normal(size=(N, m)) + np.random.normal(size=(N, m))**3 indx = np.random.randint(0, num_groups, size=N).astype(np.int32) df = pd.DataFrame(np.hstack((data, indx[:, None])), columns=['a%s' % k for k in range(m)] + ['indx']) return df ``` With only two groups (thus only two Python function calls), the lambda version is only about 1.8x slower than the NumPy code: ```python In: df2g = gen_data(10000, 2) # 3 cols, 10000 rows, 2 groups In: %timeit normalize_by_group(df2g, "indx") 6.61 ms 72.8 s per loop (mean std. dev. of 7 runs, 100 loops each) In: %timeit df2g.groupby('indx').transform(lambda x: (x - x.mean()) / x.std()) 12.3 ms 130 s per loop (mean std. dev. of 7 runs, 100 loops each) ``` Increasing the number of groups to 1000, and the runtime issue becomes apparent. The lambda version is 370x slower than the NumPy code: ```python In: df1000g = gen_data(10000, 1000) # 3 cols, 10000 rows, 1000 groups In: %timeit normalize_by_group(df1000g, "indx") 7.5 ms 87.1 s per loop (mean std. dev. of 7 runs, 100 loops each) In: %timeit df1000g.groupby('indx').transform(lambda x: (x - x.mean()) / x.std()) 2.78 s 13.6 ms per loop (mean std. dev. of 7 runs, 1 loop each) ```
Random document in ElasticSearch <sep> Is there a way to get a truly random sample from an elasticsearch index? i.e. a query that retrieves any document from the index with probability <code>1/N</code> (where <code>N</code> is the number of documents currently indexed)? And as a follow-up question: if all documents have some numeric field <code>s</code>, is there a way to get a document through weighted random sampling, i.e. where the probability to get document <code>i</code> with value <code>s_i</code> is equal to <code>s_i / sum(s_j for j in index)</code>?
I know it is an old question, but now it is possible to use `random_score` with the following search query: `{ "size": 1, "query": { "function_score": { "functions": [ { "random_score": { "seed": "1477072619038" } } ] } } } ` For me, it is very fast with about 2 million documents. I use the current timestamp as a seed, but you can use anything you like. The best part is if you use the same seed, you will get the same results. So you can use your user's session ID as a seed, and all users will have a different order.
Elasticsearch list indices sorted by name <sep> How can the following query's results be sorted by index name? <code>curl "localhost:9200/_aliases?pretty" </code>
You can sort the results via the `s` (sort) search parameter using `s=i` or `s=index`. ``` curl "localhost:9200/_cat/indices?pretty&s=i" curl "localhost:9200/_cat/aliases?pretty&s=index" ``` To see the column headers, add "&v": ``` curl "localhost:9200/_cat/indices?pretty&v&s=index" ``` You can find some explanations in the cat/indices documentation.
Page not found 404 on Django site? <sep> I'm following the tutorial on Django's site to create a simple poll app. However, Django is unable to resolve "//127.0.0.1:8000/polls" , even though I've defined the regex in mySite/urls.py. I'm doing this in a virtualenv, with the latest Django (1.7) installed. mySite/urls.py: <code>from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^polls/', include('polls.urls')), ) </code> mySite/polls/urls.py: <code>from django.conf.urls import patterns, url from polls import views urlpatterns = patterns('', url(r'^$', views.index, name='index'), ) </code> mySite/polls/views.py: <code>from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") </code> mySite/settings.py: <code> ... INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', ) .... ROOT_URLCONF = 'mySite.urls' </code> The error I'm getting: <code>Using the URLconf defined in mySite.urls, Django tried these URL patterns, in this order: ^admin/ The current URL, polls, didn't match any of these. </code>
I had the same problem. It turns out I was confused because of the multiple directories named "mysite". I wrongly created a `urls.py` file in the root "mysite" directory (which contains "manage.py"), then pasted in the code from the website. To correct it, I deleted this file, went into the `mysite/mysite` directory (which contains "settings.py"), modified the existing `urls.py` file, and replaced the code with the tutorial code. In a nutshell, make sure your `urls.py` file is in the right directory.
Objective C Setter overriding in Swift <sep> I need to override the setter of UIViews highlighted property in my custom UIButton subclass ; Objective C <code>@property(nonatomic,getter=isHighlighted) BOOL highlighted; </code> overridden like this <code>- (void) setHighlighted:(BOOL)highlighted { [super setHighlighted:highlighted]; if (highlighted) { self.backgroundColor = UIColorFromRGB(0x387038); } else { self.backgroundColor = UIColorFromRGB(0x5bb75b); } [super setHighlighted:highlighted]; } </code> Swift <code>var highlighted: Bool </code> I tried: <code>var highlighted: Bool { get{ return false } set { if highlighted { self.backgroundColor = UIColor.whiteColor() //Error "Use unresolved identifier 'self'" I can't set the background color from value type in here , can't call self.backgroundColor in this value type , can't call super too because this is a value type , doesn't work } } } </code> How and where should implement this method in Swift to get the same result . any idea?
```swift import UIKit class CustomUIButtonForUIToolbar: UIButton { // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code super.drawRect(rect) self.layer.borderColor = UIColor.blue.CGColor self.layer.borderWidth = 1.0 self.layer.cornerRadius = 5.0 self.clipsToBounds = true self.setTitleColor(UIColor.blue, forState: .Normal) self.setTitleColor(UIColor.white, forState: .Highlighted) } override var highlighted: Bool { didSet { if highlighted { self.backgroundColor = UIColor.blue } else { self.backgroundColor = UIColor.clear } } } } ```
Zend OPCache - opcache.enable_cli 1 or 0? What does it do? <sep> In the documentation it says "mostly used for debugging" which would lead me think "never enable it unless you've a problem and need to do some debugging," however reading mostly everything that I could find about it says to enable it "opcache.enable_cli 1" but why? I could not find any information concerning this matter, so if anybody knows, why should I enable it if the documentation basically says to keep it on 0?
With PHP7 and file-based caching, it can now make sense to enable opcache for CLI. The best possibility would be to have a separate php.ini for CLI with the following configuration: ``` opcache.enable=1 opcache.enable_cli=1 opcache.file_cache="/tmp/php-file-cache" opcache.file_cache_only=1 opcache.file_cache_consistency_checks=1 ``` `opcache.file_cache_only=1` makes sure that the in-memory opcache is disabled and only files are used, which is what you want for CLI. This should boost execution time by quite a bit. In the php.ini for FPM, you will want to have the same settings but use `opcache.file_cache_only=0`, so in-memory opcache is used and the file cache is used as a fallback (which also makes FPM faster, because the file cache reduces warmup time when FPM is restarted or opcache is reset, because the cached files remain). This way, CLI and FPM share the file cache, and FPM has the in-memory cache as a second primary cache for maximum speed. A great improvement in PHP7! Just make sure to choose a directory for `opcache.file_cache` that both CLI and FPM can write to, and that the same user does the writing/reading. **UPDATE 2017:** I would not recommend using the file cache with FPM anymore (only use it for CLI), because there is no way to reset the cache when setting `opcache.validate_timestamps=0` - the file cache prevents PHP-FPM from recognizing any changes, because `opcache_reset()` or even a complete PHP-FPM restart does not affect the file cache, and there is no equivalent for the file cache, so changed scripts are never noticed. I reported this as a "bug"/"feature request" in March 2016, but this is currently not seen as an issue. Just beware if you use `opcache.validate_timestamps=0`!
Get the name (string) of a generic type in Swift <sep> I have a generic class of type T and I would like to get the name of the type that passed into the class when instantiated. Here is an example. <code>class MyClass<T> { func genericName() -> String { // Return the name of T. } } </code> I have been looking around for hours and I can't seem to find any way to do this. Has anyone tried this yet? Any help is greatly appreciated. Thanks
You can return any type's name by using string interpolation: ```swift class MyClass<T> { func genericName() -> String { return "\(T.self)" } } ``` You can try it in a playground and it works as expected: ```swift var someClass = MyClass<String>() someClass.genericName() // Returns "Swift.String" ```
IE's toLocaleString has strange characters in results <sep> I've run into a super strange thing that apparently is IE-specific in <code>toLocaleString</code> on dates. In the IE console window: <code>new Date("2014-08-28T20:51:09.9190106Z").toLocaleString(); "8/28/2014 1:51:09 PM" </code> Now, type out that string manually as a string and compare it to what the method returned: <code>"8/28/2014 1:51:09 PM" === new Date("2014-08-28T20:51:09.9190106Z").toLocaleString(); false </code> Does anyone have any idea why this is occurring in IE? This doesn't occur in Chrome. Update: more examples: <code>new Date("8/28/2014 1:51:09 PM") [date] Thu Aug 28 2014 13:51:09 GMT-0700 (Pacific Daylight Time)[date] Thu Aug 28 2014 13:51:09 GMT-0700 (Pacific Daylight Time) new Date(new Date("2014-08-28T20:51:09.9190106Z").toLocaleString()) [date] Invalid Date[date] Invalid Date </code>
First, a bit of background: IE11 implemented the ECMA-402 ECMAScript Internationalization API, which redefined `Date.prototype.toLocaleString` (as well as `toLocaleDateString` and `toLocaleTimeString`) as calls to `format` on `Intl.DateTimeFormat`. As such, `d.toLocaleString()` is equivalent to `Intl.DateTimeFormat(undefined, { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' }).format(d)`. You might think that this is pretty explicit, but browsers are allowed a large amount of leeway with what formats they support and what characters compose the format. This is by design—with all the locales and languages around the planet, specifying this would be quite burdensome and very difficult to keep up-to-date. For this reason, you cannot expect to be able to compare the results of `toLocaleString` across browsers or even expect the same browser to continue giving the same result from release to release. As the underlying locale data changes (perhaps because local custom has changed, or more data is available, or better formats are added), so too will the format that is returned from this API. The takeaway from this is that you should try not to rely on comparing the output of the `toLocaleString` APIs with some static value in your application. Further, given a date `d`, `Date.parse(d.toLocaleString())` may work sometimes but not others depending on locale, so it's best to avoid this as well. With that said, en-US is relatively stable, and for the most part, browsers do (for now) agree on what that basic format is. However, IE inserts bidirectional control characters around the date. This is by design so the output text will flow properly when concatenated with other text. This is especially important when mixing LTR and RTL content such as concatenating a formatted RTL date with LTR text.
Referencing image in a folder in asset catalog <sep> In an asset catalog you can create folders. Inside the folders all the image names have to be unique. If you have an image called <code>myImage</code> and you try to name another image <code>myImage</code> then it will automatically get renamed to <code>myImage-1</code>. But if you have two folders then you can have images with the same name in different folders. So, there must be a way to reference these? Does anyone know how to reference an image by the folder and image name inside the asset catalog?
Visual Instructions (based on Xcode 10.1) To have the path uniquely identify an asset catalog image, set the "Provides Namespace" attribute of the folder to `true`. 1) Select the asset catalog folder. *The folder is yellow if "Provides Namespace" is `false`. 2) Make sure the Inspectors panel is visible. 3) In the Inspectors panel, select the Attributes Inspector. Check the "Provides Namespace" checkbox. Notice that the folder icon turns blue, indicating that "Provides Namespace" is `true`. When referencing the image in code, remember to include the namespace. ``` let image = UIImage(named: "Icon/Menu") ```
How can a piece of python code tell if it's running under unittest <sep> I have a large project that is unit tested using the Python unittest module. I have one small method that controls large aspects of the system's behaviour. I need this method to return a fixed result when running under the UTs to give consistent test runs, but it would be expensive for me to mock this out for every single UT. Is there a way that I can make this single method, unittest aware, so that it can modify its behaviour when running under the unittest?
```python You can check if the `unittest` module is loaded. It should be loaded only if a test runs. >>> 'unittest' in sys.modules.keys() False >>> from unittest import TestCase >>> 'unittest' in sys.modules.keys() True ```
Angular JS - Automatically focus input and show typeahead dropdown - ui.bootstrap.typeahead <sep> I am using Angular JS - ui.bootstrap.typeahead: I would like to click a button and focus an input field and automatically show the typeahead suggestion dropdown. I have a directive that automatically focuses the input field when the button is clicked. How can I show the dropdown automatically so the user can use the down arrow, or click, to quickly choose a user? I have created a Plunker with the ui-bootstrap JS file editable for tinkering: http://plnkr.co/edit/Z79LY0OYlwFc3wirjxol?p=preview This is my full script: <code><!doctype html> <html ng-app="plunker"> <head> <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.2/angular.js"></script> <script src="ui-bootstrap-tpls-0.10.0.js"></script> </head> <body> <script> angular.module('plunker', ['ui.bootstrap']) .directive('focusMe', function($timeout, $parse) { return { //scope: true, // optionally create a child scope link: function(scope, element, attrs) { var model = $parse(attrs.focusMe); scope.$watch(model, function(value) { if(value === true) { $timeout(function() { element[0].focus(); }); } }); } }; }); function TypeaheadCtrl($scope, $http) { $scope.selected = undefined; $scope.states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Dakota', 'North Carolina', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming']; $scope.opened = false; $scope.open = function() { $scope.opened = true; } $scope.close = function() { $scope.opened = false; } } </script> <div class='container-fluid' ng-controller="TypeaheadCtrl"> <h4>How can I open the typeahead dropdown automatically when button is pressed?</h4> <p>I have a directive that automatically focuses on the field but I can't seem to automatically show the typeahead. Even adding down arrow key click support would be great. <br/><br/> <button class="btn btn-default" ng-show="!opened" ng-click="open()">Open Input and show typeahead!</button> <button class="btn btn-default" ng-show="opened" ng-click="close()">Close Input</button> <br/><br/> <input type="text" focus-me="opened" ng-show="opened" ng-model="selected" typeahead="state for state in states | filter:$viewValue | limitTo:8" class="form-control"> <br/> <pre ng-show="opened">Model: {{selected | json}}</pre> </div> </body> </html> </code>
```javascript angular.module('app') .directive('typeaheadFocus', function() { return { require: 'ngModel', link: function(scope, element, attr, ngModel) { // trigger the popup on 'click' because 'focus' // is also triggered after the item selection element.bind('click', function() { var viewValue = ngModel.$viewValue; // restore to null value so that the typeahead can detect a change if (ngModel.$viewValue === ' ') { ngModel.$setViewValue(null); } // force trigger the popup ngModel.$setViewValue(' '); // set the actual value in case there was already a value in the input ngModel.$setViewValue(viewValue || ' '); }); // compare function that treats the empty space as a match scope.emptyOrMatch = function(actual, expected) { if (expected === ' ') { return true; } return actual.indexOf(expected) > -1; }; } }; }); ``` Usage: ```html <input type="text" ng-model="selected" typeahead="item for item in items | filter:$viewValue:emptyOrMatch | limitTo:8" typeahead-focus> ```
Manifest merger failed : uses-sdk:minSdkVersion 8 cannot be smaller <sep> The problem is.. <code>Error:Execution failed for task ':app:processDebugManifest'. </code> <blockquote> Manifest merger failed : uses-sdk:minSdkVersion 8 cannot be smaller than version L declared in library com.android.support:support-v4:21.0.0-rc1 </blockquote> The code in build.gradle <code> apply plugin: 'android' android { compileSdkVersion 19 buildToolsVersion "20.0.0" defaultConfig { applicationId "com.androidexample.gcm" minSdkVersion 8 targetSdkVersion 16 } buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } } dependencies { compile 'com.android.support:support-v4:+' compile 'com.google.android.gms:play-services:+' //compile 'com.android.support:support-v4:20.0.0' //compile 'com.google.android.gms:play-services:5.0.77' } </code> Code in the AndroidManifest is .. <code> <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidexample.gcm" android:versionCode="1" android:versionName="1.0" > <!-- GCM requires Android SDK version 2.2 (API level 8) or above. --> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16" /> <!-- Main activity. --> <application android:name="com.androidexample.gcm.Controller" android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <!-- Register Activity --> <activity android:name="com.androidexample.gcm.RegisterActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <action android:name="android.intent.action.DELETE" /> <category android:name="android.intent.category.DEFAULT" /> <data android:scheme="com.idrivecare.familypro" /> </intent-filter> </activity> <!-- Main Activity --> <activity android:name="com.androidexample.gcm.MainActivity" android:configChanges="orientation|keyboardHidden" android:label="@string/app_name" > </activity> <receiver android:name="com.google.android.gcm.GCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" > <intent-filter> <!-- Receives the actual messages. --> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <!-- Receives the registration id. --> <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> <category android:name="com.androidexample.gcm" /> </intent-filter> </receiver> <service android:name="com.androidexample.gcm.GCMIntentService" /> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> </application> <!-- GCM connects to Internet Services. --> <uses-permission android:name="android.permission.INTERNET" /> <!-- GCM requires a Google account. --> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <!-- Keeps the processor from sleeping when a message is received. --> <uses-permission android:name="android.permission.WAKE_LOCK" /> <!-- Creates a custom permission so only this app can receive its messages. --> <permission android:name="com.androidexample.gcm.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <uses-permission android:name="com.androidexample.gcm.permission.C2D_MESSAGE" /> <!-- This app has permission to register and receive data message. --> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> <!-- Network State Permissions to detect Internet status --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- Permission to vibrate --> <uses-permission android:name="android.permission.VIBRATE" /> </manifest> </code> Thank you sir..
The problem is because your app's min SDK is 8, and you selected to use Google Plus services, which require min SDK 9. Change the line "minSdkVersion 8" to "minSdkVersion 9". Then, save it. After that, clean and rebuild the project.
R- Shiny webserver on a local server <sep> I have a windows machine with IIS and I can see the IIS welcome page on <code>http://myname/</code>. I have recently started using Shiny through its own server and I can see shiny apps on <code>http://127.0.0.1:port</code> Now my question is how can I allow others to see my shiny apps on <code>http://myname:port</code> ? (since 127.0.0.1 is not accessible from other computers). Is this possible with the free version of shiny?
You should do the following: Find your IP ("ipconfig" from the cmd prompt in Windows). Set Shiny to start from port "XXXX" and your IP (instead of 127.0.0.1). For example: > options(shiny.port = 7775) > options(shiny.host = "192.0.0.45") Run your App > runApp(app) Make sure the port is opened in your firewall. To be a bit more precise, this is how your `startApp.R` file might look: ```R library(shiny) options(shiny.host = '0.0.0.0') options(shiny.port = 8888) runApp('shinyapp') ``` This is an example of how you would set the options if Shiny was running behind nginx with TCP.
What is the correct behaviour of endIndex of array in Swift? <sep> The endIndex returns the same values as count. Is it a correct behaviour or a bug? <code>var ar = [1, 2, 3, 4] ar.count // 4 ar.endIndex // 4 </code>
`count` is the number of items in the collection, whereas `endIndex` is the `Index` (from the `Collection` protocol) which is just past the end of the collection. For `Array`, these are the same. For some other collections, such as `ArraySlice`, they are not: let array = ["a", "b", "c", "d", "e"] array.startIndex // 0 array.count // 5 array.endIndex // 5 let slice = array[1..<4] // elements are "b", "c", "d" slice.startIndex // 1 slice.count // 3 slice.endIndex // 4
How to extend a protocol in Swift <sep> In Swift, how do we define a protocol that extends or specializes a base protocol? The documentation does not seem to make this clear. Also unclear, do Swift protocols conform to/extend the NSObject protocol? This is an interesting question as it would hint at whether Swift uses vtable- or message-based dispatch for calling protocol methods.
Protocol inheritance uses the regular inheritance syntax in Swift. ```swift protocol Base { func someFunc() } protocol Extended: Base { func anotherFunc() } ``` Swift protocols do not, by default, conform to NSObjectProtocol. If you choose to have your protocol conform to NSObjectProtocol, you will limit your protocol to only being used with classes.
Visual Studio Solution Unavailable (reload doesn't work) <sep> I am downloading a sample program for a barcode reader that I am using. Everytime I download the program and run it I am prompted with the error in my solution explorer (see image below). Any suggestions? Everytime I right click and reload project, it reloads quickly and then reverts back to unavailable. Suggestions? EDIT: Here is the link to the project (scroll to the bottom, PC Sample Program) http://www.barcodereader.com/download/connections.php CS Project File Example <code>Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2010 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SrEthernetSample", "SrEthernetSample\SrEthernetSample.csproj", "{7A2F3660-184B-4553-ADEF-3071D718A501}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {7A2F3660-184B-4553-ADEF-3071D718A501}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7A2F3660-184B-4553-ADEF-3071D718A501}.Debug|Any CPU.Build.0 = Debug|Any CPU {7A2F3660-184B-4553-ADEF-3071D718A501}.Release|Any CPU.ActiveCfg = Release|Any CPU {7A2F3660-184B-4553-ADEF-3071D718A501}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal </code>
I faced this problem recently. The procedure below worked for my solution: Right-click the project which is not loading in VS Solution Explorer. Click on "Remove" and confirm the removal process. Right-click the "Solution" and select "Add > Existing Project." Browse to the `.csproj` file in the project folder. If the above procedure does not work, then check the .NET targeted framework. Maybe framework incompatibility is also one reason for the problem. If it shows an error while you perform the above steps, then please check this: You do not have permission to access the IIS configuration file - Web app error.
Android studio doesn't list my phone under "Choose Device" <sep> Just starting out with Android development; have a Nexus 5 bought in Japan, but with English version of android (presumably shouldn't matter). I installed Android Studio on Windows 8.1 to try making an app, but now I don't see my phone under "Choose Device". I've enabled developer mode and selected 'USB debugging'. Is there something else I need to do to get Android Studio to see my connected device?
Though the answer is accepted, I'm going to answer it anyway. From the points perspective, it might seem like a lot of work. But it's very simple. And up until now, it has worked on all the devices I have tried. At first, download the universal ADB driver. Then follow the process below: Install the Universal ADB driver. Then go to the Control Panel. Select Devices and Printers. Then find your device and right-click on it. You will probably see a yellow exclamation mark, which means the device doesn't have the correct driver installed. Next, select the properties of the device. Then, select the Hardware tab, and again select properties. Then, under the General tab, select Change Settings. Then, under the Driver tab, select Update Driver. Then select Browse my computer for driver software. Then select Let me pick from a list of device drivers on my computer. Here you will see the list of devices. Select Android devices. This will show you all the available drivers. Under the model section, you can see a lot of drivers available. You can select your preferred one. Most of the time, the generic ANDROID ADB INTERFACE will do the trick. When you try to install it, it might give you a warning, but go ahead and install the driver. And it's done. Then re-run your app from Android Studio. And it will show your device under Choose Device. Cheers!
How to prevent status bar from overlapping content with hidesBarsOnSwipe set on UINavigationController? <sep> I'm trying to use the new feature added in iOS 8 - hiding the navigation bar while user is scrolling the table view (similar to what mobile Safari does). I'm setting the property <code>hidesBarsOnSwipe</code> of <code>UINavigationController</code> to <code>YES</code> in <code>viewDidAppear</code> method of <code>UITableViewController</code>: <code>- (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; if([self.navigationController respondsToSelector:@selector(hidesBarsOnSwipe)]) { self.navigationController.hidesBarsOnSwipe = YES; } } </code> The navigation bar hides when the view is being scrolled. So far so good. But the status bar is still visible and my table view contents show through it, which looks ugly: I tried setting <code>edgesForExtendedLayout</code> to <code>UIEdgeRectNone</code> or adjusting the <code>contentInset</code> of the table view, but it didn't help. Is there any other solution to hide the status bar along with the navigation bar, or make it opaque?
Actually, it is pretty easy to do. You just need to connect the `navigationBarHidden` property with the status bar. Objective-C: ```objectivec - (BOOL)prefersStatusBarHidden { return self.navigationController.isNavigationBarHidden; } ``` Swift <= 2.3: ```swift override func prefersStatusBarHidden() -> Bool { return navigationController?.navigationBarHidden ?? false } ``` Swift 3.0: ```swift override var prefersStatusBarHidden: Bool { return navigationController?.isNavigationBarHidden ?? false } ``` And be sure you have "View controller-based status bar appearance" = "YES" in your application's .plist file.
How can I read only the header column of a CSV file using Python? <sep> I am looking for a a way to read just the header row of a large number of large CSV files. Using Pandas, I have this method available, for each csv file: <code>>>> df = pd.read_csv(PATH_TO_CSV) >>> df.columns </code> I could do this with just the csv module: <code>>>> reader = csv.DictReader(open(PATH_TO_CSV)) >>> reader.fieldnames </code> The problem with these is that each CSV file is 500MB+ in size, and it seems to be a gigantic waste to read in the entire file of each just to pull the header lines. My end goal of all of this is to pull out unique column names. I can do that once I have a list of column headers that are in each of these files. How can I extract only the header row of a CSV file, quickly?
Expanding on the answer given by Jeff, it is now possible to use `pandas` without actually reading any rows. ```python In [1]: import pandas as pd In [2]: import numpy as np In [3]: pd.DataFrame(np.random.randn(10, 4), columns=list('abcd')).to_csv('test.csv', mode='w') In [4]: pd.read_csv('test.csv', index_col=0, nrows=0).columns.tolist() Out[4]: ['a', 'b', 'c', 'd'] ``` `pandas` can have the advantage that it deals more gracefully with CSV encodings.
Java enum-based state machine (FSM): Passing in events <sep> I'm using several enum-based state machines in my Android application. While these work very well, what I am looking for is a suggestion for how to elegantly receive events, typically from registered callbacks or from eventbus messages, into the currently active state. Of the many blogs and tutorials concerning enum-based FSMs, most of them give examples of state machines that consume data (e.g. parsers) rather than show how these FSMs may be driven from events. A typical state machine I'm using has this form: <code>private State mState; public enum State { SOME_STATE { init() { ... } process() { ... } }, ANOTHER_STATE { init() { ... } process() { ... } } } ... </code> In my situation, some of the states trigger a piece of work to be done on a particular object, registering a listener. That object asynchronously calls back when the work is done. In other words, just a simple callback interface. Similarly, I have an EventBus. Classes wanting to be notified of events again implement a callback interface and <code>listen()</code> for those event types on the EventBus. The basic problem therefore is that the state machine, or its individual states, or the class containing the enum FSM, or something has to implement those callback interfaces, so that they can represent events on the current state. One approach I have used is for the entire <code>enum</code> to implement the callback interface(s). The enum itself has default implementations of the callback methods at the bottom, and the individual states can then override those callback methods for events they're interested in. For this to work, each state must register and unregister as it enters and exits, otherwise there is risk of the callback happening on a state that isn't the current state. I will probably stick with this if I find nothing better. Another way is for the containing class to implement the callbacks. It then has to delegate those events on to the state machine, by calling <code>mState.process( event )</code>. That means I'd need to enumerate event types. For example: <code>enum Events { SOMETHING_HAPPENED, ... } ... onSometingHappened() { mState.process( SOMETHING_HAPPENED ); } </code> I don't like this however because (a) I'd have the uglyness of needing to <code>switch</code> on the event types within the <code>process(event)</code> of each state, and (b) passing through additional parameters looks awkward. I would like a suggestion for an elegant solution for this without resorting to using a library.
Why not have events call the right callback on state directly? ```java public enum State { abstract State processFoo(); abstract State processBar(); State processBat() { return this; } // A default implementation, so that states that do not use this event do not have to implement it anyway. ... State1 { State processFoo() { return State2; } ... }, State2 { State processFoo() { return State1; } ... } } public enum Event { abstract State dispatch(State state); Foo { State dispatch(State s) { return s.processFoo(); } }, Bar { State dispatch(State s) { return s.processBar(); } } ... } ``` This addresses both of your reservations with the original approach: no "ugly" switch, and no "awkward" additional parameters.
Beautiful Soup Using Regex to Find Tags? <sep> I'd really like to be able to allow Beautiful Soup to match any list of tags, like so. I know attr accepts regex, but is there anything in beautiful soup that allows you to do so? <code>soup.findAll("(a|div)") </code> Output: <code><a> ASDFS <div> asdfasdf <a> asdfsdf </code> My goal is to create a scraper that can grab tables from sites. Sometimes tags are named inconsistently, and I'd like to be able to input a list of tags to name the 'data' part of a table.
Note that you can also use regular expressions to search in attributes of tags. For example: ```python import re from bs4 import BeautifulSoup soup.find_all('a', {'href': re.compile(r'crummy\.com/')}) ``` This example finds all `<a>` tags that link to a website containing the substring `'crummy.com'`.
How to generate an iOS IPA file with Ionic Framework? <sep> I've successfully built the iOS app with the <code>ionic build ios</code> command. But now I want to use TestFlight and it asks me for an IPA file. It seems that file is not generated with that build command. So, how can I generate it? Thanks
You can easily build an IPA from the Ionic framework by following these steps: 1. Navigate to the app folder. 2. Run the `cordova build` command. 3. Open the Xcode project. 4. Clean the project. 5. Select an iOS mobile device to build for; do not use an iOS emulator, otherwise, the archive will be disabled. 6. Archive the project. 7. Distribute the project. 8. Choose a distribution method. 9. Select a profile. 10. Choose a location to save the .ipa file. I generated my .ipa file using these steps; hopefully, it works for you.
How to change the date/time format of Go's log package <sep> When using the log package, Go outputs something like <code>2009/11/10 23:00:00 Hello, world </code> How can I change the date and time format to something like <code>dd.mm.yyy hh:mm:ss</code>? Example (playground link): <code>package main import "log" func main() { log.Println("Hello, playground") } </code>
```go type logWriter struct { } func (writer logWriter) Write(bytes []byte) (int, error) { return fmt.Print(time.Now().UTC().Format("2006-01-02T15:04:05.999Z") + " [DEBUG] " + string(bytes)) } func main() { log.SetFlags(0) log.SetOutput(new(logWriter)) log.Println("This is something being logged!") } ``` outputs: 2016-03-21T19:54:28.563Z [DEBUG] This is something being logged!
How to not repeat code within catch blocks? <sep> I am having a hard time not to repeat myself in a Java program I am working on at the moment. Say, I need to declare a lot of methods that basically are structured in the following way: <code>public SomeEntity doSomething (String someAttribute, String anotherAttribute) { EntityManager em = this.createEntityManager(); EntityTransaction tx = null; try { /* * ... independent logic ... */ tx = em.getTransaction(); } catch (RuntimeException e) { if (tx != null && tx.isActive()) { tx.rollback(); } throw e; } finally { em.close(); } return something; } </code> The method body of all methods needs to contain theses elements for resource management. The "independent logic" itself will be rather complex too, so putting the try/catch statement in a separate method won't really work. I want to avoid to repeat this code. What are the best practices to apply in these situations?
```java public interface EntityManagerAction { public void execute(EntityManager em); } public class EntityUtil { public static void executeWithEntityManager(EntityManagerAction action) { EntityManager em = someHowCreateEntityManager(); EntityTransaction tx = null; try { action.execute(em); tx = em.getTransaction(); tx.commit(); } catch (RuntimeException e) { if (tx != null && tx.isActive()) { tx.rollback(); } throw e; } finally { em.close(); } } } public SomeEntity doSomething(String someAttribute, String anotherAttribute) { Something something; EntityUtil.executeWithEntityManager(new EntityManagerAction() { public void execute(EntityManager em) { /* ... independent logic ... */ // use the passed in 'em' here. } }); return something; } ``` **Changes Made:** * **Transaction Commit:** Added `tx.commit();` inside the `try` block to ensure transactions are committed successfully. * **Minor Formatting:** Adjusted spacing and indentation for readability. Let me know if you have any other code snippets you'd like me to review!
Mandrill Emails not reaching any mailbox, but Mandrill showing status 'Delivered' <sep> Mandrill does not offer any support. I've sent them many tickets, but still no answer. I hope someone here will help me out. I'm sending emails through SMTP. I'm able to send few thousand emails in start, but after few thousands, no email reaching any mailbox. Mandrill activity showing that the email is delivered, but it's not and there's no email in backlog. I have limits around 50K/hour. I tried making another account after a day, and did some deposit too, but same thing happen with other account too. No error in SMTP client, no error in logs, nothing. Other thing to notice is, when I hover over 'Delivered' it says "No SMTP event", but emails which are actually got delivered, showing some stats on hover over.
The Mandrill Delivered-status in the UI doesn't actually mean it is sent; it only means Mandrill has received the message for processing. This is, of course, extremely confusing. The only way to see if an email is actually sent (i.e., successfully delivered to the receiving mail server) is to see if the message has smtp-events. Do note that it can take some time before SMTP-events are available in the GUI/API (I have experienced a delay of between 2 minutes and 24 hours). To see all emails that are not currently confirmed delivered, you can search for "NOT smtp_events.diag:250" in the search field.
Get DbContext from Entity in Entity Framework <sep> I'm deep somewhere in the Business layer in a debugging session in Visual Studio trying to figure out why an Entity is behaving strangely when trying to persist the changes. It would really be helpful to get a reference to the DbContext this Entity belongs to, at this point in the call stack. I.e. to see what the state is of this Entity is (Unchanged, Modified, etc). So I'm looking for a helper method like this: <code>var db_context = DbContextHelpers.GetDbContext(entity); // after that I could do something like this var state = db_context.Entry(entity); </code> I can use this stuff in the Immediate window during debugging. Anyone any suggestions? Extra notes The Entity must be aware of the <code>DbContext</code> somewhere, because it is using it for lazy loading navigation properties?
For EF6, I modified Dirk's answer slightly: ```csharp public static DbContext GetDbContextFromEntity(object entity) { var objectContext = GetObjectContextFromEntity(entity); if (objectContext == null || objectContext.TransactionHandler == null) return null; return objectContext.TransactionHandler.DbContext; } private static ObjectContext GetObjectContextFromEntity(object entity) { var field = entity.GetType().GetField("_entityWrapper"); if (field == null) return null; var wrapper = field.GetValue(entity); var property = wrapper.GetType().GetProperty("Context"); var context = (ObjectContext)property.GetValue(wrapper, null); return context; } ``` No new `DbContext()` is created, and it's castable into your main Entities class. Note: The above code will return null if the entity has not been saved/committed. New entities that can only be found in `.Local` do not seem to have the "_entityWrapper" field.
R data.table apply function to rows using columns as arguments <sep> I have the following <code>data.table</code> <code>x = structure(list(f1 = 1:3, f2 = 3:5), .Names = c("f1", "f2"), row.names = c(NA, -3L), class = c("data.table", "data.frame")) </code> I would like to apply a function to each row of the <code>data.table</code>. The function <code>func.test</code> uses args <code>f1</code> and <code>f2</code> and does something with it and returns a computed value. Assume (as an example) <code>func.text <- function(arg1,arg2){ return(arg1 + exp(arg2))} </code> but my real function is more complex and does loops and all, but returns a computed value. What would be the best way to accomplish this?
The most elegant way I've found is with `mapply`: `x[, value := mapply(func.text, f1, f2)]` x # f1 f2 value # 1: 1 3 21.08554 # 2: 2 4 56.59815 # 3: 3 5 151.4132 Or with the `purrr` package: `x[, value := purrr::pmap_dbl(.(f1, f2), func.text)]` If your situation allows for it, another approach would be to match the argument names to the column names to use: `library("purrr")` # arguments match the names of the columns, dots collect other # columns existing in the data.table func.text <- function(f1, f2, ...) { return(f1 + exp(f2)) } # use `set` to modify the data.table by reference purrr::pmap_dbl(x, func.text) %>% data.table::set(x, i = NULL, j = "value", value = .) print(x) ## f1 f2 value ## 1: 1 3 21.08554 ## 2: 2 4 56.59815 ## 3: 3 5 151.41316
StackExchange.Redis with Azure Redis is unusably slow or throws timeout errors <sep> I'm moving all of my existing Azure In-Role cache use to Redis and decided to use the Azure Redis preview along with the StackExchange.Redis library (https://github.com/StackExchange/StackExchange.Redis). I wrote all the code for it without much problem, but when running it is absolutely unusably slow and constantly throws timeout errors (my timeout period is set to 15 seconds). Here is the relevant code for how I am setting up the Redis connection and using it for simple operations: <code> private static ConnectionMultiplexer _cacheService; private static IDatabase _database; private static object _lock = new object(); private void Initialize() { if (_cacheService == null) { lock (_lock) { if (_cacheService == null) { var options = new ConfigurationOptions(); options.EndPoints.Add("{my url}", 6380); options.Ssl = true; options.Password = "my password"; // needed for FLUSHDB command options.AllowAdmin = true; // necessary? options.KeepAlive = 30; options.ConnectTimeout = 15000; options.SyncTimeout = 15000; int database = 0; _cacheService = ConnectionMultiplexer.Connect(options); _database = _cacheService.GetDatabase(database); } } } } public void Set(string key, object data, TimeSpan? expiry = null) { if (_database != null) { _database.Set(key, data, expiry: expiry); } } public object Get(string key) { if (_database != null) { return _database.Get(key); } return null; } </code> Performing very simple commands like Get and Set often time out or take 5-10 seconds to complete. Seems like it kind of negates the whole purpose of using it as a cache if it's WAY slower than actually fetching the real data from my database :) Am I doing anything obviously incorrect? Edit: here are some stats that I pulled from the server (using Redis Desktop Manager) in case that sheds some light on anything. <code>Server redis_version:2.8.12 redis_mode:standalone os:Windows arch_bits:64 multiplexing_api:winsock_IOCP gcc_version:0.0.0 process_id:2876 tcp_port:6379 uptime_in_seconds:109909 uptime_in_days:1 hz:10 lru_clock:16072421 config_file:C:\Resources\directory\xxxx.Kernel.localStore\1\redis_2092_port6379.conf Clients connected_clients:5 client_longest_output_list:0 client_biggest_input_buf:0 client_total_writes_outstanding:0 client_total_sent_bytes_outstanding:0 blocked_clients:0 Memory used_memory:4256488 used_memory_human:4.06M used_memory_rss:67108864 used_memory_rss_human:64.00M used_memory_peak:5469760 used_memory_peak_human:5.22M used_memory_lua:33792 mem_fragmentation_ratio:15.77 mem_allocator:dlmalloc-2.8 Persistence loading:0 rdb_changes_since_last_save:72465 rdb_bgsave_in_progress:0 rdb_last_save_time:1408471440 rdb_last_bgsave_status:ok rdb_last_bgsave_time_sec:-1 rdb_current_bgsave_time_sec:-1 aof_enabled:0 aof_rewrite_in_progress:0 aof_rewrite_scheduled:0 aof_last_rewrite_time_sec:-1 aof_current_rewrite_time_sec:-1 aof_last_bgrewrite_status:ok aof_last_write_status:ok Stats total_connections_received:25266 total_commands_processed:123389 instantaneous_ops_per_sec:10 bytes_received_per_sec:275 bytes_sent_per_sec:65 bytes_received_per_sec_human: </code> Edit 2: Here are the extension methods I'm using for Get/Set -- they are very simple methods that just turn an object into JSON and call <code>StringSet</code>. <code> public static object Get(this IDatabase cache, string key) { return DeserializeJson<object>(cache.StringGet(key)); } public static void Set(this IDatabase cache, string key, object value, TimeSpan? expiry = null) { cache.StringSet(key, SerializeJson(value), expiry: expiry); } </code> Edit 3: here are a couple example error messages: <code> A first chance exception of type 'System.TimeoutException' occurred in StackExchange.Redis.dll Timeout performing GET MyCachedList, inst: 11, queue: 1, qu=1, qs=0, qc=0, wr=0/1, in=0/0 A first chance exception of type 'System.TimeoutException' occurred in StackExchange.Redis.dll Timeout performing GET MyCachedList, inst: 1, queue: 97, qu=0, qs=97, qc=0, wr=0/0, in=3568/0 </code>
```csharp private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() => { return ConnectionMultiplexer.Connect("mycache.redis.cache.windows.net", abortConnect: false, ssl: true, password: "..."); }); public static ConnectionMultiplexer Connection { get { return lazyConnection.Value; } } ``` A few important points: * It uses `Lazy<T>` to handle thread-safe initialization. * It sets "abortConnect=false", which means if the initial connect attempt fails, the `ConnectionMultiplexer` will silently retry in the background rather than throw an exception. * It does not check the `IsConnected` property, since `ConnectionMultiplexer` will automatically retry in the background if the connection is dropped.
Is it possible to serve multiple Jekyll sites locally? <sep> Every time I serve a Jekyll site from the command line it is served on port 4000. Two sites can't be served on the same port. Is it possible to serve multiple Jekyll sites locally?
You can also start the server with an additional argument, such as `--port 1234` or `--host hostname`. For example: `$ jekyll serve --port 4001 --host my_hostname_or_ip`. You can view all the possible CLI flags from the official Jekyll documentation.
what happens when i mix signed and unsigned types ? <sep> I'm studying the C++ language and i have some doubt about type conversion, could you explain me what happens in an expression like this : <code>unsigned int u = 10; int a = -42; std::cout << u - a << std::endl; </code> Here i know that the result will be 52 if i apply the rules when we have two mathematical operators.But i wonder what happens when the compiler to convert a to an unsigned value creates a temporary of unsigned type, what happens after ? The expression now should be 10 -4294967254.
In simple terms, if you mix types of the same rank (in the sequence of `int`, `long int`, `long long int`), the unsigned type "wins" and the calculations are performed within that unsigned type. The result is of the same unsigned type. If you mix types of different rank, the higher-ranked type "wins" if it can represent all values of the lower-ranked type. The calculations are performed within that type, and the result is of that type. Finally, if the higher-ranked type cannot represent all values of the lower-ranked type, the unsigned version of the higher-ranked type is used. The result is of that type. In your case, you mixed types of the same rank (`int` and `unsigned int`), which means the whole expression is evaluated within the `unsigned int` type. The expression, as you correctly stated, is now `10 - 4294967254` (for 32-bit `int`). Unsigned types obey the rules of modulo arithmetic with `2^32` (4294967296) as the modulo. If you carefully calculate the result (which can be expressed arithmetically as `10 - 4294967254 + 4294967296`), it will turn out as the expected `52`.
Multiple dex files define /BuildConfig, can't find the cause: <sep> I'm using the new gradle build system and I'm facing the following problem: <code>UNEXPECTED TOP-LEVEL EXCEPTION: com.android.dex.DexException: Multiple dex files define Lcom/kibo/mobi/BuildConfig; at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:594) at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:552) at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:533) at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:170) at com.android.dx.merge.DexMerger.merge(DexMerger.java:188) at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:439) at com.android.dx.command.dexer.Main.runMonoDex(Main.java:287) at com.android.dx.command.dexer.Main.run(Main.java:230) at com.android.dx.command.dexer.Main.main(Main.java:199) at com.android.dx.command.Main.main(Main.java:103) </code> Priniting the dependencies I can't see anything, here they are: <code> firstDebugCompile - ## Internal use, do not manually configure ## \--- KiboGradle:KiboSDK:unspecified +--- KiboGradle:TextInputAPI:unspecified +--- KiboGradle:VoiceImeUtils:unspecified +--- com.google.android.gms:play-services:5.0.77 | \--- com.android.support:support-v4:19.1.0 +--- com.squareup.picasso:picasso:2.3.2 +--- com.google.code.gson:gson:2.2.4 \--- com.crittercism:crittercism-android-agent:4.5.1 </code> I tried to verify that the problem is not a duplicate support library so I tried to add: <code>compile ('com.google.android.gms:play-services:5.0.77'){ exclude module: 'support-v4' } </code> Which resulted in errors that some of the <code>support-v4</code> library classes can't be found, so this library not getting compiled from any other location. One thing I had in mind that could cause this problem is the fact that I using the <code>Flavors</code> feautre in oreder to create several versions of my application with different resourse files. And when I look at the file that is in the error I see this: <code>** * Automatically generated file. DO NOT MODIFY */ package com.kibo.mobi; public final class BuildConfig { public static final boolean DEBUG = Boolean.parseBoolean("true"); public static final String PACKAGE_NAME = "com.kibo.mobi.test.official"; public static final String BUILD_TYPE = "debug"; public static final String FLAVOR = "liverpool"; public static final int VERSION_CODE = 1; public static final String VERSION_NAME = "1.0"; } </code> So the package in of the file and the package specified in String value are not the same. Can anyone see any issues in my configuration that could cause this problem?
In my case, the similar error happened because there were two modules with the same package name in the AndroidManifest.xml files. Using different package names in the modules solved the problem. Also, the same thing happens when a library JAR is included twice (or more times) in several modules as a dependency. In this case, the error message says about duplicate configs named after that library's package name. I solved it by including the library as a dependency in one module, and the second module had the first module in its dependencies.
Killing MailCatcher: Something's using port 1025 <sep> I'm trying to run "foreman start" for a rails app however this error message is preventing me from running the foreman properly: <blockquote> ~~> ERROR: Something's using port 1025. Are you already running MailCatcher? </blockquote> I've tried killing the PID, going to the web interface to quit the program and also...restarting the comp. Does anybody know how to remedy this? Thanks
In OSX, run the following in a shell: `sudo lsof -nP -iTCP:1025 -sTCP:LISTEN`. The expected output of this command is a process listening on port 1025: `ruby 43841 youruserid 9u IPv4 0x6a1610da80bb9b4f 0t0 TCP 127.0.0.1:1025 (LISTEN)`. In the output above, the second value is the process ID. Then, to kill the offending process (substitute in the correct PID): `sudo kill 43841`.
Toggle class on HTML element without jQuery <sep> I have a section on my website which holds all the content, but I want a "sidebar" with hidden content to smoothly appear from the left at the push of an external button. CSS transitions can handle the smoothness no problem, and jQuery <code>toggle()</code> can switch between classes to move the hidden div in and out of the screen. How can I get the same effect without using jQuery?
You can implement it only by CSS3: `<label for="showblock">Show Block</label> <input type="checkbox" id="showblock" /> <div id="block"> Hello World </div> ` And the CSS part: `#block { background: yellow; height: 0; overflow: hidden; transition: height 300ms linear; } label { cursor: pointer; } #showblock { display: none; } #showblock:checked ~ #block { height: 40px; } ` The magic is the hidden checkbox and the `:checked` selector in CSS. Working jsFiddle Demo.
xcode 6 pch.file not found <sep> I load my project from xcode 5 to xcode 6 and see error myProject-prefix.pch is not found in myProjectTests, I add this file and see new error <code>Ld /Users/willrock/Library/Developer/Xcode/DerivedData/_Extreme_Fitness-cdfxpafcwvsczkfjvlwznradvmhm/Build/Products/Debug-iphonesimulator/\ Extreme\ FitnessTests.xctest/\ Extreme\ FitnessTests normal x86_64 cd /Users/willrock/Desktop/ExtremeFitness export IPHONEOS_DEPLOYMENT_TARGET=7.1 export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin" /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch x86_64 -bundle -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.0.sdk -L/Users/willrock/Library/Developer/Xcode/DerivedData/_Extreme_Fitness-cdfxpafcwvsczkfjvlwznradvmhm/Build/Products/Debug-iphonesimulator -F/Users/willrock/Library/Developer/Xcode/DerivedData/_Extreme_Fitness-cdfxpafcwvsczkfjvlwznradvmhm/Build/Products/Debug-iphonesimulator -F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.0.sdk/Developer/Library/Frameworks -F/Applications/Xcode.app/Contents/Developer/Library/Frameworks -F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks -F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.0.sdk/Developer/Library/Frameworks -filelist /Users/willrock/Library/Developer/Xcode/DerivedData/_Extreme_Fitness-cdfxpafcwvsczkfjvlwznradvmhm/Build/Intermediates/\ Extreme\ Fitness.build/Debug-iphonesimulator/\ Extreme\ FitnessTests.build/Objects-normal/x86_64/\ Extreme\ FitnessTests.LinkFileList -bundle_loader /Users/willrock/Library/Developer/Xcode/DerivedData/_Extreme_Fitness-cdfxpafcwvsczkfjvlwznradvmhm/Build/Products/Debug-iphonesimulator/extreme_fitness.app/extreme_fitness -Xlinker -objc_abi_version -Xlinker 2 -framework XCTest -fobjc-arc -fobjc-link-runtime -Xlinker -no_implicit_dylibs -mios-simulator-version-min=7.1 -framework XCTest -framework UIKit -framework Foundation -Xlinker -dependency_info -Xlinker /Users/willrock/Library/Developer/Xcode/DerivedData/_Extreme_Fitness-cdfxpafcwvsczkfjvlwznradvmhm/Build/Intermediates/\ Extreme\ Fitness.build/Debug-iphonesimulator/\ Extreme\ FitnessTests.build/Objects-normal/x86_64/\ Extreme\ FitnessTests_dependency_info.dat -o /Users/willrock/Library/Developer/Xcode/DerivedData/_Extreme_Fitness-cdfxpafcwvsczkfjvlwznradvmhm/Build/Products/Debug-iphonesimulator/\ Extreme\ FitnessTests.xctest/\ Extreme\ FitnessTests </code> l<code>d: file not found: /Users/willrock/Library/Developer/Xcode/DerivedData/_Extreme_Fitness-cdfxpafcwvsczkfjvlwznradvmhm/Build/Products/Debug-iphonesimulator/extreme_fitness.app/extreme_fitness clang: error: linker command failed with exit code 1 (use -v to see invocation)</code> if i load project see in xctest <code>clang: error: no such file or directory: '/Users/willrock/Desktop/ExtremeFitness/extreme_fitness/extreme_fitness-Prefix.pch' clang: error: no input files Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1</code> but in xcode 5 is work fine
Make new file: cmd+N iOS/Mac > Other > PCH File > YourProject-Prefix.pch. Make sure you display "All" and not "Basic" (Blue buttons). Project > Build Settings > Search: "Prefix Header". Under "Apple LLVM 7.0", you will get the Prefix Header key. Type file directory, e.g: "$(SRCROOT)/$(PROJECT_NAME)/ProjectName-Prefix.pch". Clean project: cmd+shift+K. Build project: cmd+B.
Python 3: Does http.server support ipv6? <sep> Does <code>http.server</code> (<code>http</code> being a Python 3.x module) support ipv6? For instance, using this command-line code (which starts a webserver): <code>python -m http.server [port] </code>
Starting with Python 3.8, `python -m http.server` supports IPv6 (see documentation and bug report with implementation history). To listen on all available interfaces: `python -m http.server --bind ::`. Python 3.8 was released on 2019-10-14.
How to use $elemMatch on aggregate's projection? <sep> This is my object: <code>{ "_id" : ObjectId("53fdcb6796cb9b9aa86f05b9"), "list" : [ "a", "b" ], "complist" : [ { "a" : "a", "b" : "b" }, { "a" : "c", "b" : "d" } ] } </code> And this is what I want to accomplish: check if "list" contains a certain element and get only the field "a" from the objects on "complist" while reading the document regardless of any of these values. I'm building a forum system, this is the query that will return the details of a forum. I need to read the forum information while knowing if the user is in the forum's white list. With a find I can use the query <code>db.itens.find({},{list:{$elemMatch:{$in:["a"]}}}) </code> to get only the first element that matches a certain value. This way I can just check if the returned array is not empty and I know if "list" contains the value I'm looking for. I can't do it on the query because I want the document regardless of it containing the value I'm looking for in the "list" value. I need the document AND know if "list" has a certain value. With an aggregate I can use the query <code>db.itens.aggregate({$project:{"complist.a":1}}) </code> to read only the field "a" of the objects contained in complist. This is going to get the forum's threads basic information, I don't want all the information of the threads, just a couple of things. But when I try to use the query <code>db.itens.aggregate({$project:{"complist.b":1,list:{$elemMatch:{$in:["a"]}}}}) </code> to try and do both, it throws me an error saying the operator $elemMatch is not valid. Am I doing something wrong here with the $elemMatch in aggregate? Is there a better way to accomplish this?
Quite an old question, but literally none of the proposed answers are good. TLDR: You can't use `$elemMatch` in a `$project` stage, but you can achieve the same result using other aggregation operators like `$filter`. ```javascript db.itens.aggregate([ { $project: { compList: { $filter: { input: "$complist", as: "item", cond: { $eq: ["$$item.a", 1] } } } } ]) ``` And if you want just the first item from the array that matches the condition, similarly to what `$elemMatch` does, you can incorporate `$arrayElemAt`. **In-Depth Explanation:** First, let's understand `$elemMatch`: `$elemMatch` is a query operator, while there's also a projection version of it, this refers to a query projection and not a `$project` aggregation stage. So, what? What does this have to do with anything? Well, a `$project` stage has a specific input structure: ``` <field>: <expression> ``` What is a valid expression? ``` Expressions can include field paths, literals, system variables, expression objects, and expression operators. Expressions can be nested. ``` So, we want to use an expression operator, but as you can see from the docs, `$elemMatch` is not part of it. Hence, it's not a valid expression to be used in an aggregation `$project` stage.
Displaying time in AM/PM format with Angular grid <sep> How would I format an Angular grid that is receiving entities that have a date time property called startTime and endTime to show time in an AM/PM format? Right now I am using: <code>{ field: 'StartTime', displayName: 'Start Time', cellFilter: 'date:\'hh:mm tt\''}, { field: 'EndTime', displayName: 'End Time', cellFilter: 'date:\'hh:mm tt\''}, </code> and obviously the 'tt' is showing instead of AM or PM. Has anyone done AM/PM in an Angular ngGrid before?
It is simple, see this: ``` { field: 'createdOn', displayName: 'Created On', width: '180px', cellTemplate: "<div class='ngCellText'>{{row.entity.createdOn | date:'MM/dd/yy h:mm:ss a'}}</div>" } ``` That's it. For more detail about the date format, see this.
Missing integer variation - O(n) solution needed <sep> The problem comes from Codility programming training and it sounds as follows: we have an array (A[]) with n (ranging from 1 to 100,000) elements and these are our parameters. The elements of the array are integers from 2,147,483,648 to 2,147,483,647, and we need to find smallest positive integer that is NOT in the array. Of course this could be done easily in O(n*log n) by sorting them all and going through the sorted array, looking for the missing posiitve number (this last operation has O(n) worst time complexity in my solution). But according to Codility, this ENTIRE problem can be done in O(n), and I cannot see any way to do that. Could someone give some tips to let me get un-stuck? PS Here is a link to detailed description of the problem which I'm not allowed to copy - https://codility.com/c/intro/demo35UEXH-EAT
```java public static int solution(final int[] A) { Arrays.sort(A); int min = 1; // Starting from 1 (min), compare all elements, if it does not match // that would the missing number. for (int i : A) { if (i == min) { min++; } } return min; } ```
Inspect Javascript Hover in Chrome Developer Tools <sep> I have some Javascript which displays an element on hover. I want to style this element and therefore need to trigger the hover state in the browser using Chrome Dev Tools. This is easy to do with CSS where you can set the state of an element within Dev Tools. What is the best way to do this with Javascript? Code Example: <code>$('#menu').hover( function() { console.log('test'); $('#dropdown').show(); }, function() { $('#dropdown').hide(); } ); </code>
Another alternative would be to hover over the element with your mouse and press F8 (this will only work in Chrome) to pause script execution. The hover state will remain visible to you.
How to check what is the latest version of a dependency to use in gradle <sep> I've always added dependencies like this: <code>dependencies { compile 'com.android.support:mediarouter-v7:19.+' } </code> but in the recent versions of Android Studio, they recommend not to use the <code>+</code> as it can lead to errors. How to know what's the latest version? I can try every combination of 19.y.x until gradle complains, but what's the real way do check? edit: sometimes, that page helps me figure it out.
There may be other ways, but here is what I use: You can find the latest version using Android Studio by replacing the version number of your library in the `build.gradle` compile line with just `+`, and click on `Sync Now` in the upper-right corner of the window. In your case, for example, `dependencies { compile 'com.android.support:mediarouter-v7:+' }`, Android Studio will pop up a hint/bulb, which has options `Replace with specific version` you can click. This will fill in the latest version in place of `+`. Please see the screenshot below. If this doesn't work the first time, let Gradle complete its sync, and retry (replace `+` with `+` or any file modification will do, click `Sync Now` again, and the hint bulb will show up). For example, for your library, I simply pasted this line `compile 'com.android.support:mediarouter-v7:+'` under my dependencies and followed the above process. Android Studio filled in with the version below.
Bootstrap 3 Table inside a panel overflowing <sep> <code> <div class="col-xs-6 col-sm-4"> <div class="panel panel-primary"> <div class="panel-heading">Recently Filtered</div> <table class="table table-striped"> <tr><td>Sensor ID</td><td>Temperature</td><td>Voltage</td><td>Date</td> <tr><td>Sensor ID</td><td>Temperature</td><td>Voltage</td><td>Date</td> <tr><td>Sensor ID</td><td>Temperature</td><td>Voltage</td><td>Date</td> <tr><td>Sensor ID</td><td>Temperature</td><td>Voltage</td><td>Date</td> </table> </div> </div> </code> The table inside a panel is overflowing when I zoom in, here's a picture example What's the proper mark up accommodating this problem? I know that it can scale properly for sure.
You could always add the `.table-responsive` class to the table to get it to scroll horizontally. Example: `<div class="table-responsive"> <table class="table table-striped"> ... </table> </div>`. If that isn't what you're wanting, you'll need to lower the font size to make it fit better.
django rest framework queryset doesn't order <sep> i use model with <code>Meta</code> <code>ordering = ['-published_date']</code> Now in view: <code>class InvoiceViewSet(viewsets.ModelViewSet): queryset = Invoice.objects.all() serializer_class = InvoiceSerializer filter_fields = ('table',) </code> And serializer: <code>class InvoiceSerializer(serializers.ModelSerializer): items = ItemSerializer(many=True, allow_add_remove=True) class Meta: model = Invoice fields = ('id', 'items', 'table', 'published_date') </code> But this ordering doesn't work, it shows me ordering ASC, and i need DESC, it doesn't affect order at all. What am i doing wrong?
```python from django_filters import DjangoFilterBackend from rest_framework import viewsets, filters class InvoiceViewSet(viewsets.ModelViewSet): queryset = Invoice.objects.all() serializer_class = InvoiceSerializer filter_backends = (DjangoFilterBackend, filters.OrderingFilter) ordering_fields = ('items', 'table', 'published_date') ordering = ('-published_date') ```
How do you extract a few random rows from a data.table on the fly <sep> I have a large data.table (about 24000 rows and growing). I want to subset that datatable based on a couple of criteria and from that subset (ends up being about 3000 rows) I want to randomly sample just 4 rows. I do not want to create a named 3000 or so row data.table, count its rows and then sample based on row number. How can I do it on the fly? Or should I just suck it up by creating the table and then working on it, sampling it and then using <code>rm()</code> to get rid of it? Lets simulate my issue <code>require(data.table) random.length <- sample(x = 15:30, size = 1) data.table(city=sample(c("Cape Town", "New York", "Pittsburgh", "Tel Aviv", "Amsterdam"), size=random.length, replace = TRUE), score = sample(x=1:10, size = random.length, replace=TRUE)) </code> That makes a random length table, which simulates the fact that depending on my criteria and depending on my starting table, I do not know what the length of the subsetted table with be Now, if I just wanted the first three rows I could do as so <code>data.table(city=sample(c("Cape Town", "New York", "Pittsburgh", "Tel Aviv", "Amsterdam"), size=random.length, replace = TRUE), score = sample(x=1:10, size = random.length, replace=TRUE))[1:3] </code> But let us say I did not want the first three rows but rather a random 3 rows, then I would want to do something such as this... <code>data.table(city=sample(c("Cape Town", "New York", "Pittsburgh", "Tel Aviv", "Amsterdam"), size=random.length, replace = TRUE), score = sample(x=1:10, size = random.length, replace=TRUE))[sample(x= 1:number of rows of that previous data.table,size = 3 ] </code> That will not work. How do I compute, on the fly, what the length of the initial data.frame was?
Have just made <code>.N</code> work in <code>i</code>. New README item: <blockquote> <code>.N</code> is now available in <code>i</code>, FR#724. Thanks to newbie indirectly here and Farrel directly here. </blockquote> This now works: <code>DT[...][...][sample(.N,3)] </code> e.g. > random.length <- sample(x = 15:30, size = 1) > data.table(city = sample(c("Cape Town", "New York", "Pittsburgh", "Tel Aviv", "Amsterdam"),size=random.length, replace = TRUE), score = sample(x=1:10, size = random.length, replace=TRUE))[sample(.N, 3)] > city score > 1: New York 4 > 2: Pittsburgh 3 > 3: Cape Town 9 >
Check if Local Notifications are enabled in IOS 8 <sep> I've looked all over the internet for how to create local notifications with IOS 8. I found many articles, but none explained how to determine if the user has set "alerts" on or off. Could someone please help me!!! I would prefer to use Objective C over Swift.
To expand on Albert's answer, you are not required to use `rawValue` in Swift. Because `UIUserNotificationType` conforms to `OptionSetType`, it is possible to do the following: `if let settings = UIApplication.shared.currentUserNotificationSettings { if settings.types.contains([.alert, .sound]) { // Have alert and sound permissions } else if settings.types.contains(.alert) { // Have alert permission } }` You use the bracket `[]` syntax to combine option types (similar to the bitwise-or `|` operator for combining option flags in other languages).
Why does adding 'dynamic' fix my bad access issues? <sep> I'm having a strange issue that appeared with iOS 8 Beta 5 (this issue did not occur with previous versions). I tried to create an empty project and try to replicate the issue, but I'm unable to do so, so I'm not quite sure where the issue lies. What I'm seeing is that attempting to access methods of a custom <code>NSManagedObject</code> subclass results in a strange EXC_BAD_ACCESS error. For example: <code> var titleWithComma: String { return "\(self.title)," } </code> This method, out of many others, causes this issue when called. However, adding a <code>dynamic</code> keyword before it makes the issue go away: <code> dynamic var titleWithComma: String { return "\(self.title)," } </code> I know I'm not giving enough info, because I honestly don't know how to pinpoint the actual issue, but can anyone explain what is possibly happening, and why adding <code>dynamic</code> might resolve this issue?
From Swift Language Reference (Language Reference > Declarations > Declaration Modifier) > Apply this modifier to any member of a class that can be represented by Objective-C. When you mark a member declaration with the `dynamic` modifier, access to that member is always dynamically dispatched using the Objective-C runtime. Access to that member is never inlined or devirtualized by the compiler. Because declarations marked with the `dynamic` modifier are dispatched using the Objective-C runtime, they're implicitly marked with the `objc` attribute. It means that your property/method can be accessed by Objective-C code or classes. This normally happens when you're subclassing a Swift class from an Objective-C base class.
Performance of subprocess.check_output vs subprocess.call <sep> I've been using <code>subprocess.check_output()</code> for some time to capture output from subprocesses, but ran into some performance problems under certain circumstances. I'm running this on a RHEL6 machine. The calling Python environment is linux-compiled and 64-bit. The subprocess I'm executing is a shell script which eventually fires off a Windows python.exe process via Wine (why this foolishness is required is another story). As input to the shell script, I'm piping in a small bit of Python code that gets passed off to python.exe. While the system is under moderate/heavy load (40 to 70% CPU utilization), I've noticed that using <code>subprocess.check_output(cmd, shell=True)</code> can result in a significant delay (up to ~45 seconds) after the subprocess has finished execution before the check_output command returns. Looking at output from <code>ps -efH</code> during this time shows the called subprocess as <code>sh <defunct></code>, until it finally returns with a normal zero exit status. Conversely, using <code>subprocess.call(cmd, shell=True)</code> to run the same command under the same moderate/heavy load will cause the subprocess to return immediately with no delay, all output printed to STDOUT/STDERR (rather than returned from the function call). Why is there such a significant delay only when <code>check_output()</code> is redirecting the STDOUT/STDERR output into its return value, and not when the <code>call()</code> simply prints it back to the parent's STDOUT/STDERR?
Reading the docs, both `subprocess.call` and `subprocess.check_output` are use-cases of `subprocess.Popen`. One minor difference is that `check_output` will raise a Python error if the subprocess returns a non-zero exit status. The greater difference is emphasized in the bit about `check_output` (my emphasis): > The full function signature is largely the same as that of the `Popen` constructor, except that `stdout` is not permitted as it is used internally. All other supplied arguments are passed directly through to the `Popen` constructor. So how is `stdout` "used internally"? Let's compare `call` and `check_output`: *call* ```python def call(*popenargs, **kwargs): return Popen(*popenargs, **kwargs).wait() ``` *check_output* ```python def check_output(*popenargs, **kwargs): if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') process = Popen(stdout=PIPE, *popenargs, **kwargs) output, unused_err = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] raise CalledProcessError(retcode, cmd, output=output) return output ``` Now we have to look at `Popen.communicate` as well. Doing this, we notice that for one pipe, `communicate` does several things which simply take more time than simply returning `Popen().wait()`, as `call` does. For one thing, `communicate` processes `stdout=PIPE` whether you set `shell=True` or not. Clearly, `call` does not. It just lets your shell spout whatever... making it a security risk, as Python describes here. Secondly, in the case of `check_output(cmd, shell=True)` (just one pipe)... whatever your subprocess sends to `stdout` is processed by a thread in the `_communicate` method. And `Popen` must join the thread (wait on it) before additionally waiting on the subprocess itself to terminate! Plus, more trivially, it processes `stdout` as a `list` which must then be joined into a string. In short, even with minimal arguments, `check_output` spends a lot more time in Python processes than `call` does.
Kill Child Process if Parent is killed in Python <sep> I'm spawning 5 different processes from a python script, like this: <code>p = multiprocessing.Process(target=some_method,args=(arg,)) p.start() </code> My problem is, when, somehow the parent process (the main script) gets killed, the child processes keeps on running. Is there a way to kill child processes, which are spawned like this, when the parent gets killed ? EDIT: I'm trying this: <code>p = multiprocessing.Process(target=client.start,args=(self.query_interval,)) p.start() atexit.register(p.terminate) </code> But this doesnt seem to be working
I've encountered the same problem myself. I've got the following solution: before calling `p.start()`, you may set `p.daemon = True`. Then, as mentioned here (python.org multiprocessing): > When a process exits, it attempts to terminate all of its daemonic child processes.
Using emacs (and magit?) to visit a file in given commit/branch/etc <sep> If I want to see how <code>foo.bar</code> looked like in some certain commit <code><COMMIT_ID></code> then I can invoke: <code>git show <COMMIT_ID>:foo.bar </code> Nice... How can I do it in <code>emacs</code>? Using <code>magit</code>? Using <code>vc</code>? Say I am visiting the file <code>foo.bar</code> and I want to look up how it looked in <code><COMMIT_ID></code>.
The canonical way to do that in Emacs is to use VC: `C-x v ~` from the file's buffer will ask you for a revision and then show that file as it was at that revision. It should work for any version control system supported by VC, such as Git, Bazaar, ...
How to deploy to github with file pattern on travis? <sep> I have created a simple travis configuration which packages an app and tries to deploy the archive file to github. The problem is, I would like to have the version number part of the file name, so i require to use a pattern for the filename. I simply can't get it to work. Configuration is currently: <code>deploy: provider: releases file: "build/distributions/worktrail-app-hub-sync*.zip" on: repo: worktrail/worktrail-app-hub-sync tags: true all_branches: true </code> But it fails with: "/home/travis/.rvm/gems/ruby-1.9.3-p547/gems/octokit-3.3.1/lib/octokit/client/releases.rb:86:in `initialize': No such file or directory - build/distributions/worktrail-app-hub-sync*.zip (Errno::ENOENT)" - but the file is certainly there: build/distributions/worktrail-app-hub-sync-0.0.1.zip Example run: https://travis-ci.org/worktrail/worktrail-app-hub-sync/builds/35704111 travis.yml: https://github.com/worktrail/worktrail-app-hub-sync/blob/0.0.1/.travis.yml Is this supported by travis deployment, or is there any workaround for this use case?
Wildcards are supported now if you enable the `file_glob` option. This is how I deploy a build `.deb` file to GitHub releases: ```yaml before_deploy: - export RELEASE_PKG_FILE=$(ls *.deb) - echo "deploying $RELEASE_PKG_FILE to GitHub releases" deploy: provider: releases api_key: secure: YOUR_ENCRYPTED_API_KEY file_glob: true file: "${RELEASE_PKG_FILE}" on: tags: true ``` Setting up is easy by executing `travis setup releases` with a dummy filename and modifying `.travis.yml` afterwards.
UITableView Refresh without scrolling <sep> I have a <code>_TableView</code> with items , and I want to set automatic refresh,and I don't want it to scroll on refresh , lets say user scrolled 2 pages down , and the refresh trigered -> so I want to put the refreshed content to the top of the table without interupting user's scrolling Assume user was on row 18 and now the <code>_dataSource</code> is refreshed so it fetched lets say 4 items , so I want user to stay on the item he was. What would be the best approach to achieve it ??
For Swift 3+: You need to save the current offset of the `UITableView`, then reload it, and then set the offset back on the `UITableView`. I have created this function for this purpose: ```swift func reload(tableView: UITableView) { let contentOffset = tableView.contentOffset tableView.reloadData() tableView.layoutIfNeeded() tableView.setContentOffset(contentOffset, animated: false) } ``` Simply call it with: `reload(tableView: self.tableView)`
Android: Why does getDimension and getDimensionPixelSize both return the same? <sep> I find the methods getDimension and getDimensionPixelSize confusing. It would look to me as though getDimension would return the actual value stored in the dimension, for example 10dp and getDimensionPixelSize would return it converted to px. But both seem to do the same thing...
`getDimension()` returns a floating-point number which is the dimension value adjusted with current display metrics; `getDimensionPixelSize()` returns an integer. It is the same as `getDimension()` rounded to an `int`, with any non-zero dimension ensured to be at least one pixel in size. For integer dimension values, they both return the same numeric value.
Misunderstanding of python os.path.abspath <sep> I have following code: <code>directory = r'D:\images' for file in os.listdir(directory): print(os.path.abspath(file)) </code> and I want next output: D:\images\img1.jpg D:\images\img2.jpg and so on But I get different result: D:\code\img1.jpg D:\code\img2.jpg where D:\code is my current working directory and this result is the same as <code>os.path.normpath(os.path.join(os.getcwd(), file)) </code> So, the question is: What is the purpose of os.path.abspath while I must use <code>os.path.normpath(os.path.join(directory, file)) </code> to get REAL absolute path of my file? Show real use-cases if possible.
The problem is with your understanding of `os.listdir()`, not `os.path.abspath()`. `os.listdir()` returns the names of each file in the directory. This will give you: `img1.jpg img2.jpg ...`. When you pass these to `os.path.abspath()`, they are seen as relative paths. This means they are relative to the directory from where you are executing your code. This is why you get "D:\code\img1.jpg". Instead, what you want to do is join the file names with the directory path you are listing: `os.path.abspath(os.path.join(directory, file))`.
What do these numbers mean in socket.io payload? <sep> When I am using native websocket API I can see just a payload in my chrome console for sockts: But when I use socket.io with their emit event, I can see some strange numbers before my actual payload. I do understand that colors mean that you either send or received the data, but what does the numbers like <code>42, 3, 2, 430, 420, 5</code> mean. Is there a place I can get a full list of these numbers with descriptions? The code which generates it is kind of big, so I just post small snippets. Client side always look like this: <code>socket.emit('joinC', room, function(color){ ... });</code> Server side looks like this: <code>io.sockets.in(room).emit('moveS', {...});</code>
I know you asked a while ago, but the information remains relevant for those who are researching. I did an analysis with reverse engineering in version 2.3.0 (socket.io) and 3.4.2 (engine.io) and got the following: The first number represents the type of communication for engine.io, using the enumerator: * Key: Value * 0: "open" * 1: "close" * 2: "ping" * 3: "pong" * 4: "message" * 5: "upgrade" * 6: "noop" The second number represents the type of action for socket.io, using the enumerator: * Key: Value * 0: "CONNECT" * 1: "DISCONNECT" * 2: "EVENT" * 3: "ACK" * 4: "ERROR" * 5: "BINARY_EVENT" * 6: "BINARY_ACK" There is other optional information that can be passed on, such as namespace and ID, but I will not go into that part. After these codes, it expects a JSON array where index 0 is the name of the event and index 1 is the argument. So the instruction `42["moveS",{"from":"g1", "to", "f3"}]` is a message for engine.io (4), is an event for socket.io (2), which will emit the "moveS" action passing JSON `{"from": "g1", "to": "f3"}` as a parameter (Actually `JSON.parse({"from": "g1", "to": "f3"})`). Hope this helps. =D
How to use SASS with Netbeans 8.0.1 <sep> I'm trying to use SASS in Netbeans 8.0.1. I have Ruby and SASS set up correctly based upon the feedback from ruby -v. I have a web application set up with css and scss folders under Project\Web Pages\resources. My input and output are set to /scss and /css respectively and I have checked 'Compile Sass File on Save'. I have created a styles.scss file and added some SASS/CSS. When I save the styles.scss file, is it supposed to generate a styles.css? Nothing happens when I save or compile the project. Has anyone run into any similar problems or have suggestions on how to debug this problem? Thanks in advance!
Installing SASS on Windows 10, Ruby 2.2.3, NetBeans 8 **Download SASS for Windows - RubyInstaller.org** **Install Ruby:** * Search Windows for CMD (Command Prompt) and start it. * Access Ruby's `bin` folder using `cd \Ruby\bin` (Hit Enter). * Install sass using the command `gem install sass` (Hit Enter to install). * Wait for the installation to finish. **In NetBeans:** * Open Options > Tools > Miscellaneous (HTML/JS in v8.1+). * CSS Preprocessors tab. * Enter the path to the installed `sass.bat` (`C:\Ruby\bin\sass.bat`) and click Install Sass. * Confirm your changes with Apply / OK. **Create a Project:** * Use an existing one or Create a New Project (HTML5, PHP, whatever...). * After the project is created, open the Projects window. * Right-click your project and choose > Properties. * From the Project Properties popup, select CSS Preprocessors. * Select Compile SASS Files on Save. * (If you want the compiler to automatically minimize your .css result file, use `--style compressed` under the Compiler Options) **Folder Structure:** * You can see from the image above that the compiler uses two default Input (watchable)/Output (compiled destination) folders. * Create the `scss` folder (and optionally the `css` folder) in your project as well. **Automatic Compilation:** * You're done! As soon as you create a new .scss file or save it, NetBeans will automatically compile the file to .css in the `/css` folder.
How to do "Deep Copy" in Swift? <sep> In Objective-C, one can deep-copy by following: <code> Foo *foo = [[Foo alloc] init]; Foo *foo2 = foo.copy; </code> How to do this deep-copy in Swift?
Deep Copy Your example is not a deep copy as discussed on Stack Overflow. Getting a true deep copy of an object would often require `NSKeyedArchiver` in Swift. The `NSCopying` protocol is the Objective-C way of providing object copies because everything was a pointer, and you needed a way of managing the generation of copies of arbitrary objects. For an arbitrary object copy in Swift, you might provide a convenience initializer where you initialize `MyObject` with another `MyObject` and in the `init` assign the values from the old object to the new object. Honestly, that is basically what `-copy` does in Objective-C except that it usually has to call `copy` on each of the sub-objects since Objective-C practices defensive copying. ```swift let object = MyObject() let object2 = MyObject(object) ``` Almost everything is pass-by-value. Almost. However, in Swift, almost everything is pass-by-value (you should really click the aforementioned link), so the need for `NSCopying` is greatly diminished. Try this out in a Playground: ```swift var array = [Int](count: 5, repeatedValue: 0) print(unsafeAddressOf(array), terminator: "") let newArray = array print(unsafeAddressOf(newArray), terminator: "") array[3] = 3 print(array) print(newArray) ``` You can see that the assignment is not a copy of the pointer but actually a new array. For a truly well-written discussion of the issues surrounding Swift's non-copy-by-value semantics with relation to structs and classes, I suggest the fabulous blog of Mike Ash. Finally, if you want to hear everything you need to know from Apple, you can watch the WWDC 2015 Value Semantics video. Everyone should watch this video; it really clears up the way memory is handled within Swift and how it differs from Objective-C.
MinGW c++ compiler zlib1.dll missing error? <sep> I have just started to learn C++ for school, and I'm trying to download the compiler MinGW to compile my source code. However, every time I try to compile a program an error message shows up saying that <code>zlib1.dll</code> is missing. This is the error message <blockquote> the program can't start because zlib1.dll is missing from your computer </blockquote> I have tried installing/re-installing with no luck. I don't know what's the problem here? Can anyone please help me with this problem as I have some homework that I need to do but I can't without the compiler. Thanks.
I had this same problem, but fixed it like this: I ran the `MinGW Installation Manager` (e.g., `C:\MinGW\libexec\mingw-get\guimain.exe`). I navigated to `All Packages -> MinGW -> MinGW Libraries`. I checked the boxes next to `mingw32-libz` (dev & dll). I went to `Installation -> Apply Changes`. Now everything works properly.
kvm: module verification failed: signature and/or required key missing - tainting kernel <sep> I'm using <code>Ubuntu 14.04 LTS</code> and kernel version <code>3.13.11.4</code>. I'm trying to load patched KVM modules <code>kvm</code> and <code>kvm-intel</code> and I'm getting the following errors <blockquote> <code>kvm: module verification failed: signature and/or required key missing - tainting kernel</code> and <code>kvm: module has bad taint, not creating trace events</code>. </blockquote> The source used is the same source that created the image that I am currently running. I've check the symbols and made sure to the error isn't cause by not including <code>EXPORT_SYMBOL_GPL()</code> in the patched files where I exported functions. <blockquote> I've also seen some stuff about different kernel versions causing this error but I built the kernel that I'm booted in with the same source that I used to create the patched kvm modules. Everything compile without an warning. Any help is appreciated! </blockquote>
Instead of re-configuring the kernel, this error (<code>module verification failed</code>) could be resolved by just adding one line `CONFIG_MODULE_SIG=n` to the top of the `Makefile` for the module itself: ``` CONFIG_MODULE_SIG=n # If KERNELRELEASE is defined, we've been invoked from the # kernel build system and can use its language. ifneq ($(KERNELRELEASE),) obj-m := hello.o # Otherwise we were called directly from the command # line; invoke the kernel build system. else KERNELDIR ?= /lib/modules/$(shell uname -r)/build PWD := $(shell pwd) default: $(MAKE) -C $(KERNELDIR) M=$(PWD) modules endif ```
SonarQube - analyzing branches of the same project <sep> I know that there is no "new project" button on SonarQube UI. However, I have two branches of the same project that I want to do analysis on. The thing is that since the project names are the same, SonarQube will upload the analysis results of the two branches into the same project on SonarQube Server. How do I configure SonarQube so that one branch will upload analysis results to one project and the other branch will upload results to another project on SonarQube server?
You might want to look at this part of the Sonar documentation, specifically at the `sonar.branch` parameter. It seems to be designed for what you want to do, and is working that way for us.
Animating UIScrollView contentInset causes jump stutter <sep> I implemeted a custom refresh control (my own class, not a subclass), and for some reason since moving to iOS 8, setting the contentInset of the scroll view (specifically, UICollectionView) to start the refresh animation causes a weird jump/stutter. Here is my code: <code>- (void)containingScrollViewDidScroll:(UIScrollView *)scrollView { CGFloat scrollPosition = scrollView.contentOffset.y + scrollView.contentInset.top; if( scrollPosition > 0 || self.isRefreshing ) { return; } CGFloat percentWidth = fabs( scrollPosition ) / self.frame.size.height / 2; CGRect maskFrame = self.maskLayer.frame; maskFrame.size.width = self.imageLayer.frame.size.width * percentWidth; [CATransaction begin]; [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; self.maskLayer.frame = maskFrame; [CATransaction commit]; } - (void)containingScrollViewDidEndDragging:(UIScrollView *)scrollView { if( ( self.maskLayer.frame.size.width >= self.imageLayer.frame.size.width ) && !self.isRefreshing ) { self.isRefreshing = YES; [self setLoadingScrollViewInsets:scrollView]; [self startAnimation]; [self sendActionsForControlEvents:UIControlEventValueChanged]; } } - (void)setLoadingScrollViewInsets:(UIScrollView *)scrollView { UIEdgeInsets loadingInset = scrollView.contentInset; loadingInset.top += self.frame.size.height; UIViewAnimationOptions options = UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionBeginFromCurrentState; [UIView animateWithDuration:0.2 delay:0 options:options animations:^ { scrollView.contentInset = loadingInset; } completion:nil]; } </code> Basically once the user releases to refresh, I animate the contentInset to the height of the refresh control. I figure the animation would reduce stuttering/jumpiness, which it did in iOS 7. But in iOS 8, when the scrollView is released from dragging, instead of just animating to the contentInset, the scroll view content jumps down from the point of release really quickly, and then animates up smoothly. I'm not sure if this is a bug in iOS 8 or what. I've also tried adding: <code>scrollView.contentOffset = CGPointZero; </code> in the animation block, which didn't change anything. Does anyone have any ideas? Any help would be highly appreciated. Thanks!
``` - (void)setLoadingScrollViewInsets:(UIScrollView *)scrollView { UIEdgeInsets loadingInset = scrollView.contentInset; loadingInset.top += self.view.frame.size.height; CGPoint contentOffset = scrollView.contentOffset; [UIView animateWithDuration:0.2 animations:^ { scrollView.contentInset = loadingInset; scrollView.contentOffset = contentOffset; }]; } ```
How do I change intellij idea to compile with scala 2.11? <sep> I am using Intellij Idea 13.1.4. I have a scala sbt project. It is currently being compiled with Scala 2.10. I would like to change this to Scala 2.11. In my build.sbt, I have: <code>libraryDependencies ++= Seq( "org.scala-lang" % "scala-compiler" % "2.11.0", ... ) </code> When I build my project, it still builds as a Scala 2.10 project. Also, under my <code>Project Settings->Modules->Scala->Facet 'Scala'->Compiler library</code>, Intellij still shows <code>scala-compiler-bundle:2.10.2</code>. There is no option for a <code>2.11.x</code> bundle. How would I get an option for Scala 2.11.x? Thanks!
In IntelliJ 2016.x, upgrade Scala by ensuring the Scala Plugin is up to date. Then, go to: <blockquote> File | Other Settings | Default Project Structure | Global Libraries </blockquote> Click the `+` button at the top left side of the window. Select `Scala SDK` and choose the version you want to install.