question stringlengths 11 28.2k | answer stringlengths 26 27.7k | tag stringclasses 130
values | question_id int64 935 78.4M | score int64 10 5.49k |
|---|---|---|---|---|
Is there anyway to simulate the [NSString stringWithFormat:@"%p", myVar], from Objective-C, in the new Swift language?
For example:
let str = "A String"
println(" str value \(str) has address: ?")
| Note: This is for reference types.
Swift 4/5:
print(Unmanaged.passUnretained(someVar).toOpaque())
Prints the memory address of someVar.
(thanks to @Ying)
Swift 3.1:
print(Unmanaged<AnyObject>.passUnretained(someVar as AnyObject).toOpaque())
Prints the memory address of someVar.
| Swift | 24,058,906 | 254 |
I can't seem to get the top most UIViewController without access to a UINavigationController. Here is what I have so far:
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(vc, animated: true, completion: nil)
However, it does not seem to do anything. The keyWindow and rootViewContr... | presentViewController shows a view controller. It doesn't return a view controller. If you're not using a UINavigationController, you're probably looking for presentedViewController and you'll need to start at the root and iterate down through the presented views.
if var topController = UIApplication.sharedApplication(... | Swift | 26,667,009 | 253 |
How can I extend Swift's Array<T> or T[] type with custom functional utils?
Browsing around Swift's API docs shows that Array methods are an extension of the T[], e.g:
extension T[] : ArrayType {
//...
init()
var count: Int { get }
var capacity: Int { get }
var isEmpty: Bool { get }
func co... | For extending typed arrays with classes, the below works for me (Swift 2.2). For example, sorting a typed array:
class HighScoreEntry {
let score:Int
}
extension Array where Element == HighScoreEntry {
func sort() -> [HighScoreEntry] {
return sort { $0.score < $1.score }
}
}
Trying to do this with a... | Swift | 24,027,116 | 253 |
I have two classes, Shape and Square
class Shape {
var numberOfSides = 0
var name: String
init(name:String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
class Square: Shape {
var sideLength: Double
init(side... | Quote from The Swift Programming Language, which answers your question:
“Swift’s compiler performs four helpful safety-checks to make sure
that two-phase initialization is completed without error:”
Safety check 1 “A designated initializer must ensure that all of the
“properties introduced by its class are initiali... | Swift | 24,021,093 | 253 |
How to generate a date time stamp, using the format standards for ISO 8601 and RFC 3339?
The goal is a string that looks like this:
"2015-01-01T00:00:00.000Z"
Format:
year, month, day, as "XXXX-XX-XX"
the letter "T" as a separator
hour, minute, seconds, milliseconds, as "XX:XX:XX.XXX".
the letter "Z" as a zone design... | Swift 5.5 • iOS 15 • Xcode 13 or later
extension Date.ISO8601FormatStyle {
static let iso8601withFractionalSeconds: Self = .init(includingFractionalSeconds: true)
}
extension ParseStrategy where Self == Date.ISO8601FormatStyle {
static var iso8601withFractionalSeconds: Date.ISO8601FormatStyle { .iso8601withFr... | Swift | 28,016,578 | 252 |
Is there an Swift equivalent of NSLocalizedString(...)?
In Objective-C, we usually use:
NSString *string = NSLocalizedString(@"key", @"comment");
How can I achieve the same in Swift? I found a function:
func NSLocalizedString(
key: String,
tableName: String? = default,
bundle: NSBundle = default,
value... | I use the following solution:
Create extension:
extension String {
var localized: String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
}
}
In Localizable.strings file:
"Hi" = "Вітаю";
Example of use:
myLabel.text = "Hi".localized
For case with comm... | Swift | 25,081,757 | 248 |
I need to create a String with format which can convert Int, Int64, Double, etc types into String. Using Objective-C, I can do it by:
NSString *str = [NSString stringWithFormat:@"%d , %f, %ld, %@", INT_VALUE, FLOAT_VALUE, DOUBLE_VALUE, STRING_VALUE];
How to do same but in Swift?
| I think this could help you:
import Foundation
let timeNow = time(nil)
let aStr = String(format: "%@%x", "timeNow in hex: ", timeNow)
print(aStr)
Example result:
timeNow in hex: 5cdc9c8d
| Swift | 24,074,479 | 247 |
I have a Swift framework that defines a struct:
public struct CollectionTO {
var index: Order
var title: String
var description: String
}
However, I can't seem to use the implicit memberwise initialiser from another project that imports the library. The error is:
'CollectionTO' cannot be initialised becau... | Quoting the manual:
"Default Memberwise Initializers for Structure Types
The default memberwise initializer for a structure type is considered private if any of the structure’s stored properties are private. Otherwise, the initializer has an access level of internal.
As with the default initializer above, if you wan... | Swift | 26,224,693 | 245 |
I'm trying to pick up a bit of Swift lang and I'm wondering how to convert the following Objective-C into Swift:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
UITouch *touch = [touches anyObject];
if ([touch.view isKindOfClass: UIPickerVie... | The proper Swift operator is is:
if touch.view is UIPickerView {
// touch.view is of type UIPickerView
}
Of course, if you also need to assign the view to a new constant, then the if let ... as? ... syntax is your boy, as Kevin mentioned. But if you don't need the value and only need to check the type, then you s... | Swift | 24,019,707 | 245 |
I am trying to dismiss a ViewController in swift by calling dismissViewController in an IBAction
@IBAction func cancel(sender: AnyObject) {
self.dismissViewControllerAnimated(false, completion: nil)
println("cancel")
}
@IBAction func done(sender: AnyObject) {
self.dismissViewControllerAnimated(false, com... | From you image it seems like you presented the ViewController using push
The dismissViewControllerAnimated is used to close ViewControllers that presented using modal
Swift 2
navigationController.popViewControllerAnimated(true)
Swift 4
navigationController?.popViewController(animated: true)
dismiss(animated: true, co... | Swift | 24,668,818 | 244 |
I am having a issue with Xcode where the error "Source Kit Service Terminated" is popping up and all syntax highlighting and code completion is gone in Swift. How can I fix this?
Here is an example image:
| The answer to mine (Xcode6-Beta7) was simply to delete the Derived Data folder.
Preferences > Locations > Derived Data > click the arrow to open in Finder > trash it.
There's obviously many reasons why this crash can occur.
| Swift | 24,006,206 | 242 |
In iOS 7 my UIButton titles are animating in and out at the wrong time - late. This problem does not appear on iOS 6. I'm just using:
[self setTitle:text forState:UIControlStateNormal];
I would prefer this happens instantly and without a blank frame. This blink is especially distracting and draws attention away from o... | Use the performWithoutAnimation: method and then force layout to happen immediately instead of later on.
[UIView performWithoutAnimation:^{
[self.myButton setTitle:text forState:UIControlStateNormal];
[self.myButton layoutIfNeeded];
}];
| Swift | 18,946,490 | 242 |
When I use the for loop in Playground, everything worked fine, until I changed the first parameter of for loop to be the highest value. (iterated in descending order)
Is this a bug? Did any one else have it?
for index in 510..509
{
var a = 10
}
The counter that displays the number of iterations that will be execut... | Xcode 6 beta 4 added two functions to iterate on ranges with a step other than one:
stride(from: to: by:), which is used with exclusive ranges and stride(from: through: by:), which is used with inclusive ranges.
To iterate on a range in reverse order, they can be used as below:
for index in stride(from: 5, to: 1, by: -... | Swift | 24,508,592 | 241 |
How to save a string into the NSUserDefaults?
| NSString *valueToSave = @"someValue";
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"preferenceName"];
[[NSUserDefaults standardUserDefaults] synchronize];
to get it back later
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:@"preferenceName"];
| Swift | 3,074,483 | 241 |
enum PostType: Decodable {
init(from decoder: Decoder) throws {
// What do i put here?
}
case Image
enum CodingKeys: String, CodingKey {
case image
}
}
What do i put to complete this?
Also, lets say i changed the case to this:
case image(value: Int)
How do I make this conform to... | It's pretty easy, just use String or Int raw values which are implicitly assigned.
enum PostType: Int, Codable {
case image, blob
}
image is encoded to 0 and blob to 1
Or
enum PostType: String, Codable {
case image, blob
}
image is encoded to "image" and blob to "blob"
This is a simple example how to use it:... | Swift | 44,580,719 | 240 |
How do you create a date object from a date in swift xcode.
eg in javascript you would do:
var day = new Date('2014-05-20');
| Swift has its own Date type. No need to use NSDate.
Creating a Date and Time in Swift
In Swift, dates and times are stored in a 64-bit floating point number measuring the number of seconds since the reference date of January 1, 2001 at 00:00:00 UTC. This is expressed in the Date structure. The following would give you ... | Swift | 24,089,999 | 240 |
I'm trying to run a HTTP Request in Swift, to POST 2 parameters to a URL.
Example:
Link: www.thisismylink.com/postName.php
Params:
id = 13
name = Jack
What is the simplest way to do that?
I don't even want to read the response. I just want to send that to perform changes on my database through a PHP file.
| The key is that you want to:
set the httpMethod to POST;
optionally, set the Content-Type header, to specify how the request body was encoded, in case server might accept different types of requests;
optionally, set the Accept header, to request how the response body should be encoded, in case the server might generat... | Swift | 26,364,914 | 237 |
I've got the following function which compiled cleanly previously but generates a warning with Xcode 8.
func exitViewController()
{
navigationController?.popViewController(animated: true)
}
"Expression of type "UIViewController?" is unused".
Why is it saying this and is there a way to remove it?
The code execute... | TL;DR
popViewController(animated:) returns UIViewController?, and the compiler is giving that warning since you aren't capturing the value. The solution is to assign it to an underscore:
_ = navigationController?.popViewController(animated: true)
Swift 3 Change
Before Swift 3, all methods had a "discardable result" b... | Swift | 37,843,049 | 236 |
I'd like to store an array of weak references in Swift. The array itself should not be a weak reference - its elements should be. I think Cocoa NSPointerArray offers a non-typesafe version of this.
| Create a generic wrapper as:
class Weak<T: AnyObject> {
weak var value : T?
init (value: T) {
self.value = value
}
}
Add instances of this class to your array.
class Stuff {}
var weakly : [Weak<Stuff>] = [Weak(value: Stuff()), Weak(value: Stuff())]
When defining Weak you can use either struct or class.
Also... | Swift | 24,127,587 | 235 |
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent;
}
Using the above code in any ViewController to set the statusBar color to White for a specific viewcontroller doesnt work in iOS8 for me. Any suggestions? Using the UIApplication.sharedApplication method, the color c... | After reading all the suggestions, and trying out a few things, I could get this to work for specific viewcontrollers using the following steps :
First Step:
Open your info.plist and insert a new key named "View controller-based status bar appearance" to NO
Second Step (Just an explanation, no need to implement this):
... | Swift | 26,956,728 | 234 |
I'm trying to apply a gradient as the background color of a View (main view of a storyboard). The code runs, but nothing changes. I'm using xCode Beta 2 and Swift.
Here's the code:
class Colors {
let colorTop = UIColor(red: 192.0/255.0, green: 38.0/255.0, blue: 42.0/255.0, alpha: 1.0)
let colorBottom = UIColor(red:... | Xcode 11 • Swift 5.1
You can design your own Gradient View as follow:
@IBDesignable
public class Gradient: UIView {
@IBInspectable var startColor: UIColor = .black { didSet { updateColors() }}
@IBInspectable var endColor: UIColor = .white { didSet { updateColors() }}
@IBInspectable var startLocation:... | Swift | 24,380,535 | 234 |
I want to extract substrings from a string that match a regex pattern.
So I'm looking for something like this:
func matchesForRegexInText(regex: String!, text: String!) -> [String] {
???
}
So this is what I have:
func matchesForRegexInText(regex: String!, text: String!) -> [String] {
var regex = NSRegularExpr... | Even if the matchesInString() method takes a String as the first argument,
it works internally with NSString, and the range parameter must be given
using the NSString length and not as the Swift string length. Otherwise it will
fail for "extended grapheme clusters" such as "flags".
As of Swift 4 (Xcode 9), the Swift s... | Swift | 27,880,650 | 233 |
I'm using Swift for programing with iOS and I'm using this code to move the UITextField, but it does not work. I call the function keyboardWillShow correctly, but the textfield doesn't move. I'm using autolayout.
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(... | There are a couple of improvements to be made on the existing answers.
Firstly the UIKeyboardWillChangeFrameNotification is probably the best notification as it handles changes that aren't just show/hide but changes due to keyboard changes (language, using 3rd party keyboards etc.) and rotations too (but note comment b... | Swift | 25,693,130 | 233 |
Here it says, "Note: the _ means “I don’t care about that value”", but coming from JavaScript, I don't understand what that means.
The only way I can get these functions to print was by using the underscores before the parameters:
func divmod(_ a: Int, _ b:Int) -> (Int, Int) {
return (a / b, a % b)
}
print(divmod(... | There are a few nuances to different use cases, but generally an underscore means "ignore this".
When declaring a new function, an underscore tells Swift that the parameter should have no label when called — that's the case you're seeing. A fuller function declaration looks like this:
func myFunc(label name: Int) // c... | Swift | 39,627,106 | 231 |
If I have an enumeration with raw Integer values:
enum City: Int {
case Melbourne = 1, Chelyabinsk, Bursa
}
let city = City.Melbourne
How can I convert a city value to a string Melbourne? Is this kind of a type name introspection available in the language?
Something like (this code will not work):
println("Your cit... | As of Xcode 7 beta 5 (Swift version 2) you can now print type names and enum cases by default using print(_:), or convert to String using String's init(_:) initializer or string interpolation syntax. So for your example:
enum City: Int {
case Melbourne = 1, Chelyabinsk, Bursa
}
let city = City.Melbourne
print(city... | Swift | 24,113,126 | 231 |
How can I convert this string "2016-04-14T10:44:00+0000" into an NSDate and keep only the year, month, day, hour?
The T in the middle of it really throws off what I am used to when working with dates.
|
Convert the ISO8601 string to date
let isoDate = "2016-04-14T10:44:00+0000"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from:isoDate)!
Get t... | Swift | 36,861,732 | 230 |
I'm trying to assign an UIImageView to an action when the user taps it.
I know how to create an action for a UIButton, but how could I mimic the same behavior of a UIButton, but using a UIImageView?
| You'll need a UITapGestureRecognizer.
To set up use this:
override func viewDidLoad()
{
super.viewDidLoad()
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tap... | Swift | 27,880,607 | 230 |
I want to test the equality of two Swift enum values. For example:
enum SimpleToken {
case Name(String)
case Number(Int)
}
let t1 = SimpleToken.Number(123)
let t2 = SimpleToken.Number(123)
XCTAssert(t1 == t2)
However, the compiler won't compile the equality expression:
error: could not find an overload for '=... | Swift 4.1+
As @jedwidz has helpfully pointed out, from Swift 4.1 (due to SE-0185, Swift also supports synthesizing Equatable and Hashable for enums with associated values.
So if you're on Swift 4.1 or newer, the following will automatically synthesize the necessary methods such that XCTAssert(t1 == t2) works. The key i... | Swift | 24,339,807 | 230 |
I have a navigation bar with a title.
When I double click the text to rename it, it actually says it's a navigation item, so it might be that.
I'm trying to change the text using code, like:
declare navigation bar as navagationbar here
button stuff {
navigationbar.text = "title"
}
That's not my code obviously, jus... | You change the title by changing the title of the view controller being displayed:
viewController.title = "some title"
Normally this is done in view did load on the view controller:
override func viewDidLoad() {
super.viewDidLoad()
self.title = "some title"
}
However, this only works if you have your view con... | Swift | 25,167,458 | 229 |
How can I get a device's unique ID in Swift?
I need an ID to use in the database and as the API-key for my web service in my social app. Something to keep track of this devices daily use and limit its queries to the database.
| You can use this (Swift 3):
UIDevice.current.identifierForVendor!.uuidString
For older versions:
UIDevice.currentDevice().identifierForVendor
or if you want a string:
UIDevice.currentDevice().identifierForVendor!.UUIDString
There is no longer a way to uniquely identify a device after the user uninstalled the app(s)... | Swift | 25,925,481 | 228 |
I want to convert a Float to an Int in Swift. Basic casting like this does not work because these types are not primitives, unlike floats and ints in Objective-C
var float: Float = 2.2
var integer: Int = float as Float
But this produces the following error message:
'Float' is not convertible to 'Int'
Any idea how to... | You can convert Float to Int in Swift like this:
var myIntValue:Int = Int(myFloatValue)
println "My value is \(myIntValue)"
You can also achieve this result with @paulm's comment:
var myIntValue = Int(myFloatValue)
| Swift | 24,029,917 | 228 |
I have an array and I want to iterate through it initialize views based on array value, and want to perform action based on array item index
When I iterate through objects
ForEach(array, id: \.self) { item in
CustomView(item: item)
.tapAction {
self.doSomething(index) // Can't get index, so this won't work
... | Another approach is to use:
enumerated()
ForEach(Array(array.enumerated()), id: \.offset) { index, element in
// ...
}
Source: https://alejandromp.com/blog/swiftui-enumerated/
| Swift | 57,244,713 | 224 |
I need a way to remove the first character from a string which is a space. I am looking for a method or even an extension for the String type that I can use to cut out a character of a string.
| To remove leading and trailing whitespaces:
let trimmedString = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
Swift 3 / Swift 4:
let trimmedString = string.trimmingCharacters(in: .whitespaces)
| Swift | 28,570,973 | 224 |
I'm looking for a simple method to remove at once all subviews from a superview instead of removing them one by one.
//I'm trying something like this, but is not working
let theSubviews : Array = container_view.subviews
for (view : NSView) in theSubviews {
view.removeFromSuperview(container_view)
}
What I am missi... | EDIT: (thanks Jeremiah / Rollo)
By far the best way to do this in Swift for iOS is:
view.subviews.forEach({ $0.removeFromSuperview() }) // this gets things done
view.subviews.map({ $0.removeFromSuperview() }) // this returns modified array
^^ These features are fun!
let funTimes = ["Awesome","Crazy","WTF"]
extension S... | Swift | 24,312,760 | 224 |
With this simple class I am getting the compiler warning
Attempting to modify/access x within its own setter/getter
and when I use it like this:
var p: point = Point()
p.x = 12
I get an EXC_BAD_ACCESS. How can I do this without explicit backing ivars?
class Point {
var x: Int {
set {
x = ne... | Setters and Getters apply to computed properties; such properties do not have storage in the instance - the value from the getter is meant to be computed from other instance properties. In your case, there is no x to be assigned.
Explicitly: "How can I do this without explicit backing ivars". You can't - you'll need ... | Swift | 24,025,340 | 224 |
How can I determine the number of cases in a Swift enum?
(I would like to avoid manually enumerating through all the values, or using the old "enum_count trick" if possible.)
| As of Swift 4.2 (Xcode 10) you can declare
conformance to the CaseIterable protocol, this works for all
enumerations without associated values:
enum Stuff: CaseIterable {
case first
case second
case third
case forth
}
The number of cases is now simply obtained with
print(Stuff.allCases.count) // 4
Fo... | Swift | 27,094,878 | 223 |
I am new to SwiftUI (like most people) and trying to figure out how to remove some whitespace above a List that I embedded in a NavigationView.
In this image, you can see that there is some white space above the List.
What I want to accomplish is this:
I've tried using:
.navigationBarHidden(true)
but this did not ma... | For some reason, SwiftUI requires that you also set .navigationBarTitle for .navigationBarHidden to work properly.
NavigationView {
FileBrowserView(jsonFromCall: URLRetrieve(URLtoFetch: applicationDelegate.apiURL))
.navigationBarTitle("")
.navigationBarHidden(true)
}
Update
As @Peacemoon pointed o... | Swift | 57,517,803 | 222 |
It's time to admit defeat...
In Objective-C, I could use something like:
NSString* str = @"abcdefghi";
[str rangeOfString:@"c"].location; // 2
In Swift, I see something similar:
var str = "abcdefghi"
str.rangeOfString("c").startIndex
...but that just gives me a String.Index, which I can use to subscript back into... | You are not the only one who couldn't find the solution.
String doesn't implement RandomAccessIndexType. Probably because they enable characters with different byte lengths. That's why we have to use string.characters.count (count or countElements in Swift 1.x) to get the number of characters. That also applies to posi... | Swift | 24,029,163 | 222 |
I'm reading the documentation and I am constantly shaking my head at some of the design decisions of the language. But the thing that really got me puzzled is how arrays are handled.
I rushed to the playground and tried these out. You can try them too. So the first example:
var a = [1, 2, 3]
var b = a
a[1] = 42
a
b
... | Note that array semantics and syntax was changed in Xcode beta 3 version (blog post), so the question no longer applies. The following answer applied to beta 2:
It's for performance reasons. Basically, they try to avoid copying arrays as long as they can (and claim "C-like performance"). To quote the language book:
F... | Swift | 24,081,009 | 221 |
Is there a counterpart in Swift to flatten in Scala, Xtend, Groovy, Ruby and co?
var aofa = [[1,2,3],[4],[5,6,7,8,9]]
aofa.flatten() // shall deliver [1,2,3,4,5,6,7,8,9]
of course i could use reduce for that but that kinda sucks
var flattened = aofa.reduce(Int[]()){
a,i in var b : Int[] = a
b.extend(i)
re... | Swift >= 3.0
reduce:
let numbers = [[1,2,3],[4],[5,6,7,8,9]]
let reduced = numbers.reduce([], +)
flatMap:
let numbers = [[1,2,3],[4],[5,6,7,8,9]]
let flattened = numbers.flatMap { $0 }
joined:
let numbers = [[1,2,3],[4],[5,6,7,8,9]]
let joined = Array(numbers.joined())
| Swift | 24,465,281 | 220 |
What is the purpose of writing comments in Swift as:
// MARK: This is a comment
When you can also do:
// This is a comment
What does the // MARK achieve?
| The // MARK: and // MARK: - syntax in Swift functions identically to the #pragma mark and #pragma mark - syntax in Objective-C.
When using this syntax (plus // TODO: and // FIXME:), you can get some extra information to show up in the quick jump bar.
Consider these few lines of source code:
// MARK: A mark comment li... | Swift | 35,963,128 | 219 |
I am trying to implement a feature in an App that shows an alert when the internet connection is not available.
The alert has two actions (OK and Settings), whenever a user clicks on settings, I want to take them to the phone settings programmatically.
I am using Swift and Xcode.
| Using UIApplication.openSettingsURLString
Update for Swift 5.1
override func viewDidAppear(_ animated: Bool) {
let alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
... | Swift | 28,152,526 | 219 |
Problem: NSAttributedString takes an NSRange while I'm using a Swift String that uses Range
let text = "Long paragraph saying something goes here!"
let textRange = text.startIndex..<text.endIndex
let attributedString = NSMutableAttributedString(string: text)
text.enumerateSubstringsInRange(textRange, options: NSString... | Swift String ranges and NSString ranges are not "compatible".
For example, an emoji like 😄 counts as one Swift character, but as two NSString
characters (a so-called UTF-16 surrogate pair).
Therefore your suggested solution will produce unexpected results if the string
contains such characters. Example:
let text = "😄... | Swift | 27,040,924 | 219 |
I am playing around with Apple's new Swift programming language and have some problems...
Currently I'm trying to read a plist file, in Objective-C I would do the following to get the content as a NSDictionary:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"];
NSDictionary *dict = ... | You can still use NSDictionaries in Swift:
For Swift 4
var nsDictionary: NSDictionary?
if let path = Bundle.main.path(forResource: "Config", ofType: "plist") {
nsDictionary = NSDictionary(contentsOfFile: path)
}
For Swift 3+
if let path = Bundle.main.path(forResource: "Config", ofType: "plist"),
let myDict =... | Swift | 24,045,570 | 219 |
I'd like to remove the status bar at the top of the screen.
This does not work:
func application
(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: NSDictionary?)
-> Bool
{
application.statusBarHidden = true
return true
}
I've also tried:
func application
(application: UIApplicat... | You really should implement prefersStatusBarHidden on your view controller(s):
Swift 3 and later
override var prefersStatusBarHidden: Bool {
return true
}
| Swift | 24,236,912 | 217 |
For a long time, when it comes to the microservice architecture, NATS and Kafka are the first options that come to my mind. But recently I found this gRPC template in dotnet core and that grasped my attention. I read a lot about it and watched a lot of videos but I don't think any of those could address gRPC correctly ... | I often see people misplacing these technologies by one crucial aspect: public authentication.
For instance, check this graph:
This is a benchmark of Inverted Json (https://github.com/lega911/ijson), comparing some tools, such as iJson, RabbitMQ, Nats, 0MQ, etc.
Notice that Nats, ZeroMQ and iJson are not meant to be u... | gRPC | 63,418,503 | 12 |
After downloading BloomRPC from the github repo and running brew cask install bloomrpc, when I try to open the BloomRPC application I get "BloomRPC cannot be opened because the developer cannot be verified." I've tried going to Security and Privacy -> Developer Tools -> and enabling BloomRPC under "Allow the apps below... | You can try to build BloomRPC from source (as they mentioned in their repo) Or you can simply bypass this error go navigate to SystemPreference -> Security&Privacy.
Under General tab, you will see a statement about BloomRPC, click on Open Anyway to suppress the warning and continue to use.
| gRPC | 63,160,778 | 12 |
Is it possible to have a client channel that automatically reconnects?
I tried using wait_for_ready(true) on the context, but that doesn't seem to have any effect.
I get this crash when I try to use a client channel with a lost connection:
E0519 12:56:40.239405883 9379 client_context.cc:119] assertion failed: c... | My problem was attempting to re-use a context. Creating a new context for each attempt fixed the issue.
| gRPC | 61,889,726 | 12 |
I'm trying to work out whether I could use one of the (A/E/N)LBs to load balance gRPC traffic. A simple round robin would suffice in our case.
I've read that ALB doesn't fully support HTTP2 and therefore can't be used with gRPC. Specifically lack of support of sending HTTP2 traffic downstream and lack of support for tr... | As of October 29, 2020, Application Load Balancers now support HTTP/2 and gRPC load balancing. From the announcement:
To use the feature on your ALB, choose HTTPS as your listener protocol, gRPC as the protocol version for your target group and register instance or IP as targets for the configured target group. ALB pr... | gRPC | 60,164,162 | 12 |
I have worked with grpc .net client and a grpc server created with java, how can i implement grpc web client on angular 6 with typescript? Also how can i create proto files and it's typing's for typescript?
I am following this repo but not able to generate proto files.
| After spending sometime i was able to create proto files for typescript by following steps:
Download protobuf for windows from this link. After extracting files set the path variable for protoc.exe
install npm packages npm install google-protobuf @types/google-protobuf grpc-web-client ts-protoc-gen --save
After instal... | gRPC | 51,857,225 | 12 |
I'm attempting to add the GRPC dependency to a node elastic beanstalk application and all of my deployments are failing. Once I remove the GRPC dependency from my package.json my deployments work.
The error is
ERROR: Failed to run npm install.
> grpc@1.10.1 install /tmp/deployment/application/node_modules/grpc
> nod... | For anyone using bcrypt library in your project.
You will get this error if you are trying to deploy your code using Elastic Beanstalk .
Just remove bcrypt and start using bycryptjs
Banged my head for 2 weeks on this .
Also downgrading bcrypt to 3.0.0 won't help you with this.
| gRPC | 49,951,257 | 12 |
Is it possible to only stream to certain clients from a gRPC server?
I believe what I'm looking for is something like Pusher, where you have a channel for a client and you can publish messages that can be seen only by a client that has access to that channel.
What I'm struggling with is understanding what are the step... | As per as i understood the question. You want to send the the message to the particular client in gRPC. This is very much possible using Server side streaming or Bi-directional streaming in gRPC.
For example:
Define a server side streaming or bidi streaming api
rpc ListFeatures(Rectangle) returns (stream Feature) {}
... | gRPC | 49,230,524 | 12 |
I want know about good practices with golang and gRPC and protobuf.
I am implementing the following gRPC service
service MyService {
rpc dosomethink(model.MyModel) returns (model.Model) {
option (google.api.http) = { post: "/my/path" body: "" };
}
}
I compiled the protobufs. In fact, the protobuf give us a ... | You need to return empty model.Model object in order for protobufs to be able to properly serialise the message.
Try
import "google.golang.org/grpc/status"
func (Abcd) Dosomethink(c context.Context, sessionRequest *model.MyModel) (*model.Model, error) {
return &model.Model{}, status.Error(400,"Default error messag... | gRPC | 45,455,144 | 12 |
When we want to use distributed TensorFlow, we will create a parameter server using
tf.train.Server.join()
However, I can't find any way to shut down the server except killing the processing. The TensorFlow documentation for join() is
Blocks until the server has shut down.
This method currently blocks forever.
This i... | You can have parameter server processes die on demand by using session.run(dequeue_op) instead of server.join() and having another process enqueue something onto that queue when you want this process to die.
So for k parameter server shards you could create k queues, with unique shared_name property and try to dequeue... | gRPC | 39,810,356 | 12 |
While using Cloud Functions, we've encountered the following error:
Timestamp: 2023-10-21 18:50:18.281 EEST
Function: v8-specialist
---updateUserByID finish update---
Caused by: Error
at WriteBatch.commit (/workspace/node_modules/firebase-admin/node_modules/@google-cloud/firestore/build/src/write-batch.js:433:23)... | I had the same problem last week and it seems to be something inside firebase / grpc implementation related to long time delays between firebase calls.
Also, firebase library seems to be moving away from RPC but it still keeps it as a default option if you don't set preferRest: true (see docs)
For me it works when I ca... | gRPC | 77,337,076 | 11 |
I am trying to make an application using python and gRPC as shown in this article - link
I am able to run the app successfully on my terminal but to run with a frontend I need to run it as a flask app, codebase. And I am doing all this in a virtual environment.
when I run my flask command FLASK_APP=marketplace.py flask... | If downgrading will solve the issue for you try the following code inside your virtual environment.
pip install MarkupSafe==2.0.1
| gRPC | 71,271,759 | 11 |
I'm doing load tests between services implemented in Node.JS, both services on the same machine connected through localhost.
There are REST and gRPC client & server files. The main goal is to prove that gRPC is faster than an HTTP call because the use of HTTP/2, the use of protocol buffers that are more efficient than ... | The reason gRPC -- well, really protobufs -- doesn’t scale well in your example is that every entry of your repeated field results in protobuf needing to decode a separate field, and there is overhead related to that. You can see more details about the encoding of repeated fields in the docs here. You're using proto3, ... | gRPC | 69,889,439 | 11 |
I've tried to define a gRPC service where client can subscribe to receive broadcasted messages and they can also send them.
syntax = "proto3";
package Messenger;
service MessengerService {
rpc SubscribeForMessages(User) returns (stream Message) {}
rpc SendMessage(Message) returns (Close) {}
}
message User {
... | The problem you're experiencing is due to the fact that MessengerServer.SubscribeForMessages returns immediately. Once that method returns, the stream is closed.
You'll need an implementation similar to this to keep the stream alive:
public class MessengerService : MessengerServiceBase
{
private static readonly Con... | gRPC | 62,436,956 | 11 |
When I try to execute docker build -t exampledockeracc/testapp:v1.0.0 . I receive the following error: failed to dial gRPC: unable to upgrade to h2c, received 500, context canceled
When i search for the error people come with the solution to restart docker and waite a while before executing but it does not seem to work... | This issue is caused because you have not let the Docker enough time to load completely. Please wait for some time and try again.
Github Issue Link
One other reason is OS mismatch. The node image is Linux-based and you are on windows. I would recommend you, get a Linux server or a VM for building the containers.
| gRPC | 62,261,552 | 11 |
I'm trying to establish a connection to an insecure gRPC server. I'm using gRPC for communication between two processes inside of a Docker container, that's why I don't need any encryption or strong authentication.
The server behaves as expected and I can do calls using grpcurl like that:
grpcurl -plaintext localhost:4... | I found the fix on my own:
It works when I move the AppContext.SetSwitch above the AddGrpcClient.
// Enable support for unencrypted HTTP2
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
// Registration of the DI service
services.AddGrpcClient<DaemonService.DaemonServiceClien... | gRPC | 58,052,596 | 11 |
I am having issues building the grpc cpp helloworld example with cmake.
I built and installed grpc with cmake initially, and then with make directly.
I have found this issue raised by someone else in the past, which was closed as resolved.
It does not appear to be resolved and I opened a new issue for it, but I feel it... | The cause of this problem is explained at https://github.com/grpc/grpc/issues/13841:
Because of some limitations of our current CMakeLists.txt, the install targets (see gRPC_INSTALL option) will only be generated if you are building using a pre-installed version of our dependencies (gRPC_CARES_PROVIDER in your case ne... | gRPC | 57,413,975 | 11 |
I am relatively new to GRPC and want to be sure that I am doing connection management correctly with golang. I don't want to have to create a new connection for every call but I also don't want to create bottlenecks as I scale.
What I did was to create a single connection in the init function:
var userConn *grpc.Cli... | Yes, it's fine to have single GRPC client connection per service. Moreover, I don't see any other options here. GRPC does all the heavy lifting under the hood: for example, you don't need to write your own client connection pool (as you would do for a typical RDBMS), because it won't provide better results than a singl... | gRPC | 56,067,076 | 11 |
When working with gRPC in C#, asynchronous calls return AsyncUnaryCall<T> (for unary calls - of course, other calls have slightly different return types). However, AsyncUnaryCall<T> does not extend Task<T>. Therefore, common things you would ordinarily do with a Task<T> do not work with AsyncUnaryCall<T>. This includes... | As I said in a comment, whilst it's "Task-like", it actually represents two separate Tasks. If you want to work with the individual Tasks as Tasks, just access the appropriate property (e.g. ResponseHeadersAsync or ResponseAsync).
If you have a variable themAll of type List<AsyncUnaryCall<T>> then using WhenAll/WhenAny... | gRPC | 54,684,416 | 11 |
If the browser supports http/2, why does grpc-web require envoy proxy?
Is it just required for older browsers that do not support http/2?
| Answered in https://github.com/grpc/grpc-web/issues/347. For gRPC-Web to work, we need a lot of the underlying transport to be exposed to us but that's not the case currently cross browsers. We cannot leverage the full http2 protocol given the current set of browser APIs.
| gRPC | 53,051,648 | 11 |
The spec for google.protobuf.Empty states:
A generic empty message that you can re-use to avoid defining duplicated
empty messages in your APIs. A typical example is to use it as the request
or the response type of an API method.
I've been advocating internally to use an empty message wrapper instead, to preser... | The wire format handles this gracefully. However, most code using the gRPC stubs will break as type-safe languages will notice the incompatible types.
If you think you may ever need fields, go ahead and make a special message for that case, even if it is empty. If in doubt, do it. If you are confident you will never ne... | gRPC | 50,993,815 | 11 |
I am trying to run the Helloworld example with the client in C# and the server in Python.
When I manually start the server and then the client, the client can successfully connect to the server and call the SayHello method.
Now, I have configured my IDE (Visual Studio) to start both the client and the server at the sa... | You can use the "WaitForReady" option from the CallOptions (it's off by default) to wait for the server to become available. Using
var reply = client.SayHello(new HelloRequest { Name = user }, new CallOptions().WithWaitForReady(true));
will have the desired effect.
The option was introduced here:
https://github.com/gr... | gRPC | 45,547,278 | 11 |
I am using Java and Protoc 3.0 compiler and my proto file is mention below.
https://github.com/openconfig/public/blob/master/release/models/rpc/openconfig-rpc-api.yang
syntax = "proto3";
package Telemetry;
// Interface exported by Agent
service OpenConfigTelemetry {
// Request an inline subscription for data... | The method you used is for request metadata, not response metadata:
public void start(Listener<RespT> responseListener, Metadata headers) {
For response metadata, you will need a ClientCall.Listener and wait for the onHeaders callback:
public void onHeaders(Metadata headers)
I do feel like the usage of metadata you m... | gRPC | 43,479,217 | 11 |
I know there is an example helloworld program in gRPC source. However, being new to this, I don't understand how to write more than one async services in the server. The example here talks about spawning new instances of a class to handle SayHello service calls.
How to add new services, for example SayBye, so that I c... | See this
thread and
the relevant
example.
The suggestion is to add a bool parameter to CallData (hello_ in
this example), instantiate two CallData objects, one with hello_ =
true, and one with hello_ = false, and have each one request a
different RPC.
if (hello_) {
service_->RequestSayHello(...);
} else {
service_-... | gRPC | 41,732,884 | 11 |
I wonder what is the best practice for protocol buffer regarding source repository (e.g. git) :
Do I have to put ONLY the .proto file in the repository and let anyone else who uses the source code to regenerate classes code with protoc compiler ? or is it a best pratice to put both .proto files AND source code generate... | You should never check in generated code if you can avoid it.
If you check in generated code, you take on multiple risks, such as:
You risk losing the knowledge of how to correctly regenerate that code. If it's not automated as part of the build, it's too easy to forget to document, or to have the documentation be wro... | gRPC | 41,186,798 | 11 |
Maybe (hopefully) I'm missing something very simple, but I can't seem to figure this out.
I have a set of gRPC services that I would like to put behind a nghttpx proxy. For this I need to be able to configure my client with a channel on a non-root url. Eg.
channel = grpc.insecure_channel('localhost:50051/myapp')
stub ... | As confirmed here, this is not possible. I will route traffic via subdomains in nghttpx.
| gRPC | 40,410,392 | 11 |
Given the address of a GRPC service at, say, ipv4:127.0.0.1:25000, are there any standardized queries or tools I can use to discover what GRPC requests the service is capable of receiving?
e.g. I'm looking for something like:
./magic-grpc-service-tool 127.0.0.1:25000
> service Greeter {
> rpc Greet(HelloMessage) ret... | Update: the reflection service is supported across the various languages and grpc CLI is able to consume it.
At the moment, no. We will be adding server reflection to the various languages, but the support has to be added to each individually. Once server reflection is supported, the grpc CLI will be enhanced to use it... | gRPC | 37,534,274 | 11 |
I'm trying to use http2/grpc streaming, but my connection cuts off in 15 seconds. The documentation on the timeout setting says to set the timeout to 0. However when I do this then Envoy throws an error on startup complaining that 0 isn't a valid value for the Duration type.
How do I disable the route timeout?
Here i... | You almost got it. The only change you need to make is to go from an integer to a duration. So rather than "0", you need to specify "0s" for zero seconds.
I verified this by setting timeout: 0s in your config.yaml and everything started up.
| gRPC | 65,897,760 | 10 |
i want return list of Person model to client in grpc.project is asp.net core
person.proto code is :
syntax = "proto3";
option csharp_namespace = "GrpcService1";
service People {
rpc GetPeople (RequestModel) returns (ReplyModel);
}
message RequestModel {
}
message ReplyModel {
repeated Person person= 1;
}
... | change error line (replyModel.Person = people) to this code
replyModel.Person.AddRange(people);
| gRPC | 63,955,514 | 10 |
To compile proto files for Python, I could
protoc -I=.--python_out=$DST_DIR sommem.proto
based on https://developers.google.com/protocol-buffers/docs/pythontutorial
or
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. some.proto
based on https://grpc.io/docs/languages/python/basics/#generating-client... | protoc contains just logic for protocol buffers. That is, it will generate serialization/deserialization code for many languages. It does not, however, generate code for stubs and servers by default. This is left up to separate RPC systems through a system called protoc plugins.
Protoc plugins offer a simple interface ... | gRPC | 62,649,353 | 10 |
I have a service that transfers messages at a quite high rate.
Currently it is served by akka-tcp and it makes 3.5M messages per minute. I decided to give grpc a try.
Unfortunately it resulted in much smaller throughput: ~500k messages per minute an even less.
Could you please recommend how to optimize it?
My setup
H... | I solved the issue by creating several ManagedChannel instances per destination. Despite articles say that a ManagedChannel can spawn enough connections itself so one instance is enough it's wasn't true in my case.
Performance is in parity with akka-tcp implementation.
| gRPC | 58,764,891 | 10 |
I want to use gRPC to expose an interface for bidirectional transfer of large data sets (~100 MB) between two services. Because gRPC imposes a 4 MB message size limit by default, it appears that the preferred way to do this is to manually code streaming of chunks, and re-assemble them at the receiving end [1][2].
Howe... | The 4 MB limit is protect clients/servers who haven't thought about message size constraints. gRPC itself is fine with going much higher (100s of MBs), but most applications could be trivially attacked or accidentally go out-of-memory allowing messages of that size.
If you're willing to receive a 100 MB message all-at-... | gRPC | 58,429,357 | 10 |
If I run following these two tests I get the error.
1st test
@Rule
public GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
@Test
public void findAll() throws Exception {
// Generate a unique in-process server name.
String serverName = InProcessServerBuilder.generateName();
// Create a server, add serv... | Hey I just faced similar issue using Dialogflow V2 Java SDK where I received the error
Oct 19, 2019 4:12:23 PM io.grpc.internal.ManagedChannelOrphanWrapper$ManagedChannelReference cleanQueue
SEVERE: *~*~*~ Channel ManagedChannelImpl{logId=41, target=dialogflow.googleapis.com:443} was not shutdown properly!!! ~*~*~*
... | gRPC | 57,481,760 | 10 |
To provide better debugging information for my GRPC server/client setup, I am trying to find an API for grpc.server that allows me to inspect what clients are connected to the server.
The most promising question I have found is question, which gives a starting point on how to do this in Java GRPC. However, the Java API... | There isn't a native API for this, but you have all of the pieces you need. Here's a modified version of the helloworld example from the repo.
class PeerSet(object):
def __init__(self):
self._peers_lock = threading.RLock()
self._peers = {}
def connect(self, peer):
print("Peer {} connect... | gRPC | 57,228,886 | 10 |
Will gRPC support in Python allow me to implement a server that listens on a Unix domain socket (as opposed to a port)? I am using Python 3.5.3 and grpcio/grpcio-tools 1.18.0.
So far, I have not been able to find any relevant example nor direct evidence. The official examples use server.add_insecure_port('[::]:50051')... | Apparently add_insecure_port(address) accepts Unix domain sockets in the format unix:///var/run/test.sock after all.
More details: https://github.com/grpc/grpc/blob/master/doc/naming.md
| gRPC | 54,844,882 | 10 |
What is the difference between thread safe and thread compatible?
What thread compatible mean?
What is use cases for thread compatible?
UPD:
I have found this definition in the grpc documentation of StreamObserver.
Also, I have found the link to Characterizing thread safety but its still not clear for me.
If a metho... | Thread safe means that an object can be used by many threads concurrently and still be correct 1
Thread hostile means that the object does something (mutates static state, thread local storage etc.) that prevents it from being thread safe.
Thread compatible means not thread safe, but not thread hostile - so to satisfy ... | gRPC | 52,714,494 | 10 |
I am building a client/server system in go, using gRPC and protobuf (and with a gRPC gateway to REST).
I use metadata in the context on the server side to carry authentication data from the client, and that works perfectly well.
Now, I'd like the server to set some metadata keys/values so that the client can get them, ... | I finally found my way: https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-metadata.md
So basically, grpc.SetHeader() + grpc.SendHeader() and grpc.SetTrailer() are totally what I was looking for. On the client side, grpc.Header() and grpc.Trailer() functions need to be passed to the RPC call, and their argu... | gRPC | 47,599,509 | 10 |
Was wondering if anybody has tried to use jmeter to test gRPC application.
I was hoping that
I could write a gRPC client class with a non-blocking/asynchronous stub that makes non-blocking calls to the server,
Create a Jar of the above client
Import the Jar to JMeter
Use the Java method in Jmeter BeanShell sampler
be... |
if above workaround work?
Your solution will work. But if you need it long term, I would recommend, rather than having client class and using BeanShell sampler, implementing custom Java Sampler. It's very practical, since work-wise it will be similar/same as implementing custom client + BeanShell sampler script, but... | gRPC | 43,018,472 | 10 |
For some background, I am attempting to use grpc auth in order to provide security for some services I am defining.
Let's see if I can ask this is a way that makes sense. For my python code, it was pretty easy to implement the server side code.
class TestServiceServer(service_pb2.TestServiceServer):
def TestHello... | Use a ServerInterceptor and then propagate the identity via Context. This allows you to have a central policy for authentication.
The interceptor can retrieve the identity from Metadata headers. It should then validate the identity. The validated identity can then be communicated to the application (i.e., testHello) vi... | gRPC | 40,112,374 | 10 |
Does anyone know how to compile *.proto files for grpc application in maven?
This is how I'm compiling protobuf in maven - (old way, using installed protoc compiler, excerpt from pom.xml):
<build>
<plugins>
<!-- protocol buffers runner, requires protoc -->
<plugin>
<artifactId>maven-antrun-pl... | I'd highly recommend using protobuf-maven-plugin as described in the grpc-java README.
If you really want to do it manually, you can download protoc-gen-grpc-java from Maven Central and add another <arg> for the exec of protoc:
--plugin=protoc-gen-grpc-java=path/to/protoc-gen-grpc-java
| gRPC | 35,934,276 | 10 |
As the question says, I compiled grpc from source and also did sudo pip install grpcio, however, the which grpc_python_plugin doesn't return anything. This is a problem because the grpc python example for route_guide requires me to run protoc -I . --python_out=. --grpc_out=. --plugin=protoc-gen-grpc='which grpc_python_... | python -m grpc_tools.protoc --proto_path=. --python_out=. --grpc_python_out=. my_proto.proto
Edited:
Apparently, there is open Issue on gRPC github site regarding this problem. Protoc seems to have a compatibility issue with grpc_python_plugin? I solved this problem by installing grpc_tools, then used grpc_tools.prot... | gRPC | 34,713,861 | 10 |
I'm writing an opencv program and I found a script on another stackoverflow question: Computer Vision: Masking a human hand
When I run the scripted answer, I get the following error:
Traceback (most recent call last):
File "skinimagecontour.py", line 13, in <module>
contours, _ = cv2.findContours(skin_ycrcb, cv... | I got the answer from the OpenCV Stack Exchange site. Answer
THE ANSWER:
I bet you are using the current OpenCV's master branch: here the return statements have changed, see http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=findcontours.
Thus, change the corresponding ... | Contour | 25,504,964 | 88 |
My simple Python code is this
import cv2
img=cv2.imread('Materials/shapes.png')
blur=cv2.GaussianBlur(img,(3,3),0)
gray=cv2.cvtColor(blur,cv2.COLOR_BGR2GRAY)
returns,thresh=cv2.threshold(gray,80,255,cv2.THRESH_BINARY)
ret,contours,hierachy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for cnt in co... | the function cv2.findContours() has been changed to return only the contours and the hierarchy and not ret
you should change it to:
contours,hierachy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
| Contour | 54,164,630 | 66 |
I would like to get data from a single contour of evenly spaced 2D data (an image-like data).
Based on the example found in a similar question: How can I get the (x,y) values of the line that is ploted by a contour plot (matplotlib)?
>>> import matplotlib.pyplot as plt
>>> x = [1,2,3,4]
>>> y = [1,2,3,4]
>>> m = [[15,... | For a given path, you can get the points like this:
p = cs.collections[0].get_paths()[0]
v = p.vertices
x = v[:,0]
y = v[:,1]
| Contour | 5,666,056 | 62 |
Im trying to get the largest contour of a red book.
I've got a little problem with the code because its getting the contours of the smallest objects (blobs) instead of the largest one and I can't seem to figure out why this is happening
The code I use:
camera = cv2.VideoCapture(0)
kernel = np.ones((2,2),np.uint8)
whil... | You can start by defining a mask in the range of the red tones of the book you are looking for.
Then you can just find the contour with the biggest area and draw the rectangular shape of the book.
import numpy as np
import cv2
# load the image
image = cv2.imread("path_to_your_image.png", 1)
# red color boundaries [B,... | Contour | 44,588,279 | 57 |
I can't seem to find the answer anywhere! I found a discussion here, but trying this I get a TypeError: 'NoneType' object is not iterable:
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> x, y = np.meshgrid(np.arange(10),np.arange(10))
>>> z = x + y
>>> cs = plt.contourf(x,y,z,levels=[2,3])
>>> cs.collect... | You could also do it directly with the lines of the contour, without using proxy artists.
import matplotlib
import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
matplotlib.rcParams['xtick.direction'] = 'out'
matplotlib.rcParams['ytick.direction'] = 'out'
delta =... | Contour | 10,490,302 | 46 |
I have gone through pages and pages of contour plots in R (including many hints on stackoverflow) without success. Here is my data to contour, including adding a map of Rwanda (the data consists of 14 values of longitude, latitude and rain as x,y and z):
Lon Lat Rain
28.92 -2.47 83.4
29.02 -2.68 144
29.25 -1... | Here are some different possibilites using base R graphics and ggplot. Both simple contours plots, and plots on top of maps are generated.
Interpolation
library(akima)
fld <- with(df, interp(x = Lon, y = Lat, z = Rain))
base R plot using filled.contour
filled.contour(x = fld$x,
y = fld$y,
... | Contour | 19,339,296 | 38 |
When using matplotlib with a contour plot, I'm having trouble getting the colorbar to display as I want. I've read through numerous similar examples, but have still not been able to get what I want.
In the image below, I want two things changed. I want the minimum value and maximum values to be display on the color ... | If I understand correctly what you want, I think this should do it:
import numpy as np
import matplotlib.pyplot as plt
xi = np.array([0., 0.5, 1.0])
yi = np.array([0., 0.5, 1.0])
zi = np.array([[0., 1.0, 2.0],
[0., 1.0, 2.0],
[-0.1, 1.0, 2.0]])
v = np.linspace(-.1, 2.0, 15, endpoint=True... | Contour | 5,826,592 | 37 |
I need to use cv::FindContours() in a program and I have to know the algorithm behind that.
What algorithm does openCV use to find contours?
How does it work?
| If you read the documentation it is mentioned this function implements the algorithm of:
Suzuki, S. and Abe, K., Topological Structural Analysis of Digitized
Binary Images by Border Following. CVGIP 30 1, pp 32-46 (1985)
OpenCV is open source if you want to see how this is implemented just need to read the code:
http... | Contour | 10,427,474 | 34 |
I am working on Retinal fundus images.The image consists of a circular retina on a black background. With OpenCV, I have managed to get a contour which surrounds the whole circular Retina. What I need is to crop out the circular retina from the black background.
| It is unclear in your question whether you want to actually crop out the information that is defined within the contour or mask out the information that isn't relevant to the contour chosen. I'll explore what to do in both situations.
Masking out the information
Assuming you ran cv2.findContours on your image, you wi... | Contour | 28,759,253 | 33 |
I have a simple problem in python and matplotlib.
I have 3 lists : x, y and rho with rho[i] a density at the point x[i], y[i].
All values of x and y are between -1. and 1. but they are not in a specific order.
How to make a contour plot (like with imshow) of the density rho (interpolated at the points x, y).
Thank you ... | You need to interpolate your rho values. There's no one way to do this, and the "best" method depends entirely on the a-priori information you should be incorporating into the interpolation.
Before I go into a rant on "black-box" interpolation methods, though, a radial basis function (e.g. a "thin-plate-spline" is a p... | Contour | 9,008,370 | 33 |
I want to visualize polygonal curve(s) extracted with cv2.approxPolyDP(). Here's the image I am using:
My code attempts to isolate the main island and define and plot the contour approximation and contour hull. I have plotted the contour found in green, the approximation in red:
import numpy as np
import cv2
# load i... | The problem is in visualization only: drawContours expects array (list in case of python) of contours, not just one numpy array (which is returned from approxPolyDP).
Solution is the following: replacing
cv2.drawContours(canvas, approx, -1, (0, 0, 255), 3)
to
cv2.drawContours(canvas, [approx], -1, (0, 0, 255), 3)
| Contour | 41,879,315 | 32 |
I'm attempting to script a contour polar plot in R from interpolated point data. In other words, I have data in polar coordinates with a magnitude value I would like to plot and show interpolated values. I'd like to mass produce plots similar to the following (produced in OriginPro):
My closest attempt in R to this ... | [[major edit]]
I was finally able to add contour lines to my original attempt, but since the two sides of the original matrix that gets contorted don't actually touch, the lines don't match up between 360 and 0 degree. So I've totally rethought the problem, but leave the original post below because it was still kind of... | Contour | 10,856,882 | 31 |
I have a pet project to create images of maps, where I draw the roads and other stuff over a contour plot of the terrain elevation. It is intended to plan mountain bike routes (I have made some vectorial drawings by hand, in the past, and they work great for visualization).
Currently, I download Digital Elevation Model... | I finally found a proper solution to this long-standing problem (currently in Matplotlib 3), which does not require multiple calls to contour or rasterize the figure.
Note that the problem illustrated in the question appears only in saved publication-quality figures formats like PDF, not in lower-quality raster files l... | Contour | 8,263,769 | 31 |
In python, If I have a set of data
x, y, z
I can make a scatter with
import matplotlib.pyplot as plt
plt.scatter(x,y,c=z)
How I can get a plt.contourf(x,y,z) of the scatter ?
| You can use tricontourf as suggested in case b. of this other answer:
import matplotlib.tri as tri
import matplotlib.pyplot as plt
plt.tricontour(x, y, z, 15, linewidths=0.5, colors='k')
plt.tricontourf(x, y, z, 15)
Old reply:
Use the following function to convert to the format required by contourf:
from numpy import... | Contour | 18,764,814 | 30 |
I want to draw x=0 and y=0 axis in my contour plot, using a white color. If that is too cumbersome, I would like to have a white dot denoting where the origin is.
My contour plot looks as follows and the code to create it is given below.
xvec = linspace(-5.,5.,100)
X,Y = meshgrid(xvec, ... | There are a number of options (E.g. centered spines), but in your case, it's probably simplest to just use axhline and axvline.
E.g.
import numpy as np
import matplotlib.pyplot as plt
xvec = np.linspace(-5.,5.,100)
x,y = np.meshgrid(xvec, xvec)
z = -np.hypot(x, y) ... | Contour | 9,609,372 | 30 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.