repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
andlabs/misctestprogs
macsplitviewtest.swift
1
2210
// 3 january 2016 // scratch program 17 august 2015 import Cocoa import WebKit var keepAliveMainwin: NSWindow? = nil func appLaunched() { let mainwin = NSWindow( contentRect: NSMakeRect(0, 0, 320, 240), styleMask: (NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask), backing: NSBackingStoreType.Buffered, `defer`: true) let contentView = mainwin.contentView! let splitView = NSSplitView(frame: NSZeroRect) splitView.dividerStyle = NSSplitViewDividerStyle.Thin splitView.vertical = true splitView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(splitView) let box1 = NSScrollView(frame: NSZeroRect) let ov = NSOutlineView(frame: NSZeroRect) ov.headerView = nil ov.selectionHighlightStyle = NSTableViewSelectionHighlightStyle.SourceList box1.documentView = ov box1.translatesAutoresizingMaskIntoConstraints = false splitView.addSubview(box1) let box2 = WebView(frame: NSZeroRect) box2.translatesAutoresizingMaskIntoConstraints = false splitView.addSubview(box2) let views: [String: NSView] = [ "splitView": splitView, ] addConstraint(contentView, "H:|-[splitView]-|", views) addConstraint(contentView, "V:|-[splitView]-|", views) splitView.setPosition(50, ofDividerAtIndex: 0) mainwin.cascadeTopLeftFromPoint(NSMakePoint(20, 20)) mainwin.makeKeyAndOrderFront(mainwin) keepAliveMainwin = mainwin } func addConstraint(view: NSView, _ constraint: String, _ views: [String: NSView]) { let constraints = NSLayoutConstraint.constraintsWithVisualFormat( constraint, options: [], metrics: nil, views: views) view.addConstraints(constraints) } class appDelegate : NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(note: NSNotification) { appLaunched() } func applicationShouldTerminateAfterLastWindowClosed(app: NSApplication) -> Bool { return true } } func main() { let app = NSApplication.sharedApplication() app.setActivationPolicy(NSApplicationActivationPolicy.Regular) // NSApplication.delegate is weak; if we don't use the temporary variable, the delegate will die before it's used let delegate = appDelegate() app.delegate = delegate app.run() } main()
mit
1e93d505e06cd428fc7c686aa7683a3e
28.466667
114
0.782353
4.040219
false
false
false
false
rmulkey/RMSwiftTest
RMSwiftTest/RMSwiftTest/MainViewController.swift
1
2698
// // MainViewController.swift // RMSwiftTest // // Created by Rodrigo Mulkey on 6/4/14. // Copyright (c) 2014 Rodrigo Mulkey. All rights reserved. // import UIKit class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var tableView: UITableView! var menuItems: String[] = ["Reddit", "Twitter", "RSS", "Flickr"] var item = NSString []() var titleLabel: UILabel! init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override func viewDidLoad() { super.viewDidLoad() println("Main View Loaded") menuItems = ["Reddit", "Twitter", "RSS", "Flickr"] println(menuItems) titleLabel = UILabel(frame: CGRectMake(100, 50, 200, 50)) titleLabel.text = "Select an API" view.addSubview(self.titleLabel) tableView = UITableView(frame: CGRectMake(0, 100, self.view.bounds.width-10, self.view.bounds.height-10), style: UITableViewStyle.Plain) tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "mainMenu") tableView.delegate = self tableView.dataSource = self view.addSubview(self.tableView) } func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int{ println("Menu items count: \(self.menuItems.count)") return self.menuItems.count } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("mainMenu", forIndexPath: indexPath) as UITableViewCell cell.text = self.menuItems[indexPath.row] return cell } func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { tableView.deselectRowAtIndexPath(indexPath, animated:true) println("did select") // let nextView = self.storyboard.instantiateViewControllerWithIdentifier("SecondSwiftView") as SecondSwiftViewController // nextView.titleInteger = indexPath.row // self.navigationController.pushViewController(nextView, animated: true) let navigation :UINavigationController = UINavigationController() let redditVC: UIViewController! = UIViewController(nibName:"RedditViewController", bundle: nil) navigation.pushViewController(redditVC, animated:true) self.presentViewController(redditVC, animated:true, completion:nil) } }
mit
e8887a23c5c5d3921f79a5bdb11f3ae6
35.459459
144
0.670497
5.290196
false
false
false
false
ArtisOracle/libSwiftCal
libSwiftCal/Reminder.swift
1
11139
// // ListItem.swift // libSwiftCal // // Created by Stefan Arambasich on 9/15/14. // // Copyright (c) 2014 Stefan Arambasich. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import EventKit /** Defines a VTODO calendar component. This object describes a to-do event that is part of a VCALENDAR component. "Reminder" is interchangable with "to-do" unless specifically noted. :URL: https://tools.ietf.org/html/rfc5545#section-3.6.2 */ public class Reminder: CalendarObject { public enum Status: String { case NeedsAction = "NEEDS-ACTION" case Completed = "COMPLETED" case InProcess = "IN-PROCESS" case Canceled = "CANCELLED" } public struct AccessClass { public static let Public = "PUBLIC" public static let Private = "PRIVATE" public static let Confidential = "CONFIDENTIAL" } /// In the case of an iCalendar object that specifies a /// "METHOD" property, this property specifies the date and time that /// the instance of the iCalendar object was created. In the case of /// an iCalendar object that doesn't specify a "METHOD" property, this /// property specifies the date and time that the information /// associated with the calendar component was last revised in the /// calendar store. public var dateTimestamp: ReminderProperty! = ReminderProperty(dictionary: [SerializationKeys.PropertyKeyKey: kDTSTAMP, SerializationKeys.PropertyValKey: NSDate()]) /// Unique identifier public var uid: ReminderProperty! = ReminderProperty() { didSet { if let newId = uid.stringValue { id = newId } } } /// The access classification (or visibility) of the reminder public var accessClass: ReminderProperty! = ReminderProperty() /// The datetime the reminder was completed or nil if it isn't public var completed: ReminderProperty! = ReminderProperty() /// The datetime this object was created in the calendar store public var createdTime: ReminderProperty! = ReminderProperty(dictionary: [SerializationKeys.PropertyKeyKey: kCREATED, SerializationKeys.PropertyValKey: NSDate()]) /// A description of this reminder (longer than its summary) public var desc: ReminderProperty! = ReminderProperty(dictionary: [SerializationKeys.PropertyKeyKey: kDESCRIPTION, SerializationKeys.PropertyValKey: ""]) /// The datetime this reminder should start public var start: ReminderProperty! = ReminderProperty(dictionary: [SerializationKeys.PropertyKeyKey: kDTSTART, SerializationKeys.PropertyValKey: NSDate().dateByAddingTimeInterval(Conversions.Time.SecondsInADay)]) /// The GPS coordinate of this location public var geo: Geo! = Geo() /// The datetime this reminder was last modified public var lastModified: ReminderProperty! = ReminderProperty() /// A description of the intended venue for this reminder public var location: ReminderProperty! = ReminderProperty() /// The person who created this reminder public var organizer: Organizer! = Organizer() /// This property is used by an assignee or delegatee of a /// to-do to convey the percent completion of a to-do to the /// "Organizer". public var percentComplete: ReminderProperty! = ReminderProperty() /// Describes this reminder's relative priority as an integer public var priority: ReminderProperty! = ReminderProperty() /// used in conjunction with the "UID" and /// "SEQUENCE" properties to identify a specific instance of a /// recurring "VEVENT", "VTODO", or "VJOURNAL" calendar component. /// The property value is the original value of the "DTSTART" property /// of the recurrence instance. public var recurrenceID: ReminderProperty! = ReminderProperty() /// The current integer sequence of revisions of this item public var sequence: ReminderProperty! = ReminderProperty(dictionary: [SerializationKeys.PropertyKeyKey: kSEQUENCE, SerializationKeys.PropertyValKey: 0]) /// Overall status or progress for this reminder public var status: ReminderProperty! = ReminderProperty(dictionary: [SerializationKeys.PropertyKeyKey: kSTATUS, SerializationKeys.PropertyValKey: kNEEDS_ACTION]) /// A short summary or description of this reminder public var summary: ReminderProperty! = ReminderProperty(dictionary: [SerializationKeys.PropertyKeyKey: kSUMMARY, SerializationKeys.PropertyValKey: ""]) /// A pointer to a URL representation of this object public var URL: ReminderProperty! = ReminderProperty() /// Defines a rule or repeating pattern for /// recurring events, to-dos, journal entries, or time zone /// definitions. public var rrule: RecurrenceRule! = RecurrenceRule() /// Defines a datetime of when this reminder is due public var due: ReminderProperty! = ReminderProperty(dictionary: [SerializationKeys.PropertyKeyKey: kDUE, SerializationKeys.PropertyValKey: NSDate().dateByAddingTimeInterval(Conversions.Time.SecondsInADay)]) /// Defines a duration after the start time for which this reminder is valid public var duration: Duration! /// Items attached to this reminder public var attachments = [Attachment]() /// Attendees assigned to this reminder public var attendees = [Attendee]() /// A list of categories (strings) that describe this reminder public var categories = [ReminderProperty]() /// A list of comments (strings) about this reminder public var comments = [ReminderProperty]() /// A list of contacts (strings) attached to this reminder public var contacts = [ReminderProperty]() /// Exceptions to recurring datetimes public var exceptions = [ExceptionDate]() /// Whether the request was successful or otherwise impacted public var requestStatus = [RequestStatus]() /// Associated calendar objects public var related = [ReminderProperty]() // TODO: weak ref /// A list of resources (string) required for this reminder public var resources = [ReminderProperty]() /// A list of recurrence dates for this reminder object private var _recurrenceDates = [RecurrenceDate]() public var recurrenceDates: [RecurrenceDate] { get { return _recurrenceDates } set { _recurrenceDates = newValue } } /// Non-standard "X-" properties public var xProperties = [GenericProperty]() /// IANA-registered property names public var IANAProperties = [IANAProperty]() /// A list of alarm components associated with this reminder public var alarms = [Alarm]() // *** public override func generateUUID(format: String? = nil) { super.generateUUID(format: format) self.uid.key = kUID self.uid.stringValue = self.id } /// Returns the reminder status as a value of `Reminder.Status` public var reminderStatus: Status? { get { if let s = self.status.stringValue { let wsp = NSCharacterSet.whitespaceAndNewlineCharacterSet() if let st = Status(rawValue: self.status.stringValue!.stringByTrimmingCharactersInSet(wsp)) { return st } } return nil } set { self.status.stringValue = newValue!.rawValue } } public required init() { super.init() } // MARK: - CalendarType public override func serializeToiCal() -> String { var result = String() result += kBEGIN + kCOLON + kVTODO + kCRLF result += model__serializeiCalChildren(self) result += kEND + kCOLON + kVTODO + kCRLF return result } // MARK: - Hashable public override var hashValue: Int { get { return model__defaultHash(model: self) } } // MARK: - NSCoding public required init(coder aDecoder: NSCoder) { super.init() nscoder__initWithCoder(aDecoder, mirror: reflect(self), onObject: self) } // MARK: - Serializable public override var serializationKeys: [String] { get { return super.serializationKeys + [kDTSTAMP, kUID, kCLASS, kCOMPLETED, kCREATED, kDESCRIPTION, kDTSTART, kGEO, kLAST_MODIFIED, kLOCATION, kORGANIZER, kPERCENT_COMPLETE, kPRIORITY, kRECURRENCE_ID, kSEQUENCE, kSTATUS, kSUMMARY, kURL, kRRULE, kDUE, kDURATION, kATTACH, kATTENDEE, kCATEGORIES, kCOMMENT, kCONTACT, SerializationKeys.ExceptionDatesKey, kREQUEST_STATUS, kRELATED, kRESOURCES, SerializationKeys.RecurrenceDatesKey, SerializationKeys.XPropertiesKey, SerializationKeys.IANAPropertiesKey, SerializationKeys.AlarmsKey] } } public required init(dictionary: [String : AnyObject]) { super.init(dictionary: dictionary) if let rDateArr = dictionary[SerializationKeys.RecurrenceDatesKey] as? [[String : AnyObject]] { var inRDates = [RecurrenceDate]() for dict in rDateArr { let r = RecurrenceDate(dictionary: dict) inRDates.append(r) } self.recurrenceDates = inRDates } if let exDateArr = dictionary[SerializationKeys.ExceptionDatesKey] as? [[String : AnyObject]] { var inExDates = [ExceptionDate]() for dict in exDateArr { let r = ExceptionDate(dictionary: dict) inExDates.append(r) } self.exceptions = inExDates } } public override func toDictionary() -> [String : AnyObject] { var result = [String: AnyObject]() serializable__addToDict(&result, mirror: reflect(self), onObject: self) return result } }
mit
e4d1ddd64503cfa1754907923c0a1925
41.681992
217
0.66927
4.748082
false
false
false
false
languageininteraction/VowelSpaceTravel
mobile/Vowel Space Travel iOS/Vowel Space Travel iOS/VSTServer.swift
1
21181
// // VSTServer.swift // Vowel Space Travel iOS // // Created by Wessel Stoop on 23/04/15. // Copyright (c) 2015 Radboud University. All rights reserved. // import Foundation protocol StimuliRequest { var selectedTask : Task { get } var multipleSpeakers : Bool { get } var differentStartingSounds : Bool { get } var selectedBaseVowel : VowelDefinition? { get } var selectedTargetVowel : VowelDefinition? { get } } enum LoginResult { case Successful case UserDoesNotExist case IncorrectPassword } class VSTServer : NSObject { var url : String var availableVowels : [VowelDefinition] = [] var confidencesForVowelPairsByTargetVowelId = Dictionary<Int,[ConfidenceForVowelPair]>() var userName : String? var userID : Int? var email : String? var password : String? var genericToken : String = kWebserviceUserPassword var userLoggedInSuccesfully : Bool = false var latestResponse : NSArray? var showAlert : ((String,String,Bool) -> ())? init(url: String) { self.url = url super.init() self.loadAvailableVowels() } func createCredentialString() -> String { //Set up the credentials let loggedIn : Bool = self.userID != nil let username : String = loggedIn ? "\(self.email!)" : kWebserviceUsername let password : String = loggedIn ? "\(self.password!)" : self.genericToken print("Using credentials with un \(username) and password \(password)") let loginString = NSString(format: "%@:%@", username, password) let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)! let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) return base64LoginString } func HTTPGetToJSON(urlExtension: String, completionHandler: ((NSDictionary?, NSError?) -> Void)) { //Create the request var jsonData : NSDictionary? let cleanedUrlExtension : String = urlExtension.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) let request : NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: self.url+cleanedUrlExtension)!) request.setValue("Basic \(self.createCredentialString())", forHTTPHeaderField : "Authorization") //Do the request NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: { (response: NSURLResponse?, responseData: NSData?, error: NSError?) -> Void in if responseData == nil { self.presentConnectionErrorMessage() return } do { jsonData = try NSJSONSerialization.JSONObjectWithData(responseData!,options: NSJSONReadingOptions.MutableContainers) as? NSDictionary } catch { print(error) self.presentConnectionErrorMessage() } completionHandler(jsonData,error); }) } func HTTPPostToJSON(urlExtension: String, data : AnyObject, processResponse : Bool = true, completionHandler: ((NSDictionary?, NSError?) -> Void)) { //Create the request var jsonData : NSDictionary? let request : NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: self.url+urlExtension)!) request.setValue("Basic \(self.createCredentialString())", forHTTPHeaderField : "Authorization") //Add the POST data do { let jsonString = try NSString(data: NSJSONSerialization.dataWithJSONObject(data, options: NSJSONWritingOptions(rawValue: 0)),encoding: NSASCIIStringEncoding)! request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding,allowLossyConversion:true) request.HTTPMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") } catch { print(error) self.presentConnectionErrorMessage() } NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response: NSURLResponse?, responseData: NSData?, error: NSError?) -> Void in if !processResponse { completionHandler(jsonData,error) return } if responseData == nil { self.presentConnectionErrorMessage() return } do { jsonData = try NSJSONSerialization.JSONObjectWithData(responseData!,options: NSJSONReadingOptions.MutableContainers) as? NSDictionary } catch { print(error) self.presentConnectionErrorMessage() } completionHandler(jsonData,error); } } func createNewUser(email: String,token: String,nativeLanguage: String,allowsUseForResearch: Bool) { print("Creating new user") self.HTTPPostToJSON("players",data: ["firstName":"unknown","lastName":"unknown", "token":token, "email":email, "nativeLanguage": nativeLanguage, "canUseDataForResearch": allowsUseForResearch ],processResponse: false) { (jsonData,err) -> Void in self.HTTPGetToJSON("players/search/findByEmail?email=\(email)") { (response,err) -> Void in self.getUserIDFromResponseToSearchByEmail(response!) } } } func logIn(email : String,password : String, completionHandler: Void -> Void) { print("Trying to log in") self.email = email self.password = password self.HTTPGetToJSON("players/search/findByEmail?email=\(email)") { (jsonData,err) -> Void in print(jsonData) print(err) if err != nil { self.presentAuthenticationErrorMessage() } else if jsonData!.count == 0 { print("User not found") self.presentAuthenticationErrorMessage() } else { print("Found a user") self.getUserIDFromResponseToSearchByEmail(jsonData!) //Final check credentials print("Final credential check") self.HTTPGetToJSON("players/search/findByEmail?email=\(email)") { (jsonData,err) -> Void in print(err) if err != nil { self.presentAuthenticationErrorMessage() } else { completionHandler() } } } } } func getUserIDFromResponseToSearchByEmail(response : NSDictionary) { let embeddedData : NSDictionary = response["_embedded"] as! NSDictionary let allPlayers : NSArray = embeddedData["players"] as! NSArray let foundPlayer : NSDictionary = allPlayers[0] as! NSDictionary let linksForPlayers : NSDictionary = foundPlayer["_links"] as! NSDictionary let basicLink : NSDictionary = linksForPlayers["self"] as! NSDictionary let urlForThisPlayer : NSString = basicLink["href"] as! NSString let separatedURL : NSArray = urlForThisPlayer.componentsSeparatedByString("/") let userIDString : String = separatedURL[separatedURL.count-1] as! String self.userID = Int(userIDString) } func checkWhetherEmailIsInDatabase(email : String, completionHandler: ((Bool, NSError?) -> Void)) { self.userID = nil self.HTTPGetToJSON("players/search/findByEmail?email=\(email)") { (jsonData,err) -> Void in completionHandler(jsonData!.count != 0,err) } } func loadAvailableVowels() { var urlExtensionToGetVowels : String = "vowels?page=0&size=30" print("loading vowels") self.HTTPGetToJSON(urlExtensionToGetVowels) { (jsonData,err) -> Void in let unpackagedJsonData : NSDictionary = jsonData!["_embedded"] as! NSDictionary var idCounter : Int = 1 //Get the basic info for vowel in unpackagedJsonData["vowels"] as! NSArray { let discNotation : String = vowel["disc"] as! String let currentVowel : VowelDefinition = VowelDefinition(id: idCounter, ipaNotation: discNotation) self.availableVowels.append(currentVowel) idCounter++ } //Get the vowel qualities urlExtensionToGetVowels = "qualities?page=0&size=30" self.HTTPGetToJSON(urlExtensionToGetVowels) { (jsonData,err) -> Void in let unpackagedJsonData : NSDictionary = jsonData!["_embedded"] as! NSDictionary var counter = 0 var currentVowel : VowelDefinition for vowelQuality in unpackagedJsonData["qualities"] as! NSArray { currentVowel = self.availableVowels[counter] currentVowel.manner = VowelManner(rawValue: vowelQuality["manner"]! as! String) currentVowel.place = VowelPlace(rawValue: vowelQuality["place"]! as! String) currentVowel.rounded = vowelQuality["roundness"]! as! String == "rounded" counter++ if counter == self.availableVowels.count { break } } } } } func translateSettingsToDifficultyString(multipleSpeakers : Bool, differentStartingSounds : Bool) -> String { if !multipleSpeakers && !differentStartingSounds { return "easy" } else if multipleSpeakers && !differentStartingSounds { return "medium" } else if !multipleSpeakers && differentStartingSounds { return "hard" } else if multipleSpeakers && differentStartingSounds { return "veryhard" } return "easy" } func getStimuliForSettings(stimuliRequest : StimuliRequest, completionHandler: (([Stimulus], NSError?) -> Void)) { //Turned off until logging in is fixed //assert(self.userLoggedInSuccesfully, "You have to be logged in to do this") let difficulty : String = self.translateSettingsToDifficultyString(stimuliRequest.multipleSpeakers, differentStartingSounds: stimuliRequest.differentStartingSounds); let urlExtensionToGetSoundFileUrls : String = "stimulus/sequence/"+stimuliRequest.selectedTask.rawValue+"/"+difficulty+"/2?maxSize=\(kNumberOfStimuliInRound)&maxTargetCount=\(kMaxNumberOfTargetsInRound)&target=\(stimuliRequest.selectedBaseVowel!.id)&standard=\(stimuliRequest.selectedTargetVowel!.id)" var stimuli = [Stimulus]() self.HTTPGetToJSON(urlExtensionToGetSoundFileUrls) { (jsonData,err) -> Void in if jsonData != nil && jsonData!["_embedded"] != nil { let unpackagedJsonData : NSDictionary = jsonData!["_embedded"] as! NSDictionary for stimulus in unpackagedJsonData["stimuli"] as! NSArray { let newStimulus : Stimulus = Stimulus(sampleID: stimulus["sampleId"] as! Int,requiresResponse: stimulus["relevance"] as! String == "isTarget", relevance: stimulus["relevance"] as! String, vowelID: stimulus["vowelId"] as! Int, speakerLabel: stimulus["speakerLabel"] as! String, wordString : stimulus["wordString"] as! String) stimuli.append(newStimulus) } completionHandler(stimuli,nil); } else { //If this fails, try again until it does not print("Retry downloading the files") self.getStimuliForSettings(stimuliRequest, completionHandler: completionHandler) } } } func downloadSampleWithID(id : Int, fileSafePath : String) { print("Downloading sample \(id)") let urlExtensionToDownloadSample : String = "stimulus/audio/\(id)" let url = NSURL(string: self.url + urlExtensionToDownloadSample) let dataFromURL = NSData(contentsOfURL: url!) let fileManager = NSFileManager.defaultManager() fileManager.createFileAtPath(fileSafePath, contents: dataFromURL, attributes: nil) print("Saved at \(fileSafePath)") } func saveStimulusResults(stimuli : [Stimulus],stimuliRequestUsedToGenerateTheseStimuli : StimuliRequest,completionHandler: (NSError?) -> Void) { var postData = [Dictionary<String,AnyObject>]() for stimulus in stimuli { postData.append(stimulus.packageToDictionary()) } let difficulty : String = self.translateSettingsToDifficultyString(stimuliRequestUsedToGenerateTheseStimuli.multipleSpeakers, differentStartingSounds: stimuliRequestUsedToGenerateTheseStimuli.differentStartingSounds); self.HTTPPostToJSON("stimulus/response/"+stimuliRequestUsedToGenerateTheseStimuli.selectedTask.rawValue+"/"+difficulty+"/\(self.userID!)",data: postData,processResponse: false) { (jsonData,err) -> Void in completionHandler(err) } } func loadAllConfidenceValuesForCurrentUserID(allVowels : Dictionary<String,VowelDefinition>,completionHandler: ((Dictionary<Int,[ConfidenceForVowelPair]>,NSError?) -> Void)) { //Make sure there is at least a key for every targetID for (exampleWord, vowel) in allVowels { self.confidencesForVowelPairsByTargetVowelId[vowel.id] = [] } //Load what confidences there are on the server var playerIdToUse : Int if kShowPlanetsForExampleUser { playerIdToUse = 2 } else { playerIdToUse = self.userID! } let confidenceName : String = "score" let urlExtensionToGetConfidenceValues : String = confidenceName+"/search/findByPlayer?player=\(playerIdToUse)" print("loading confidences") self.HTTPGetToJSON(urlExtensionToGetConfidenceValues) { (jsonData,err) -> Void in if (jsonData!["_embedded"] != nil) { let embeddedData : NSDictionary = jsonData!["_embedded"] as! NSDictionary let confidences : NSArray = embeddedData[confidenceName] as! NSArray var currentConfidenceObject : ConfidenceForVowelPair for confidence in confidences { let targetVowelId : Int = confidence["targetId"] as! Int currentConfidenceObject = ConfidenceForVowelPair(raw: confidence["score"] as! Float, targetVowelId: targetVowelId, standardVowelId: confidence["standardId"] as! Int) self.confidencesForVowelPairsByTargetVowelId[targetVowelId]!.append(currentConfidenceObject) } } //Add confidences not present for (targetID, confidences) in self.confidencesForVowelPairsByTargetVowelId { for (exampleWord, vowel) in allVowels { var foundVowel : Bool = false for confidence in confidences { if confidence.standardVowelId == vowel.id { foundVowel = true break } } if !foundVowel { self.confidencesForVowelPairsByTargetVowelId[targetID]!.append(ConfidenceForVowelPair(raw: 0, targetVowelId: targetID, standardVowelId: vowel.id) ) } } } completionHandler(self.confidencesForVowelPairsByTargetVowelId,nil) } } func getSuggestionForGame(completionHandler: ((GameSuggestion) -> Void)) { let urlExtensionToGetSuggestion : String = "suggestion/tasksuggestion/\(self.userID!)" print("suggestion") self.HTTPGetToJSON(urlExtensionToGetSuggestion) { (jsonData,err) -> Void in print("data") print(err) print(jsonData!["task"]) let task : Task = Task(rawValue: jsonData!["task"] as! String)! let targetVowelInfo : NSDictionary = jsonData!["targetVowel"] as! NSDictionary let standardVowelInfo : NSDictionary let standardVowelID : String if task == Task.Discrimination { standardVowelInfo = jsonData!["standardVowel"] as! NSDictionary standardVowelID = standardVowelInfo["disc"] as! String } else { standardVowelID = "6" //Because we need something here } let targetVowelID : String = targetVowelInfo["disc"] as! String var targetVowel : VowelDefinition? var standardVowel : VowelDefinition? for vowel in self.availableVowels { print(vowel.ipaNotation) print(targetVowelID) if vowel.ipaNotation == targetVowelID { targetVowel = vowel } if vowel.ipaNotation == standardVowelID { standardVowel = vowel } } if targetVowel == standardVowel { standardVowel = self.availableVowels[0] } let difficulty : String = jsonData!["difficulty"] as! String var multipleSpeakers : Bool var differentStartingSounds : Bool switch(difficulty) { case "easy": multipleSpeakers = false; differentStartingSounds = false; break; case "medium": multipleSpeakers = true; differentStartingSounds = false; break; case "hard": multipleSpeakers = false; differentStartingSounds = true; break; case "veryhard": multipleSpeakers = true; differentStartingSounds = true; break; default : multipleSpeakers = false; differentStartingSounds = false; break; } let gameSuggestion = GameSuggestion(targetVowel: targetVowel!, standardVowel: standardVowel!, task: task, multipleSpeakers: multipleSpeakers, differentStartingSounds:differentStartingSounds) completionHandler(gameSuggestion) } } func presentAuthenticationErrorMessage() { self.showAlert!("Incorrect credentials","It looks like either your email or password is not in our database. Please try again.",false) } func presentConnectionErrorMessage() { self.showAlert!("Problem connecting to the server","An internet connection is required for this app.",true) } } class ConfidenceForVowelPair { var raw : Float var inverted : Float var targetVowelId : Int var standardVowelId : Int var mixingWeigth : Float? init(raw : Float, targetVowelId : Int, standardVowelId : Int) { self.raw = raw self.inverted = 1 - raw self.targetVowelId = targetVowelId self.standardVowelId = standardVowelId } }
gpl-2.0
9c47cb4733c51ff8fe6268f57f14e09d
36.031469
309
0.561069
5.346037
false
false
false
false
e155707/remote
AfuRo/AfuRo/Tutorial/TutorialController.swift
1
3155
// // TutorialController.swift // AfuRo // // Created by e155707 on 2017/11/27. // Copyright © 2017年 Ryukyu. All rights reserved. // import UIKit import SceneKit class TutorialController: UIPageViewController { override func viewDidLoad() { super.viewDidLoad() self.setViewControllers([getFirst()], direction: .forward, animated: true, completion: nil) self.dataSource = self } func getFirst() -> FirstTutorialController { let storyboard: UIStoryboard = UIStoryboard(name:"FirstTutorial",bundle: nil) return storyboard.instantiateViewController(withIdentifier: "FirstTutorialController") as! FirstTutorialController } func getSecond() -> SecondTutorialController { let storyboard: UIStoryboard = UIStoryboard(name:"SecondTutorial",bundle: nil) return storyboard.instantiateViewController(withIdentifier: "SecondTutorialController") as! SecondTutorialController } func getThird() -> ThreeTutorialController { let storyboard: UIStoryboard = UIStoryboard(name:"ThreeTutorial",bundle: nil) return storyboard.instantiateViewController(withIdentifier: "ThreeTutorialController") as! ThreeTutorialController } func getFourth() -> FourTutorialController { let storyboard: UIStoryboard = UIStoryboard(name:"FourTutorial",bundle: nil) return storyboard.instantiateViewController(withIdentifier: "FourTutorialController") as! FourTutorialController } func getMain() -> MainController{ let storyboard: UIStoryboard = UIStoryboard(name:"Main",bundle: nil) return storyboard.instantiateViewController(withIdentifier: "Main") as! MainController } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension TutorialController : UIPageViewControllerDataSource { func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { if viewController.isKind(of:FourTutorialController.self) { return getThird() } else if viewController.isKind(of:ThreeTutorialController.self) { return getSecond() } else if viewController.isKind(of:SecondTutorialController.self) { return getFirst() } else if viewController.isKind(of:MainController.self) { return nil } else { return nil } } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { if viewController.isKind(of:FirstTutorialController.self) { return getSecond() } else if viewController.isKind(of:SecondTutorialController.self) { return getThird() } else if viewController.isKind(of:ThreeTutorialController.self) { return getFourth() } else if viewController.isKind(of:MainController.self) { return nil } else { return nil } } }
mit
516f7530a3dfa357952b0f9ea997da46
35.651163
149
0.686548
5.52014
false
false
false
false
Bouke/HAP
Sources/HAP/Base/Predefined/Characteristics/Characteristic.SecuritySystemCurrentState.swift
1
2229
import Foundation public extension AnyCharacteristic { static func securitySystemCurrentState( _ value: Enums.SecuritySystemCurrentState = .disarm, permissions: [CharacteristicPermission] = [.read, .events], description: String? = "Security System Current State", format: CharacteristicFormat? = .uint8, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = 4, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> AnyCharacteristic { AnyCharacteristic( PredefinedCharacteristic.securitySystemCurrentState( value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) as Characteristic) } } public extension PredefinedCharacteristic { static func securitySystemCurrentState( _ value: Enums.SecuritySystemCurrentState = .disarm, permissions: [CharacteristicPermission] = [.read, .events], description: String? = "Security System Current State", format: CharacteristicFormat? = .uint8, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = 4, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> GenericCharacteristic<Enums.SecuritySystemCurrentState> { GenericCharacteristic<Enums.SecuritySystemCurrentState>( type: .securitySystemCurrentState, value: value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) } }
mit
e499d629124df12c473d06efbca3ca3c
35.540984
67
0.608345
5.410194
false
false
false
false
SVKorosteleva/heartRateMonitor
HeartMonitor/HeartMonitor/SettingsStorageManager.swift
1
2004
// // SettingsStorageManager.swift // HeartMonitor // // Created by Светлана Коростелёва on 8/10/17. // Copyright © 2017 home. All rights reserved. // import CoreData enum SettingsKey: String { case age case restingHeartRate case fatBurnMinHeartRate case fatBurnMaxHeartRate } typealias SettingsValue = UInt32 class SettingsStorageManager { private var context: NSManagedObjectContext init(context: NSManagedObjectContext) { self.context = context } func settings() -> [SettingsKey: SettingsValue] { let fetchRequest = NSFetchRequest<Settings>(entityName: "Settings") guard let settings = try? context.fetch(fetchRequest) else { return [:] } var result = [SettingsKey: SettingsValue]() for setting in settings { if let settingKey = setting.settingKey, let key = SettingsKey(rawValue: settingKey) { result[key] = SettingsValue(setting.settingValue) } } return result } func save(_ value: SettingsValue, forSetting key: SettingsKey) { let fetchRequest = NSFetchRequest<Settings>(entityName: "Settings") fetchRequest.predicate = NSPredicate(format: "settingKey == %@", key.rawValue) guard let settings = try? context.fetch(fetchRequest) else { return } if let setting = settings.first { setting.settingValue = Int32(value) } else { guard let setting = NSEntityDescription.insertNewObject(forEntityName: "Settings", into: context) as? Settings else { return } setting.settingKey = key.rawValue setting.settingValue = Int32(value) } do { try context.save() } catch let e { print("Unable to save setting: \(e.localizedDescription)") } } }
mit
fc93f32485a20b154239732c7a812fe0
27.342857
86
0.595262
4.850856
false
false
false
false
Hout/TravisTester
Sources/SwiftDateTests/NSDateComponentsTests.swift
2
1602
// // NSDateComponentsTests.swift // SwiftDate // // Created by Jeroen Houtzager on 22/02/16. // Copyright © 2016 Jeroen Houtzager. All rights reserved. // import Foundation import Quick import Nimble import SwiftDate class NSDateComponentsSpec: QuickSpec { override func spec() { describe("NSDateComponents") { var components: NSDateComponents! var date: NSDate! beforeEach { components = NSDateComponents() components.year = 1 components.month = 2 components.day = 3 components.second = 4 date = NSDate(year: 2006, month: 7, day: 19, hour: 13) } context("fromDate") { it("should return date with added components") { let newDate = components.fromDate(date) expect(newDate.year) == 2007 expect(newDate.month) == 9 expect(newDate.day) == 22 expect(newDate.hour) == 13 expect(newDate.second) == 4 } } context("agoFromDate") { it("should return date with subtracted components") { let newDate = components.agoFromDate(date) expect(newDate.year) == 2005 expect(newDate.month) == 5 expect(newDate.day) == 16 expect(newDate.hour) == 12 expect(newDate.second) == 56 } } } } }
mit
6f697494baefaa8c65c51a23521fc2de
28.648148
70
0.492817
5.18123
false
false
false
false
NicholasTD07/HarvestAPI.swift
Sources/HarvestAPI.swift
1
8771
import Foundation import enum Alamofire.HTTPMethod import class Alamofire.SessionManager import class Alamofire.Request import enum Result.Result import Argo import Curry import Runes public protocol APIType { typealias DayHandler = (_ date: Date) -> (_: Result<Model.Day, API.Error>) -> Void typealias ProjectsHandler = (_: Result<[Model.Project], API.Error>) -> Void typealias UserHandler = (_: Result<Model.User, API.Error>) -> Void func days(_ days: [Date], handler: @escaping APIType.DayHandler) func day(at date: Date, handler: @escaping APIType.DayHandler) func projects(handler: @escaping ProjectsHandler) func user(handler: @escaping UserHandler) } extension API { public enum Error: Swift.Error { case networkFailed(Swift.Error) case decodingFailed(DecodeError) } } public struct API: APIType { public typealias HTTPBasicAuth = (username: String, password: String) public let company: String private let auth: HTTPBasicAuth private let sessionManager: SessionManager public init(company: String, auth: HTTPBasicAuth) { self.company = company self.auth = auth let configuration = URLSessionConfiguration.default let authorizationHeader = Request.authorizationHeader( user: auth.username, password: auth.password )! configuration.httpAdditionalHeaders = [ "Accept": "application/json", authorizationHeader.key: authorizationHeader.value, ] self.sessionManager = SessionManager(configuration: configuration) } public func days(_ days: [Date], handler: @escaping APIType.DayHandler) { days.forEach { day(at: $0, handler: handler) } } public func day(at date: Date, handler: @escaping APIType.DayHandler) { request(Router.day(at: date), with: handler(date)) } public func projects(handler: @escaping APIType.ProjectsHandler) { request(Router.today) { (result: Result<Model.Day, API.Error>) in switch result { case let .success(day): handler(.success(day.projects)) case let .failure(error): handler(.failure(error)) } } } public func user(handler: @escaping APIType.UserHandler) { request(Router.whoami, with: handler) } private func request<Value>(_ route: Router, with handler: @escaping (_: Result<Value, API.Error>) -> Void) where Value: Decodable, Value.DecodedType == Value { sessionManager.request(route.request(forCompany: company)) .responseJSON { response in guard let json = response.result.value else { handler(.failure(.networkFailed(response.result.error!))) return } let decoded: Decoded<Value> = decode(json) switch decoded { case let .success(value): handler(.success(value)) case let .failure(decodeError): handler(.failure(.decodingFailed(decodeError))) } } } // Note: This is here for requesting `[Decodable]` types // Difference to the one above is where `Value` is used, it is replaced with `[Value]` // FIXME: Investigate whether there's a better/more clever way to solve it // without duplicating 98% of the code private func request<Value>(_ route: Router, with handler: @escaping (_: Result<[Value], API.Error>) -> Void) where Value: Decodable, Value.DecodedType == Value { sessionManager.request(route.request(forCompany: company)) .responseJSON { response in guard let json = response.result.value else { handler(.failure(.networkFailed(response.result.error!))) return } let decoded: Decoded<[Value]> = decode(json) switch decoded { case let .success(value): handler(.success(value)) case let .failure(decodeError): handler(.failure(.decodingFailed(decodeError))) } } } } public enum Router { case whoami case today case day(at: Date) case addEntry public func request(forCompany company: String) -> URLRequest { let baseURL = URL(string: "https://\(company).harvestapp.com")! var request = URLRequest(url: baseURL.appendingPathComponent(path)) request.httpMethod = method.rawValue // encode param return request } public var method: HTTPMethod { switch self { case .whoami, .today, .day: return .get case .addEntry: return .post } } public var path: String { switch self { case .whoami: return "/account/who_am_i" case .today: return "/daily" case let .day(date): let day = calendar.ordinality(of: .day, in: .year, for: date)! let year = calendar.component(.year, from: date) return "/daily/\(day)/\(year)" case .addEntry: return "/daily/add" } } } private let calendar = Calendar.current public enum Model { public struct User { public let firstName: String public let lastName: String public var name: String { return "\(firstName) \(lastName)" } } public struct Day { public let dateString: String public let entries: [Entry] public let projects: [Project] public func date() -> Date { return Day.dateFormatter.date(from: dateString)! } public static let dateFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" return dateFormatter }() } public struct Entry { public let hours: Float } public struct Project { public let id: Int public let name: String public let billable: Bool public let tasks: [Task] } public struct Task { public let id: Int public let name: String public let billable: Bool } } extension Model.User: Decodable { public static func decode(_ json: JSON) -> Decoded<Model.User> { return curry(Model.User.init) <^> json <| ["user", "first_name"] <*> json <| ["user", "last_name"] } } extension Model.Day: Decodable { public static func decode(_ json: JSON) -> Decoded<Model.Day> { return curry(Model.Day.init) <^> json <| "for_day" <*> json <|| "day_entries" <*> json <|| "projects" } } extension Model.Entry: Decodable { public static func decode(_ json: JSON) -> Decoded<Model.Entry> { return curry(Model.Entry.init) <^> json <| "hours" } } extension Model.Project: Decodable { public static func decode(_ json: JSON) -> Decoded<Model.Project> { return curry(Model.Project.init) <^> json <| "id" <*> json <| "name" <*> json <| "billable" <*> json <|| "tasks" } } extension Model.Task: Decodable { public static func decode(_ json: JSON) -> Decoded<Model.Task> { return curry(Model.Task.init) <^> json <| "id" <*> json <| "name" <*> json <| "billable" } } extension Model.Project: Equatable { } public func == (rhs: Model.Project, lhs: Model.Project) -> Bool { return rhs.id == lhs.id } extension Model.Task: Equatable { } public func == (rhs: Model.Task, lhs: Model.Task) -> Bool { return rhs.id == lhs.id } // ViewModel candidates extension Model.Day { public func hours() -> Float { return entries.reduce(0) { $0 + $1.hours } } } extension Model.Project { public var description: String { let billableString = billable ? "Billable" : "Non-billable" return "\(billableString) \(name)" } } extension Model.Task { public var description: String { let billableString = billable ? "Billable" : "Non-billable" return "\(billableString) \(name)" } } /** From: https://github.com/NicholasTD07/TTTTT/blob/master/2016-08---Py---Harvest-Season/harvest_season.py entry_post_payload = { 'notes': notes, 'hours': hours, 'project_id': project.id, 'task_id': task.id, 'spent_at': spent_at, } */
mit
3d8a9559fc357d368a8c6915008b4974
28.334448
113
0.576787
4.479571
false
false
false
false
CodaFi/swift
test/Sanitizers/symbolication.swift
1
1299
// RUN: %target-build-swift %s -sanitize=address -g -target %sanitizers-target-triple -o %t // RUN: env %env-ASAN_OPTIONS=abort_on_error=0 not %target-run %t 2>&1 | %FileCheck %s -check-prefix=OOP // RUN: env %env-ASAN_OPTIONS=abort_on_error=0,external_symbolizer_path= not %target-run %t 2>&1 | %FileCheck %s -check-prefix=IP // REQUIRES: executable_test // REQUIRES: asan_runtime // REQUIRES: VENDOR=apple // REQUIRES: rdar68353068 // Check that Sanitizer reports are properly symbolicated on Apple platforms, // both out-of-process (via `atos`) and when falling back to in-process // symbolication. Note that `atos` also demangles Swift symbol names. @inline(never) func foo() { let x = UnsafeMutablePointer<Int>.allocate(capacity: 1) x.deallocate() print(x.pointee) } @inline(never) func bar() { foo() print("Prevent tail call optimization") } bar() // Out-of-process // OOP: #0 0x{{[0-9a-f]+}} in foo() symbolication.swift:[[@LINE-12]] // OOP-NEXT: #1 0x{{[0-9a-f]+}} in bar() symbolication.swift:[[@LINE-8]] // OOP-NEXT: #2 0x{{[0-9a-f]+}} in main symbolication.swift:[[@LINE-5]] // In-process // IP: #0 0x{{[0-9a-f]+}} in main.foo() -> ()+0x // IP-NEXT: #1 0x{{[0-9a-f]+}} in main.bar() -> ()+0x // IP-NEXT: #2 0x{{[0-9a-f]+}} in main+0x
apache-2.0
3e48a20bdf0765f47123332916644742
34.108108
130
0.641263
2.830065
false
false
false
false
DancewithPeng/DPMapper
Pods/Reflection/Sources/Reflection/Properties.swift
2
2793
private struct HashedType : Hashable { let hashValue: Int init(_ type: Any.Type) { hashValue = unsafeBitCast(type, to: Int.self) } } private func == (lhs: HashedType, rhs: HashedType) -> Bool { return lhs.hashValue == rhs.hashValue } private var cachedProperties = [HashedType : Array<Property.Description>]() /// An instance property public struct Property { public let key: String public let value: Any /// An instance property description public struct Description { public let key: String public let type: Any.Type let offset: Int func write(_ value: Any, to storage: UnsafeMutableRawPointer) throws { return try extensions(of: type).write(value, to: storage.advanced(by: offset)) } } } /// Retrieve properties for `instance` public func properties(_ instance: Any) throws -> [Property] { let props = try properties(type(of: instance)) var copy = extensions(of: instance) let storage = copy.storage() return props.map { nextProperty(description: $0, storage: storage) } } private func nextProperty(description: Property.Description, storage: UnsafeRawPointer) -> Property { return Property( key: description.key, value: extensions(of: description.type).value(from: storage.advanced(by: description.offset)) ) } /// Retrieve property descriptions for `type` public func properties(_ type: Any.Type) throws -> [Property.Description] { let hashedType = HashedType(type) if let properties = cachedProperties[hashedType] { return properties } else if let nominalType = Metadata.Struct(type: type) { return try fetchAndSaveProperties(nominalType: nominalType, hashedType: hashedType) } else if let nominalType = Metadata.Class(type: type) { return try fetchAndSaveProperties(nominalType: nominalType, hashedType: hashedType) } else { throw ReflectionError.notStruct(type: type) } } private func fetchAndSaveProperties<T : NominalType>(nominalType: T, hashedType: HashedType) throws -> [Property.Description] { let properties = try propertiesForNominalType(nominalType) cachedProperties[hashedType] = properties return properties } private func propertiesForNominalType<T : NominalType>(_ type: T) throws -> [Property.Description] { guard type.nominalTypeDescriptor.numberOfFields != 0 else { return [] } guard let fieldTypes = type.fieldTypes, let fieldOffsets = type.fieldOffsets else { throw ReflectionError.unexpected } let fieldNames = type.nominalTypeDescriptor.fieldNames return (0..<type.nominalTypeDescriptor.numberOfFields).map { i in return Property.Description(key: fieldNames[i], type: fieldTypes[i], offset: fieldOffsets[i]) } }
mit
d33fefa73ca845e92776df2bd4fd0a23
36.743243
127
0.704619
4.290323
false
false
false
false
superk589/CGSSGuide
DereGuide/LiveSimulator/LiveFormulator.swift
2
4465
// // LiveFormulator.swift // DereGuide // // Created by zzk on 2017/5/18. // Copyright © 2017 zzk. All rights reserved. // import UIKit import SwiftyJSON fileprivate extension Int { func addGreatPercent(_ percent: Double) -> Int { return Int(round(Double(self) * (1 - 0.3 * percent / 100))) } } extension LSNote { func expectation(in distribution: LFDistribution) -> Double { // 先对离散分布的每种情况进行分别取整 再做单个note的得分期望计算 let expectation = distribution.samples.reduce(0.0) { $0 + round(baseScore * comboFactor * Double($1.value.bonusValue) / 10000) * $1.probability } return expectation } } /// Formulator is only used in optimistic score 2 and average score calculation class LiveFormulator { var notes: [LSNote] var bonuses: [LSSkill] lazy var distributions: [LFDistribution] = { return self.generateScoreDistributions() }() init(notes: [LSNote], bonuses: [LSSkill]) { self.bonuses = bonuses self.notes = notes } var averageScore: Int { // var scores = [Int]() var sum = 0.0 for i in 0..<notes.count { let note = notes[i] let distribution = distributions[i] sum += note.expectation(in: distribution) // scores.append(Int(round(note.baseScore * note.comboFactor * distribution.average / 10000))) } // (scores as NSArray).write(to: URL.init(fileURLWithPath: NSHomeDirectory() + "/new.txt"), atomically: true) return Int(round(sum)).addGreatPercent(LiveSimulationAdvanceOptionsManager.default.greatPercent) } var maxScore: Int { var sum = 0 for i in 0..<notes.count { let note = notes[i] let distribution = distributions[i] sum += Int(round(note.baseScore * note.comboFactor * Double(distribution.maxValue) / 10000)) } return sum.addGreatPercent(LiveSimulationAdvanceOptionsManager.default.greatPercent) } var minScore: Int { var sum = 0 for i in 0..<notes.count { let note = notes[i] let distribution = distributions[i] sum += Int(round(note.baseScore * note.comboFactor * Double(distribution.minValue) / 10000)) } return sum.addGreatPercent(LiveSimulationAdvanceOptionsManager.default.greatPercent) } private func generateScoreDistributions() -> [LFDistribution] { var distributions = [LFDistribution]() for i in 0..<notes.count { let note = notes[i] let validBonuses = bonuses.filter { $0.range.contains(note.sec) } var samples = [LFSamplePoint<LSScoreBonusGroup>]() for mask in 0..<(1 << validBonuses.count) { var bonusGroup = LSScoreBonusGroup.basic var p = 1.0 for j in 0..<validBonuses.count { let bonus = validBonuses[j] if mask & (1 << j) != 0 { p *= bonus.probability switch bonus.type { case .comboBonus, .allRound: bonusGroup.baseComboBonus = max(bonusGroup.baseComboBonus, bonus.value) case .perfectBonus, .overload, .concentration: bonusGroup.basePerfectBonus = max(bonusGroup.basePerfectBonus, bonus.value) case .skillBoost: bonusGroup.skillBoost = max(bonusGroup.skillBoost, bonus.value) case .deep, .synergy: bonusGroup.basePerfectBonus = max(bonusGroup.basePerfectBonus, bonus.value) bonusGroup.baseComboBonus = max(bonusGroup.baseComboBonus, bonus.value2) default: break } } else { p *= 1 - bonus.probability } } let sample = LFSamplePoint<LSScoreBonusGroup>.init(probability: p, value: bonusGroup) samples.append(sample) } let distribution = LFDistribution(samples: samples) distributions.append(distribution) } return distributions } }
mit
65d51255f7c5b8bea7021a849190efef
35.733333
153
0.556942
4.421264
false
false
false
false
ibm-wearables-sdk-for-mobile/ios
RecordApp/RecordApp/DataCell.swift
2
1477
/* * © Copyright 2015 IBM Corp. * * Licensed under the Mobile Edge iOS Framework License (the "License"); * you may not use this file except in compliance with the License. You may find * a copy of the license in the license.txt file in this package. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit import IBMMobileEdge //cell to display the data and the sensitivity values class DataCell: UITableViewCell { @IBOutlet weak var name: UILabel! @IBOutlet weak var sensativity: UITextField! var sourceData:Data! func setData(data:Data){ sourceData = data name.text = data.name sensativity.text = "\(data.sensitivity)" name.enabled = !data.isDisabled sensativity.enabled = !data.isDisabled //will update the status in the prefs SensitivityUtils.setDisableStatus(sourceData.name, isDisabled: data.isDisabled) } @IBAction func onSensitivityChanged(sender: AnyObject) { sourceData.sensitivity = Double(sensativity.text!)! //change the sensativity pref SensitivityUtils.set(sourceData.name, sensitivity: sourceData.sensitivity) } }
epl-1.0
1c374e422c2e8671e87999c543eac9ac
32.545455
87
0.699187
4.392857
false
false
false
false
ConceptsInCode/PackageTracker
PackageTracker/PackageTracker/Summary.swift
1
1783
// // Summary.swift // PackageTracker // // Created by Hank Turowski on 5/10/15. // Copyright (c) 2015 Concepts In Code. All rights reserved. // import Foundation class Summary: NSObject, NSXMLParserDelegate { var eventTime = "" var eventDate = "" var event = "" var eventCity = "" var eventState = "" var eventZipCode = "" var eventCountry = "" var firmName = "" var name = "" var authorizedAgent = "" var deliveryAttributeCode = "" private var parsingContext : String? = nil func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI : String?, qualifiedName: String?, attributes attributeDict: [String: String]) { parsingContext = elementName } func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI : String?, qualifiedName: String?) { parsingContext = nil } func parser(parser: NSXMLParser, foundCharacters: String) { if let context = parsingContext { switch context { case "EventTime": eventTime = foundCharacters case "EventDate": eventDate = foundCharacters case "Event": event = foundCharacters case "EventCity": eventCity = foundCharacters case "EventState": eventState = foundCharacters case "EventZipCode": eventZipCode = foundCharacters case "EventCountry": eventCountry = foundCharacters case "FirmName": firmName = foundCharacters case "Name": name = foundCharacters case "AuthorizedAgent": authorizedAgent = foundCharacters case "DeliveryAttributeCode" : deliveryAttributeCode = foundCharacters default: break } } } }
mit
b7b7e925f068d2f6f62e0e7058f636c6
32.641509
167
0.637689
5.123563
false
false
false
false
mpsnp/ReSwift
ReSwift/CoreTypes/DispatchingStoreType.swift
1
2169
import Foundation public typealias ActionCreator<T> = ( _ store: DispatchingStoreType ) -> T public typealias AsyncActionCreator<T> = ( _ store: DispatchingStoreType, _ next: (T) -> Void ) -> Void /** Defines the interface of a dispatching, stateless Store in ReSwift. `StoreType` is the default usage of this interface. Can be used for store variables where you don't care about the state, but want to be able to dispatch actions. */ public protocol DispatchingStoreType { /** Dispatches an action. This is the simplest way to modify the stores state. Example of dispatching an action: ``` store.dispatch( CounterAction.IncreaseCounter ) ``` - parameter action: The action that is being dispatched to the store - returns: By default returns the dispatched action, but middlewares can change the return type, e.g. to return promises */ @discardableResult func dispatch(_ actions: Any...) -> Any } extension DispatchingStoreType { public func dispatch(_ action: Action) { dispatch(action as Any) } public func dispatch<ReturnValue>( _ actionCreator: @escaping ActionCreator<ReturnValue> ) -> ReturnValue { guard let result = dispatch(actionCreator as ActionCreator<Any>) as? ReturnValue else { raiseFatalError( "ReSwift: You tried to dispatch action creator" + " with different return value type" ) } return result } public func dispatch<CallbackParam>( _ asyncActionCreator: @escaping AsyncActionCreator<CallbackParam>, _ callback: @escaping (CallbackParam) -> Void ) { let typeErasedActionCreator: AsyncActionCreator<Any> = { store, next in asyncActionCreator(store, { (param) in next(param) }) } let typeErasedCallback: (Any) -> Void = { param in guard let param = param as? CallbackParam else { raiseFatalError() } callback(param) } dispatch(typeErasedActionCreator as Any, typeErasedCallback as Any) } }
mit
d314621ceca8e9ddbb5ec19e6bb62d97
29.125
95
0.639004
4.885135
false
false
false
false
myandy/shi_ios
shishi/UI/Setting/SettingVC.swift
1
7454
// // SettingVC.swift // shishi // // Created by andymao on 2017/5/10. // Copyright © 2017年 andymao. All rights reserved. // import Foundation import UIKit import RxSwift import NSObject_Rx class SettingVC: BaseSettingVC { lazy var yunItem: SettingItemView = SettingItemView() lazy var fontItem: SettingItemView = SettingItemView() lazy var checkPingzeItem: SettingItemView = SettingItemView() lazy var authorItem: SettingItemView = SettingItemView() lazy var selectorList = [#selector(yunItemClick),#selector(fontItemClick),#selector(checkItemClick),#selector(writingItemClick)] lazy var titleList = [SSStr.Setting.YUN_TITLE,SSStr.Setting.FONT_TITLE,SSStr.Setting.CHECK_TITLE,SSStr.Setting.AUTHOR_TITLE] lazy var selectorList2 = [#selector(aboutItemClick),#selector(weiboItemClick),#selector(marktemClick),#selector(shareItemClick)] lazy var titleList2 = [SSStr.Setting.ABOUT_TITLE,SSStr.Setting.WEIBO_TITLE,SSStr.Setting.MARK_TITLE,SSStr.Setting.SHARE_TITLE] override func setupUI(){ SSNotificationCenter.default.rx.notification(SSNotificationCenter.Names.updateAppLanguage).subscribe(onNext: { [weak self] notify in self?.refreshFont() }) .addDisposableTo(self.rx_disposeBag) let card1 = getCardView() self.scrollView.addSubview(card1) var itemList = [yunItem,fontItem,checkPingzeItem,authorItem] card1.snp.makeConstraints{ (make) in make.left.equalToSuperview().offset(20) make.right.equalTo(self.view).offset(-20) make.top.equalTo(backBtn).offset(80) make.height.equalTo(ITEM_HEIGHT * itemList.count) } for (index,item) in itemList.enumerated() { card1.addSubview(item) item.snp.makeConstraints{ (make) in make.left.right.equalToSuperview() make.height.equalTo(ITEM_HEIGHT) if index == 0 { make.top.equalToSuperview() } else { make.top.equalTo(itemList[index-1].snp.bottom).offset(1) } } item.title.text = titleList[index] item.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: selectorList[index]) item.addGestureRecognizer(tapGes) if index > 0 && index < itemList.count { addDivideView(card1,topView:itemList[index-1]) } } refreshYun() refreshFont() refreshCheckPingze() refreshUsername() let card2 = getCardView() self.scrollView.addSubview(card2) var itemList2 = [SettingItemView(),SettingItemView(),SettingItemView(),SettingItemView()] card2.snp.makeConstraints{ (make) in make.left.equalToSuperview().offset(20) make.right.equalTo(self.view).offset(-20) make.top.equalTo(card1.snp.bottom).offset(20) make.height.equalTo(ITEM_HEIGHT * itemList2.count) } for (index,item) in itemList2.enumerated() { card2.addSubview(item) item.snp.makeConstraints{ (make) in make.left.right.equalToSuperview() make.height.equalTo(ITEM_HEIGHT) if index == 0 { make.top.equalToSuperview() } else { make.top.equalTo(itemList2[index-1].snp.bottom).offset(1) } } item.title.text = titleList2[index] item.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: selectorList2[index]) item.addGestureRecognizer(tapGes) if index > 0 && index < itemList.count { addDivideView(card2,topView:itemList2[index-1]) } } } func refreshYun(){ self.yunItem.hint.text = SSStr.Setting.YUN_CHOICES[UserDefaultUtils.getYunshu()] } func refreshFont(){ self.fontItem.hint.text = SSStr.Setting.FONT_CHOICES[UserDefaultUtils.getFont()] fixLanguage() } func refreshCheckPingze(){ self.checkPingzeItem.hint.text = SSStr.Setting.CHECK_CHOICES[UserDefaultUtils.isCheckPingze() ? 0 : 1] } func refreshUsername(){ self.authorItem.hint.text = UserDefaultUtils.getUsername() } override func onBackBtnClicked() { self.navigationController?.popViewController(animated: true) } } // MARK: - Action extension SettingVC{ func yunItemClick(){ let vc = YunSettingVC() vc.changeSelector = { () in self.refreshYun() } self.navigationController?.pushViewController(vc, animated: false) } func fontItemClick(){ let vc = FontSettingVC() vc.changeSelector = { () in self.refreshFont() } self.navigationController?.pushViewController(vc, animated: false) } func checkItemClick(){ let vc = CheckPingzeSettingVC() vc.changeSelector = { () in self.refreshCheckPingze() } self.navigationController?.pushViewController(vc, animated: false) } func writingItemClick(){ let alert = UIAlertController(title: SSStr.Setting.USERNAME_TITLE, message: SSStr.Setting.USERNAME_CONTENT, preferredStyle: UIAlertControllerStyle.alert) alert.addTextField { (textField: UITextField!) -> Void in let username = UserDefaultUtils.getUsername() if username != nil && !(username?.isEmpty)! { textField.text = username } textField.placeholder = SSStr.Setting.USERNAME_HINT } let alertView1 = UIAlertAction(title: SSStr.Common.CANCEL, style: UIAlertActionStyle.cancel) let alertView2 = UIAlertAction(title: SSStr.Common.CONFIRM, style: UIAlertActionStyle.default) { (UIAlertAction) -> Void in UserDefaultUtils.setUsername((alert.textFields?.first?.text)!) self.refreshUsername() SSNotificationCenter.default.post(name: SSNotificationCenter.Names.updateAuthorName, object: nil) } alert.addAction(alertView1) alert.addAction(alertView2) self.present(alert, animated: true, completion: nil) } //关于我们 func aboutItemClick(){ self.navigationController?.pushViewController(AboutVC(), animated: false) } //app store 评分 func marktemClick(){ let urlString = "itms-apps://itunes.apple.com/app/id1277723033" let url = URL(string: urlString)! UIApplication.shared.openURL(url) // UIApplication.shared.open(url!) } //跳转微博 func weiboItemClick(){ UIApplication.shared.openURL(URL(string: "http://www.weibo.com/anddymao")!) } //分享给好友 func shareItemClick(){ let urlString = "https://itunes.apple.com/cn/app/id1277723033?mt=8" // SSStr.Setting.SHARE_FRIENDS_CONTENT SSShareUtil.default.shareToSystem(controller: self, title: SSStr.Setting.SHARE_FRIENDS_TITLE, image: UIImage(named: "icon")!, urlString: urlString) } }
apache-2.0
370d7f60b28e9073ed0cc9b57ea1492a
33.041284
161
0.61299
4.435744
false
false
false
false
mohamede1945/quran-ios
Quran/QuranViewController.swift
1
14876
// // QuranViewController.swift // Quran // // Created by Mohamed Afifi on 4/28/16. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import UIKit class QuranViewController: BaseViewController, AudioBannerViewPresenterDelegate, QuranDataSourceDelegate, QuranViewDelegate, QuranNavigationBarDelegate { private let bookmarksPersistence: BookmarksPersistence private let bookmarksManager: BookmarksManager private let quranNavigationBar: QuranNavigationBar private let verseTextRetrieval: AnyInteractor<QuranShareData, String> private let dataRetriever: AnyGetInteractor<[QuranPage]> private let audioViewPresenter: AudioBannerViewPresenter private let qarisControllerCreator: AnyCreator<([Qari], Int, UIView?), QariTableViewController> private let translationsSelectionControllerCreator: AnyGetCreator<UIViewController> private let simplePersistence: SimplePersistence private var lastPageUpdater: LastPageUpdater private let dataSource: QuranDataSource private let scrollToPageToken = Once() private let didLayoutSubviewToken = Once() private let interactiveGestureToken = Once() private var titleView: QuranPageTitleView? { return navigationItem.titleView as? QuranPageTitleView } private var quranView: QuranView? { return view as? QuranView } private var barsTimer: VFoundation.Timer? private var interactivePopGestureOldEnabled: Bool? private var barsHiddenTimerExecuted = false override var screen: Analytics.Screen { return isTranslationView ? .quranArabic : .quranTranslation } private var statusBarHidden = false { didSet { setNeedsStatusBarAppearanceUpdate() } } private var initialPage: Int = 0 { didSet { title = Quran.nameForSura(Quran.PageSuraStart[initialPage - 1], withPrefix: true) titleView?.setPageNumber(initialPage, navigationBar: navigationController?.navigationBar) } } private var isTranslationView: Bool { set { simplePersistence.setValue(newValue, forKey: .showQuranTranslationView) } get { return simplePersistence.valueForKey(.showQuranTranslationView) } } var isBookmarked: Bool { return bookmarksManager.isBookmarked } var lastViewedPage: Int { return lastPageUpdater.lastPage?.page ?? initialPage } override var prefersStatusBarHidden: Bool { return statusBarHidden || traitCollection.containsTraits(in: UITraitCollection(verticalSizeClass: .compact)) } override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return .slide } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } init(imageService : AnyCacheableService<Int, UIImage>, // swiftlint:disable:this function_parameter_count pageService : AnyCacheableService<Int, TranslationPage>, dataRetriever : AnyGetInteractor<[QuranPage]>, ayahInfoRetriever : AyahInfoRetriever, audioViewPresenter : AudioBannerViewPresenter, qarisControllerCreator : AnyCreator<([Qari], Int, UIView?), QariTableViewController>, translationsSelectionControllerCreator : AnyGetCreator<UIViewController>, bookmarksPersistence : BookmarksPersistence, lastPagesPersistence : LastPagesPersistence, simplePersistence : SimplePersistence, verseTextRetrieval : AnyInteractor<QuranShareData, String>, page : Int, lastPage : LastPage?) { self.initialPage = page self.dataRetriever = dataRetriever self.lastPageUpdater = LastPageUpdater(persistence: lastPagesPersistence) self.bookmarksManager = BookmarksManager(bookmarksPersistence: bookmarksPersistence) self.simplePersistence = simplePersistence self.audioViewPresenter = audioViewPresenter self.qarisControllerCreator = qarisControllerCreator self.translationsSelectionControllerCreator = translationsSelectionControllerCreator self.quranNavigationBar = QuranNavigationBar(simplePersistence: simplePersistence) self.bookmarksPersistence = bookmarksPersistence self.verseTextRetrieval = verseTextRetrieval let imagesDataSource = QuranImagesDataSource( imageService: imageService, ayahInfoRetriever: ayahInfoRetriever, bookmarkPersistence: bookmarksPersistence) let translationsDataSource = QuranTranslationsDataSource( pageService: pageService, ayahInfoRetriever: ayahInfoRetriever, bookmarkPersistence: bookmarksPersistence) let dataSources = [imagesDataSource.asBasicDataSourceRepresentable(), translationsDataSource.asBasicDataSourceRepresentable()] let handlers: [QuranDataSourceHandler] = [imagesDataSource, translationsDataSource] dataSource = QuranDataSource(dataSources: dataSources, handlers: handlers) super.init(nibName: nil, bundle: nil) updateTranslationView(initialization: true) self.lastPageUpdater.configure(initialPage: page, lastPage: lastPage) audioViewPresenter.delegate = self imagesDataSource.delegate = self automaticallyAdjustsScrollViewInsets = false // page behavior let pageBehavior = ScrollViewPageBehavior() dataSource.scrollViewDelegate = pageBehavior kvoController.observe(pageBehavior, keyPath: #keyPath(ScrollViewPageBehavior.currentPage), options: .new) { [weak self] _ in self?.onPageChanged() } pageBehavior.onScrollViewWillBeginDragging = { [weak self] in self?.setBarsHidden(true) } dataSource.onScrollViewWillBeginDragging = { [weak self] in self?.setBarsHidden(true) } } required init?(coder aDecoder: NSCoder) { unimplemented() } override func loadView() { view = QuranView(bookmarksPersistence: bookmarksPersistence, verseTextRetrieval: verseTextRetrieval) } override func viewDidLoad() { super.viewDidLoad() quranView?.delegate = self quranNavigationBar.delegate = self configureAudioView() quranView?.collectionView.ds_useDataSource(dataSource) // set the custom title view navigationItem.titleView = QuranPageTitleView() dataRetriever.get().then(on: .main) { [weak self] items -> Void in self?.dataSource.setItems(items) self?.scrollToFirstPage() }.suppress() audioViewPresenter.onViewDidLoad() } private func configureAudioView() { quranView?.audioView.onTouchesBegan = { [weak self] in self?.stopBarHiddenTimer() } audioViewPresenter.view = quranView?.audioView quranView?.audioView.delegate = audioViewPresenter } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) UIApplication.shared.isIdleTimerDisabled = true navigationController?.setNavigationBarHidden(false, animated: animated) interactiveGestureToken.once { interactivePopGestureOldEnabled = navigationController?.interactivePopGestureRecognizer?.isEnabled } navigationController?.interactivePopGestureRecognizer?.isEnabled = false // start hiding bars timer if !barsHiddenTimerExecuted { startHiddenBarsTimer() } // reload when coming from translation if presentedViewController is TranslationsSelectionNavigationController { dataSource.invalidate() } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) UIApplication.shared.isIdleTimerDisabled = false navigationController?.interactivePopGestureRecognizer?.isEnabled = interactivePopGestureOldEnabled ?? true } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() didLayoutSubviewToken.once {} scrollToFirstPage() } fileprivate func scrollToFirstPage() { let currentIndex = dataSource.selectedBasicDataSource.items.index(where: { $0.pageNumber == initialPage }) guard let index = currentIndex, didLayoutSubviewToken.executed else { return } scrollToPageToken.once { let indexPath = IndexPath(item: index, section: 0) scrollToIndexPath(indexPath, animated: false) onPageChangedToPage(dataSource.selectedBasicDataSource.item(at: indexPath)) } } func stopBarHiddenTimer() { barsTimer?.cancel() barsTimer = nil } // MARK: - Quran View Delegate func onQuranViewTapped(_ quranView: QuranView) { setBarsHidden(navigationController?.isNavigationBarHidden == false) } func quranView(_ quranView: QuranView, didSelectTextToShare text: String, sourceView: UIView, sourceRect: CGRect) { ShareController.share(text: text, sourceView: sourceView, sourceRect: sourceRect, sourceViewController: self, handler: nil) } private func setBarsHidden(_ hidden: Bool) { // remove the timer barsHiddenTimerExecuted = true stopBarHiddenTimer() navigationController?.setNavigationBarHidden(hidden, animated: true) quranView?.setBarsHidden(hidden) // animate the change UIView.animate(withDuration: 0.3, animations: { self.statusBarHidden = hidden self.view.layoutIfNeeded() }) } fileprivate func startHiddenBarsTimer() { // increate the timer duration to give existing users the time to see the new buttons barsTimer = Timer(interval: 5) { [weak self] in if self?.presentedViewController == nil { self?.setBarsHidden(true) } } } fileprivate func scrollToIndexPath(_ indexPath: IndexPath, animated: Bool) { quranView?.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false) } fileprivate func onPageChanged() { guard let page = currentPage() else { return } onPageChangedToPage(page) } fileprivate func onPageChangedToPage(_ page: QuranPage) { updateBarToPage(page) } fileprivate func updateBarToPage(_ page: QuranPage) { // only apply if there is a change guard page.pageNumber != titleView?.pageNumber else { return } titleView?.setPageNumber(page.pageNumber, navigationBar: navigationController?.navigationBar) bookmarksManager.calculateIsBookmarked(pageNumber: page.pageNumber) .then(on: .main) { _ -> Void in guard page.pageNumber == self.currentPage()?.pageNumber else { return } self.quranNavigationBar.updateRightBarItems(animated: false) }.cauterize(tag: "bookmarksPersistence.isPageBookmarked") // only persist if active if UIApplication.shared.applicationState == .active { Crash.setValue(page.pageNumber, forKey: .QuranPage) updateLatestPageTo(page: page.pageNumber) } } private func updateLatestPageTo(page: Int) { Analytics.shared.showing(quranPage: page, isTranslation: isTranslationView, numberOfSelectedTranslations: simplePersistence.valueForKey(.selectedTranslations).count) lastPageUpdater.updateTo(page: page) } func onBookmarkButtonTapped() { guard let page = currentPage() else { return } bookmarksManager .toggleBookmarking(pageNumber: page.pageNumber) .cauterize(tag: "bookmarksPersistence.toggleBookmarking") } func onTranslationButtonTapped() { updateTranslationView(initialization: false) } func onSelectTranslationsButtonTapped() { let controller = translationsSelectionControllerCreator.create() present(controller, animated: true, completion: nil) } func showQariListSelectionWithQari(_ qaris: [Qari], selectedIndex: Int) { let controller = qarisControllerCreator.create((qaris, selectedIndex, quranView?.audioView)) controller.onSelectedIndexChanged = { [weak self] index in self?.audioViewPresenter.setQariIndex(index) } present(controller, animated: true, completion: nil) } func highlightAyah(_ ayah: AyahNumber) { var set = Set<AyahNumber>() set.insert(ayah) dataSource.highlightAyaht(set) // persist if not active guard UIApplication.shared.applicationState != .active else { return } Queue.background.async { let page = ayah.getStartPage() self.updateLatestPageTo(page: page) Crash.setValue(page, forKey: .QuranPage) } } func removeHighlighting() { dataSource.highlightAyaht(Set()) } func currentPage() -> QuranPage? { return quranView?.visibleIndexPath().map { dataSource.selectedBasicDataSource.item(at: $0) } } func onErrorOccurred(error: Error) { showErrorAlert(error: error) } private func updateTranslationView(initialization: Bool) { let isTranslationView = quranNavigationBar.isTranslationView dataSource.selectedDataSourceIndex = isTranslationView ? 1 : 0 let noTranslationsSelected = simplePersistence.valueForKey(.selectedTranslations).isEmpty if !initialization && isTranslationView && noTranslationsSelected { onSelectTranslationsButtonTapped() } } }
gpl-3.0
b61aa5b1978d2032d0993dfa6442db23
37.942408
135
0.665098
5.489299
false
false
false
false
colemancda/XcodeServerSDK
XcodeServerSDK/XcodeServerEndpoints.swift
1
5306
// // XcodeServerEndpoints.swift // Buildasaur // // Created by Honza Dvorsky on 14/12/2014. // Copyright (c) 2014 Honza Dvorsky. All rights reserved. // import Foundation public class XcodeServerEndPoints { enum Endpoint { case Bots case Integrations case CancelIntegration case UserCanCreateBots case Devices case Login case Logout case Platforms case SCM_Branches case Repositories } let serverConfig: XcodeServerConfig /** Designated initializer. - parameter serverConfig: Object of XcodeServerConfig class - returns: Initialized object of XcodeServer endpoints */ public init(serverConfig: XcodeServerConfig) { self.serverConfig = serverConfig } private func endpointURL(endpoint: Endpoint, params: [String: String]? = nil) -> String { let base = "/api" switch endpoint { case .Bots: let bots = "\(base)/bots" if let bot = params?["bot"] { let bot = "\(bots)/\(bot)" if let rev = params?["rev"] { let rev = "\(bot)/\(rev)" return rev } return bot } return bots case .Integrations: if let _ = params?["bot"] { //gets a list of integrations for this bot let bots = self.endpointURL(.Bots, params: params) return "\(bots)/integrations" } let integrations = "\(base)/integrations" if let integration = params?["integration"] { let oneIntegration = "\(integrations)/\(integration)" return oneIntegration } return integrations case .CancelIntegration: let integration = self.endpointURL(.Integrations, params: params) let cancel = "\(integration)/cancel" return cancel case .Devices: let devices = "\(base)/devices" return devices case .UserCanCreateBots: let users = "\(base)/auth/isBotCreator" return users case .Login: let login = "\(base)/auth/login" return login case .Logout: let logout = "\(base)/auth/logout" return logout case .Platforms: let platforms = "\(base)/platforms" return platforms case .SCM_Branches: let branches = "\(base)/scm/branches" return branches case .Repositories: let repositories = "\(base)/repositories" return repositories } } /** Builder method for URlrequests based on input parameters. - parameter method: HTTP method used for request (GET, POST etc.) - parameter endpoint: Endpoint object - parameter params: URL params (default is nil) - parameter query: Query parameters (default is nil) - parameter body: Request's body (default is nil) - parameter doBasicAuth: Requirement of authorization (default is true) - returns: NSMutableRequest or nil if wrong URL was provided */ func createRequest(method: HTTP.Method, endpoint: Endpoint, params: [String : String]? = nil, query: [String : String]? = nil, body: NSDictionary? = nil, doBasicAuth auth: Bool = true) -> NSMutableURLRequest? { let endpointURL = self.endpointURL(endpoint, params: params) let queryString = HTTP.stringForQuery(query) let wholePath = "\(self.serverConfig.host):\(self.serverConfig.port)\(endpointURL)\(queryString)" guard let url = NSURL(string: wholePath) else { return nil } let request = NSMutableURLRequest(URL: url) request.HTTPMethod = method.rawValue if auth { //add authorization header let user = self.serverConfig.user ?? "" let password = self.serverConfig.password ?? "" let plainString = "\(user):\(password)" as NSString let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding) let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) request.setValue("Basic \(base64String!)", forHTTPHeaderField: "Authorization") } if let body = body { do { let data = try NSJSONSerialization.dataWithJSONObject(body, options: .PrettyPrinted) request.HTTPBody = data request.setValue("application/json", forHTTPHeaderField: "Content-Type") } catch { let error = error as NSError Log.error("Parsing error \(error.description)") return nil } } return request } }
mit
06caa459d11fb2f7e6868c2c3f57fc86
30.583333
214
0.532416
5.687031
false
true
false
false
groue/GRDB.swift
GRDB/Core/SQLRequest.swift
1
7579
/// An SQL request that can decode database rows. /// /// `SQLRequest` allows you to safely embed raw values in your SQL, /// without any risk of syntax errors or SQL injection: /// /// ```swift /// extension Player: FetchableRecord { /// static func filter(name: String) -> SQLRequest<Player> { /// "SELECT * FROM player WHERE name = \(name)" /// } /// /// static func maximumScore() -> SQLRequest<Int> { /// "SELECT MAX(score) FROM player" /// } /// } /// /// try dbQueue.read { db in /// let players = try Player.filter(name: "O'Brien").fetchAll(db) // [Player] /// let maxScore = try Player.maximumScore().fetchOne(db) // Int? /// } /// ``` /// /// An `SQLRequest` can be created from a string literal or interpolation, as in /// the above examples, and from the initializers documented below. /// /// ## Topics /// /// ### Creating an SQL Request from a Literal Value /// /// - ``init(stringLiteral:)`` /// - ``init(unicodeScalarLiteral:)-84mq8`` /// - ``init(extendedGraphemeClusterLiteral:)-1sf75`` /// /// ### Creating an SQL Request from an Interpolation /// /// - ``init(stringInterpolation:)`` /// /// ### Creating an SQL Request from an SQL Literal /// /// - ``init(literal:adapter:cached:)-4vuxn`` /// - ``init(literal:adapter:cached:)-82f97`` /// /// ### Creating an SQL Request from an SQL String /// /// - ``init(sql:arguments:adapter:cached:)-3qq8t`` /// - ``init(sql:arguments:adapter:cached:)-5ecx2`` public struct SQLRequest<RowDecoder> { /// There are two statement caches: one "public" for statements generated by /// the user, and one "internal" for the statements generated by GRDB. Those /// are separated so that GRDB has no opportunity to inadvertently modify /// the arguments of user's cached statements. enum Cache { /// The public cache, for library user case `public` /// The internal cache, for GRDB case `internal` } /// The row adapter. public var adapter: (any RowAdapter)? private(set) var sqlLiteral: SQL let cache: Cache? private init( literal sqlLiteral: SQL, adapter: (any RowAdapter)?, fromCache cache: Cache?, type: RowDecoder.Type) { self.sqlLiteral = sqlLiteral self.adapter = adapter self.cache = cache } } extension SQLRequest { /// Creates a request from an SQL string. /// /// ```swift /// let request = SQLRequest<String>(sql: """ /// SELECT name FROM player /// """) /// let request = SQLRequest<Player>(sql: """ /// SELECT * FROM player WHERE name = ? /// """, arguments: ["O'Brien"]) /// ``` /// /// - parameters: /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter. /// - cached: Defaults to false. If true, the request reuses a cached /// prepared statement. public init( sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil, cached: Bool = false) { self.init( literal: SQL(sql: sql, arguments: arguments), adapter: adapter, fromCache: cached ? .public : nil, type: RowDecoder.self) } /// Creates a request from an ``SQL`` literal. /// /// ``SQL`` literals allow you to safely embed raw values in your SQL, /// without any risk of syntax errors or SQL injection: /// /// ```swift /// let name = "O'Brien" /// let request = SQLRequest<Player>(literal: """ /// SELECT * FROM player WHERE name = \(name) /// """) /// ``` /// /// - parameters: /// - sqlLiteral: An `SQL` literal. /// - adapter: Optional RowAdapter. /// - cached: Defaults to false. If true, the request reuses a cached /// prepared statement. public init(literal sqlLiteral: SQL, adapter: (any RowAdapter)? = nil, cached: Bool = false) { self.init( literal: sqlLiteral, adapter: adapter, fromCache: cached ? .public : nil, type: RowDecoder.self) } } extension SQLRequest<Row> { /// Creates a request of database rows, from an SQL string. /// /// ```swift /// let request = SQLRequest(sql: """ /// SELECT * FROM player WHERE name = ? /// """, arguments: ["O'Brien"]) /// ``` /// /// - parameters: /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter. /// - cached: Defaults to false. If true, the request reuses a cached /// prepared statement. public init( sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil, cached: Bool = false) { self.init( literal: SQL(sql: sql, arguments: arguments), adapter: adapter, fromCache: cached ? .public : nil, type: Row.self) } /// Creates a request of database rows, from an ``SQL`` literal. /// /// ``SQL`` literals allow you to safely embed raw values in your SQL, /// without any risk of syntax errors or SQL injection: /// /// ```swift /// let name = "O'Brien" /// let request = SQLRequest(literal: """ /// SELECT * FROM player WHERE name = \(name) /// """) /// ``` /// /// - parameters: /// - sqlLiteral: An `SQL` literal. /// - adapter: Optional RowAdapter. /// - cached: Defaults to false. If true, the request reuses a cached /// prepared statement. public init(literal sqlLiteral: SQL, adapter: (any RowAdapter)? = nil, cached: Bool = false) { self.init( literal: sqlLiteral, adapter: adapter, fromCache: cached ? .public : nil, type: Row.self) } } extension SQLRequest: FetchRequest { public var sqlSubquery: SQLSubquery { .literal(sqlLiteral) } public func fetchCount(_ db: Database) throws -> Int { try SQLRequest<Int>("SELECT COUNT(*) FROM (\(self))").fetchOne(db)! } public func makePreparedRequest( _ db: Database, forSingleResult singleResult: Bool = false) throws -> PreparedRequest { let context = SQLGenerationContext(db) let sql = try sqlLiteral.sql(context) let statement: Statement switch cache { case .none: statement = try db.makeStatement(sql: sql) case .public?: statement = try db.cachedStatement(sql: sql) case .internal?: statement = try db.internalCachedStatement(sql: sql) } try statement.setArguments(context.arguments) return PreparedRequest(statement: statement, adapter: adapter) } } extension SQLRequest: ExpressibleByStringInterpolation { public init(unicodeScalarLiteral: String) { self.init(sql: unicodeScalarLiteral) } public init(extendedGraphemeClusterLiteral: String) { self.init(sql: extendedGraphemeClusterLiteral) } /// Creates an `SQLRequest` from the given literal SQL string. public init(stringLiteral: String) { self.init(sql: stringLiteral) } public init(stringInterpolation sqlInterpolation: SQLInterpolation) { self.init(literal: SQL(stringInterpolation: sqlInterpolation)) } }
mit
8699b02feae104dd4b5c06910f8f4b99
31.114407
98
0.580683
4.401278
false
false
false
false
gokselkoksal/Lightning
Lightning/Sources/Components/WeakArray.swift
1
1145
// // WeakArray.swift // Lightning // // Created by Göksel Köksal on 22/11/2016. // Copyright © 2016 GK. All rights reserved. // import Foundation /// Array to keep elements weakly. public struct WeakArray<Element: AnyObject> { /// Array of weak elements. public var weakElements: [Weak<Element>] /// Creates a weak array with given elements. /// /// - Parameter elements: Initial elements. public init(elements: [Element] = []) { weakElements = elements.map({ Weak($0) }) } /// Wraps given object in `Weak` struct and appends it to `weakElements`. /// /// - Parameter object: Object to append weakly. public mutating func append(_ object: Element?) { guard let object = object else { return } weakElements.append(Weak(object)) } /// Removes wrappers with nil values from elements. public mutating func compact() { weakElements = weakElements.filter({ $0.value != nil }) } /// Reads elements stored in weak array. /// /// - Returns: Strong references to the elements. public func strongElements() -> [Element] { return weakElements.compactMap({ $0.value }) } }
mit
20201fcf142b4bf6c5ac8ccba3c2c72d
25.55814
75
0.65937
4.035336
false
false
false
false
Chris-Perkins/Lifting-Buddy
Lifting Buddy/WorkoutTableViewCell.swift
1
19524
// // WorkoutTableViewCell.swift // Lifting Buddy // // Created by Christopher Perkins on 9/4/17. // Copyright © 2017 Christopher Perkins. All rights reserved. // import UIKit import Realm import RealmSwift import CDAlertView class WorkoutTableViewCell: UITableViewCell { // MARK: View properties // These properties are used in determining the cell height for the tableview delegate public static let heightPerLabel: CGFloat = 40.0 public static let heightPerExercise: CGFloat = 40.0 // The workout associated with each cell private var workout: Workout? // The title for every cell private let cellTitle: UILabel // The fire image displayed by streak private let fireImage: UIImageView // The label saying how many days we're on streak private let streakLabel: UILabel // An indicator on whether or not the cell is expanded private let expandImage: UIImageView // Label stating how many times we've completed the displayed exercise private let completedLabel: UILabel // The labels for every exercise private var exerciseLabels: [LabelWithPrettyButtonView] // A delegate to show a view for us public var showViewDelegate: ShowViewDelegate? // The button stating whether or not we want to edit this workout private var editButton: PrettyButton? // A button to start the workout private var startWorkoutButton: PrettyButton? // The exercises this cell has private var exercises = List<Exercise>() // Whether or not this workout requires attention for some reason public var workoutRequiresAttention: Bool = false // MARK: View inits override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { cellTitle = UILabel() fireImage = UIImageView(image: #imageLiteral(resourceName: "Fire")) streakLabel = UILabel() expandImage = UIImageView(image: #imageLiteral(resourceName: "DownArrow")) exerciseLabels = [LabelWithPrettyButtonView]() completedLabel = UILabel() super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none addSubview(cellTitle) addSubview(fireImage) addSubview(streakLabel) addSubview(expandImage) createAndActivateCellTitleConstraints() createAndActivateExpandImageConstraints() createAndActivateStreakLabelConstraints() createAndActivateFireImageConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: View overrides override func layoutSubviews() { super.layoutSubviews() if workout?.isInvalidated == true { return } clipsToBounds = true cellTitle.textColor = .niceBlue cellTitle.textAlignment = .left completedLabel.textAlignment = .center // Don't show the streak if there is no streak if workout != nil && workout!.getCurSteak() > 0 { streakLabel.text = String(describing: workout!.getCurSteak()) streakLabel.textColor = .niceRed streakLabel.alpha = 1 fireImage.alpha = 1 } else { streakLabel.alpha = 0 fireImage.alpha = 0 } // Only layout if selected as they won't be visible if isSelected { editButton?.setDefaultProperties() editButton?.backgroundColor = (workout?.canModifyCoreProperties ?? true) ? .niceBlue : .niceLightBlue editButton?.setTitle("Edit", for: .normal) startWorkoutButton?.setDefaultProperties() startWorkoutButton?.setTitle(NSLocalizedString("Button.StartWO", comment: ""), for: .normal) } if (!workoutRequiresAttention) { backgroundColor = isSelected ? .lightestBlackWhiteColor : .primaryBlackWhiteColor setLabelTextColorsTo(color: .niceBlue, streakLabelColor: .niceRed) } // If the last time we did this workout was today... else if let dateLastDone = workout?.getDateLastDone(), Calendar.current.isDateInToday(dateLastDone) { backgroundColor = .niceGreen setLabelTextColorsTo(color: .white) } else { backgroundColor = .niceLightRed setLabelTextColorsTo(color: .white) } for (index, exerciseLabel) in exerciseLabels.enumerated() { exerciseLabel.backgroundColor = UIColor.oppositeBlackWhiteColor.withAlphaComponent(index&1 == 0 ? 0.05 : 0.1) exerciseLabel.button.setDefaultProperties() exerciseLabel.label.textAlignment = .left } } // MARK: view functions // Update selected status; v image becomes ^ public func updateSelectedStatus() { expandImage.transform = CGAffineTransform(scaleX: 1, y: isSelected ? -1 : 1) layoutIfNeeded() } // Removes views that have positions depend on the exercise labels private func removeExerciseDependentViews() { for exerciseLabel in exerciseLabels { exerciseLabel.removeFromSuperview() } editButton?.removeFromSuperview() startWorkoutButton?.removeFromSuperview() completedLabel.removeFromSuperview() } public func setLabelTextColorsTo(color: UIColor, streakLabelColor: UIColor? = nil) { cellTitle.textColor = color streakLabel.textColor = streakLabelColor ?? color // Only bother modifying views if they can be seen for performance if isSelected { completedLabel.textColor = color for exerciseLabel in exerciseLabels { exerciseLabel.label.textColor = color } } } // MARK: Encapsulated methods // Set the workout for this cell public func setWorkout(workout: Workout) { removeExerciseDependentViews() exerciseLabels.removeAll() if workout.isInvalidated { cellTitle.text = "<DELETED>" self.workout = nil return } cellTitle.text = workout.getName() self.workout = workout editButton = PrettyButton() startWorkoutButton = PrettyButton() editButton?.addTarget(self, action: #selector(buttonPress(sender:)), for: .touchUpInside) startWorkoutButton?.addTarget(self, action: #selector(buttonPress(sender:)), for: .touchUpInside) addSubview(editButton!) addSubview(startWorkoutButton!) // Previous view var prevView: UIView = cellTitle exercises = workout.getExercises() for (index, exercise) in exercises.enumerated() { let exerciseView = LabelWithPrettyButtonView() addSubview(exerciseView) exerciseLabels.append(exerciseView) exerciseView.label.text = exercise.getName()! exerciseView.button.setTitle(NSLocalizedString("Button.View", comment: ""), for: .normal) exerciseView.button.tag = index exerciseView.button.addTarget(self, action: #selector(labelButtonPress(sender:)), for: .touchUpInside) createAndActivateViewBelowViewConstraints(view: exerciseView, belowView: prevView, withHeight: WorkoutTableViewCell.heightPerExercise) prevView = exerciseView } addSubview(completedLabel) createAndActivateViewBelowViewConstraints(view: completedLabel, belowView: prevView, withHeight: WorkoutTableViewCell.heightPerLabel) prevView = completedLabel completedLabel.text = workout.getCompletedCount() == 0 ? "Workout not yet completed" : "Completed \(workout.getCompletedCount()) times" createAndActivateStartEditWorkoutButtonConstraints(belowView: prevView) layoutSubviews() } // Returns this workout public func getWorkout() -> Workout? { return workout } // MARK: Event functions @objc func labelButtonPress(sender: PrettyButton) { guard let exercise = workout?.getExercises()[sender.tag] else { fatalError("Workout either nil or exercise out of bounds!") } (viewContainingController() as? ExerciseDisplayer)?.displayExercise(exercise) } // Notified on a button press @objc func buttonPress(sender: UIButton) { switch(sender) { case startWorkoutButton!: guard let mainViewController = viewContainingController() as? MainViewController else { fatalError("view controller is now main view controller?") } mainViewController.startSession(workout: workout, exercise: nil) case editButton!: if workout?.canModifyCoreProperties ?? true { let createWorkoutView = CreateWorkoutView(workout: workout!, frame: .zero) createWorkoutView.showViewDelegate = showViewDelegate showViewDelegate?.showView(createWorkoutView) } else { let alert = CDAlertView(title: NSLocalizedString("Message.CannotEditWorkout.Title", comment: ""), message: NSLocalizedString("Message.CannotEditWorkout.Desc", comment: ""), type: CDAlertViewType.error) alert.add(action: CDAlertViewAction(title: NSLocalizedString("Button.OK", comment: ""), font: nil, textColor: UIColor.white, backgroundColor: UIColor.niceBlue, handler: nil)) alert.show() } default: fatalError("User pressed a button that does not exist?") } } // MARK: Constraint functions // Below view top ; cling to left of view ; to the right of the fire image ; height of default height private func createAndActivateCellTitleConstraints() { cellTitle.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: cellTitle, withCopyView: self, attribute: .top).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: cellTitle, withCopyView: self, attribute: .left, plusConstant: 10).isActive = true NSLayoutConstraint(item: fireImage, attribute: .left, relatedBy: .equal, toItem: cellTitle, attribute: .right, multiplier: 1, constant: 5).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: cellTitle, height: UITableViewCell.defaultHeight).isActive = true } // Width 16 ; height 8.46 ; center in this view ; 10 pixels from the right. private func createAndActivateExpandImageConstraints() { expandImage.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createWidthConstraintForView(view: expandImage, width: 16).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: expandImage, height: 8.46).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: expandImage, withCopyView: self, attribute: .top, plusConstant: 20.77).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: expandImage, withCopyView: self, attribute: .right, plusConstant: -10).isActive = true } // Width of 72 ; height of 20 ; 15 from top ; cling to expand image's left side private func createAndActivateStreakLabelConstraints() { streakLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createWidthConstraintForView(view: streakLabel, width: 72).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: streakLabel, height: 20).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: streakLabel, withCopyView: self, attribute: .top, plusConstant: 15).isActive = true NSLayoutConstraint(item: expandImage, attribute: .left, relatedBy: .equal, toItem: streakLabel, attribute: .right, multiplier: 1, constant: -10).isActive = true } // Width/height of 25 ; 12.5 from top ; cling to streak label's left side private func createAndActivateFireImageConstraints() { fireImage.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createWidthConstraintForView(view: fireImage, width: 25).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: fireImage, height: 25).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: fireImage, withCopyView: self, attribute: .top, plusConstant: 12.5).isActive = true NSLayoutConstraint(item: streakLabel, attribute: .left, relatedBy: .equal, toItem: fireImage, attribute: .right, multiplier: 1, constant: 0).isActive = true } // Cling below belowView, left and right of self - 20 ; height of height private func createAndActivateViewBelowViewConstraints(view: UIView, belowView: UIView, withHeight height: CGFloat) { view.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewBelowViewConstraint(view: view, belowView: belowView).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: view, height: height).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: view, withCopyView: self, attribute: .left, plusConstant: 20).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: view, withCopyView: self, attribute: .right, plusConstant: -20).isActive = true } // clings below previous view ; width of this view ; height of prettybutton's default button private func createAndActivateStartEditWorkoutButtonConstraints(belowView: UIView) { editButton?.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewBelowViewConstraint(view: editButton!, belowView: belowView).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: editButton!, height: PrettyButton.defaultHeight).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: editButton!, withCopyView: self, attribute: .left).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: editButton!, withCopyView: self, attribute: .width, multiplier: 0.5).isActive = true startWorkoutButton?.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewBelowViewConstraint(view: startWorkoutButton!, belowView: belowView).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: startWorkoutButton!, height: PrettyButton.defaultHeight).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: startWorkoutButton!, withCopyView: self, attribute: .right).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: startWorkoutButton!, withCopyView: self, attribute: .width, multiplier: 0.5).isActive = true } }
mit
2591deafe82b1f8990cd6ea3c7063546
45.044811
111
0.533934
6.854986
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/Settings/Coordinators/AddCustomNetworkCoordinator.swift
1
1638
// Copyright DApps Platform Inc. All rights reserved. import Foundation import UIKit protocol AddCustomNetworkCoordinatorDelegate: class { func didAddNetwork(network: CustomRPC, in coordinator: AddCustomNetworkCoordinator) func didCancel(in coordinator: AddCustomNetworkCoordinator) } final class AddCustomNetworkCoordinator: Coordinator { let navigationController: NavigationController var coordinators: [Coordinator] = [] weak var delegate: AddCustomNetworkCoordinatorDelegate? lazy var addNetworkItem: UIBarButtonItem = { return UIBarButtonItem( barButtonSystemItem: .add, target: self, action: #selector(addNetwork) ) }() lazy var addCustomNetworkController: AddCustomNetworkViewController = { let controller = AddCustomNetworkViewController() controller.navigationItem.rightBarButtonItem = addNetworkItem return controller }() init( navigationController: NavigationController = NavigationController() ) { self.navigationController = navigationController self.navigationController.modalPresentationStyle = .formSheet } func start() { navigationController.viewControllers = [addCustomNetworkController] } @objc func addNetwork() { addCustomNetworkController.addNetwork { [weak self] result in guard let `self` = self else { return } switch result { case .success(let network): self.delegate?.didAddNetwork(network: network, in: self) case .failure: break } } } }
gpl-3.0
202021d2ec48bff2543c70ec2295780b
31.117647
87
0.686203
5.571429
false
false
false
false
mxcl/swift-package-manager
Sources/PackageGraph/DependencyResolver.swift
1
29563
/* This source file is part of the Swift.org open source project Copyright 2016 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import struct Utility.Version public enum DependencyResolverError: Error { /// The resolver was unable to find a solution to the input constraints. case unsatisfiable /// The resolver hit unimplemented functionality (used temporarily for test case coverage). // // FIXME: Eliminate this. case unimplemented } /// An abstract definition for a set of versions. public enum VersionSetSpecifier: Equatable { /// The universal set. case any /// The empty set. case empty /// A non-empty range of version. case range(Range<Version>) /// Compute the intersection of two set specifiers. public func intersection(_ rhs: VersionSetSpecifier) -> VersionSetSpecifier { switch (self, rhs) { case (.any, _): return rhs case (_, .any): return self case (.empty, _): return .empty case (_, .empty): return .empty case (.range(let lhs), .range(let rhs)): let start = Swift.max(lhs.lowerBound, rhs.lowerBound) let end = Swift.min(lhs.upperBound, rhs.upperBound) if start < end { return .range(start..<end) } else { return .empty } default: // FIXME: Compiler should be able to prove this? https://bugs.swift.org/browse/SR-2221 fatalError("not reachable") } } /// Check if the set contains a version. public func contains(_ version: Version) -> Bool { switch self { case .empty: return false case .range(let range): return range.contains(version) case .any: return true } } } public func ==(_ lhs: VersionSetSpecifier, _ rhs: VersionSetSpecifier) -> Bool { switch (lhs, rhs) { case (.any, .any): return true case (.any, _): return false case (.empty, .empty): return true case (.empty, _): return false case (.range(let lhs), .range(let rhs)): return lhs == rhs case (.range, _): return false } } /// An identifier which unambiguously references a package container. /// /// This identifier is used to abstractly refer to another container when /// encoding dependencies across packages. public protocol PackageContainerIdentifier: Hashable { } /// A container of packages. /// /// This is the top-level unit of package resolution, i.e. the unit at which /// versions are associated. /// /// It represents a package container (e.g., a source repository) which can be /// identified unambiguously and which contains a set of available package /// versions and the ability to retrieve the dependency constraints for each of /// those versions. /// /// We use the "container" terminology here to differentiate between two /// conceptual notions of what the package is: (1) informally, the repository /// containing the package, but from which a package cannot be loaded by itself /// and (2) the repository at a particular version, at which point the package /// can be loaded and dependencies enumerated. /// /// This is also designed in such a way to extend naturally to multiple packages /// being contained within a single repository, should we choose to support that /// later. public protocol PackageContainer { /// The type of packages contained. associatedtype Identifier: PackageContainerIdentifier /// The identifier for the package. var identifier: Identifier { get } /// Get the list of versions which are available for the package. /// /// The list will be returned in sorted order, with the latest version last. /// /// This property is expected to be efficient to access, and cached by the /// client if necessary. // // FIXME: It is possible this protocol could one day be more efficient if it // returned versions more lazily, e.g., if we could fetch them iteratively // from the server. This might mean we wouldn't need to pull down as much // content. var versions: [Version] { get } /// Fetch the declared dependencies for a particular version. /// /// This property is expected to be efficient to access, and cached by the /// client if necessary. /// /// - Precondition: `versions.contains(version)` /// - Throws: If the version could not be resolved; this will abort /// dependency resolution completely. // // FIXME: We should perhaps define some particularly useful error codes // here, so the resolver can handle errors more meaningfully. func getDependencies(at version: Version) throws -> [PackageContainerConstraint<Identifier>] } /// An interface for resolving package containers. public protocol PackageContainerProvider { associatedtype Container: PackageContainer /// Get the container for a particular identifier. /// /// - Throws: If the package container could not be resolved or loaded. func getContainer(for identifier: Container.Identifier) throws -> Container } /// An individual constraint onto a container. public struct PackageContainerConstraint<T: PackageContainerIdentifier> { public typealias Identifier = T /// The identifier for the container the constraint is on. public let identifier: Identifier /// The version requirements. public let versionRequirement: VersionSetSpecifier /// Create a constraint requiring the given `container` satisfying the /// `versionRequirement`. public init(container identifier: Identifier, versionRequirement: VersionSetSpecifier) { self.identifier = identifier self.versionRequirement = versionRequirement } } /// Delegate interface for dependency resoler status. public protocol DependencyResolverDelegate { associatedtype Identifier: PackageContainerIdentifier /// Called when a new container is being considered. func added(container identifier: Identifier) } /// A bound version for a package within an assignment. // // FIXME: This should be nested, but cannot be currently. enum BoundVersion: Equatable { /// The assignment should not include the package. /// /// This is different from the absence of an assignment for a particular /// package, which only indicates the assignment is agnostic to its /// version. This value signifies the package *may not* be present. case excluded /// The version of the package to include. case version(Version) } func ==(_ lhs: BoundVersion, _ rhs: BoundVersion) -> Bool { switch (lhs, rhs) { case (.excluded, .excluded): return true case (.excluded, _): return false case (.version(let lhs), .version(let rhs)): return lhs == rhs case (.version, _): return false } } /// A container for constraints for a set of packages. // // FIXME: Maybe each package should just return this, instead of a list of // `PackageContainerConstraint`s. That won't work if we decide this should // eventually map based on the `Container` rather than the `Identifier`, though, // so they are separate for now. struct PackageContainerConstraintSet<C: PackageContainer>: Collection { typealias Container = C typealias Identifier = Container.Identifier typealias Index = Dictionary<Identifier, VersionSetSpecifier>.Index typealias Element = Dictionary<Identifier, VersionSetSpecifier>.Element /// The set of constraints. private var constraints: [Identifier: VersionSetSpecifier] /// Create an empty constraint set. init() { self.constraints = [:] } /// Create an constraint set from known values. init(_ constraints: [Identifier: VersionSetSpecifier]) { self.constraints = constraints } /// The list of containers with entries in the set. var containerIdentifiers: AnySequence<Identifier> { return AnySequence<C.Identifier>(constraints.keys) } /// Get the version set associated with the given package `identifier`. subscript(identifier: Identifier) -> VersionSetSpecifier? { return constraints[identifier] } /// Merge the given version requirement for the container `identifier`. /// /// - Returns: False if the merger has made the set unsatisfiable; i.e. true /// when the resulting set is satisfiable, if it was already so. private mutating func merge(versionRequirement: VersionSetSpecifier, for identifier: Identifier) -> Bool { let intersection: VersionSetSpecifier if let existing = constraints[identifier] { intersection = existing.intersection(versionRequirement) } else { intersection = versionRequirement } constraints[identifier] = intersection return intersection != .empty } /// Merge the given `constraint`. /// /// - Returns: False if the merger has made the set unsatisfiable; i.e. true /// when the resulting set is satisfiable, if it was already so. mutating func merge(_ constraint: PackageContainerConstraint<Identifier>) -> Bool { return merge(versionRequirement: constraint.versionRequirement, for: constraint.identifier) } /// Merge the given constraint set. /// /// - Returns: False if the merger has made the set unsatisfiable; i.e. true /// when the resulting set is satisfiable, if it was already so. mutating func merge(_ constraints: PackageContainerConstraintSet<Container>) -> Bool { var satisfiable = true for (key, versionRequirement) in constraints { if !merge(versionRequirement: versionRequirement, for: key) { satisfiable = false } } return satisfiable } // MARK: Collection Conformance var startIndex: Index { return constraints.startIndex } var endIndex: Index { return constraints.endIndex } func index(after i: Index) -> Index { return constraints.index(after: i) } subscript(position: Index) -> Element { return constraints[position] } } /// A container for version assignments for a set of packages, exposed as a /// sequence of `Container` to `BoundVersion` bindings. /// /// This is intended to be an efficient data structure for accumulating a set of /// version assignments along with efficient access to the derived information /// about the assignment (for example, the unified set of constraints it /// induces). /// /// The set itself is designed to only ever contain a consistent set of /// assignments, i.e. each assignment should satisfy the induced /// `constraints`, but this invariant is not explicitly enforced. // // FIXME: Actually make efficient. struct VersionAssignmentSet<C: PackageContainer>: Sequence { typealias Container = C typealias Identifier = Container.Identifier /// The assignment records. // // FIXME: Does it really make sense to key on the identifier here. Should we // require referential equality of containers and use that to simplify? private var assignments: [Identifier: (container: Container, binding: BoundVersion)] /// Create an empty assignment. init() { assignments = [:] } /// The assignment for the given `container`. subscript(container: Container) -> BoundVersion? { get { return assignments[container.identifier]?.binding } set { // We disallow deletion. let newBinding = newValue! // Validate this is a valid assignment. assert(isValid(binding: newBinding, for: container)) assignments[container.identifier] = (container: container, binding: newBinding) } } /// Merge in the bindings from the given `assignment`. /// /// - Returns: False if the merge cannot be made (the assignments contain /// incompatible versions). mutating func merge(_ assignment: VersionAssignmentSet<Container>) -> Bool { // In order to protect the assignment set, we first have to test whether // the merged constraint sets are satisfiable. // // FIXME: Move to non-mutating methods with results, in order to have a // nice consistent API with `PackageContainerConstraintSet.merge`. // // FIXME: This is very inefficient; we should decide whether it is right // to handle it here or force the main resolver loop to handle the // discovery of this property. var mergedConstraints = constraints guard mergedConstraints.merge(assignment.constraints) else { return false } // The induced constraints are satisfiable, so we *can* union the // assignments without breaking our internal invariant on // satisfiability. for (container, binding) in assignment { if let existing = self[container] { if existing != binding { // NOTE: We are returning here with the data structure // partially updated, which feels wrong. See FIXME above. return false } } else { self[container] = binding } } return true } /// The combined version constraints induced by the assignment. /// /// This consists of the merged constraints which need to be satisfied on /// each package as a result of the versions selected in the assignment. /// /// The resulting constraint set is guaranteed to be non-empty for each /// mapping, assuming the invariants on the set are followed. // // FIXME: We need to cache this. var constraints: PackageContainerConstraintSet<Container> { // Collect all of the constraints. var result = PackageContainerConstraintSet<Container>() for (_, (container: container, binding: binding)) in assignments { switch binding { case .excluded: // If the package is excluded, it doesn't contribute. continue case .version(let version): // If we have a version, add the constraints from that package version. // // FIXME: We should cache this too, possibly at a layer // different than above (like the entry record). // // FIXME: Error handling, except that we probably shouldn't have // needed to refetch the dependencies at this point. for constraint in try! container.getDependencies(at: version) { let satisfiable = result.merge(constraint) assert(satisfiable) } } } return result } /// Check if the given `binding` for `container` is valid within the assignment. // // FIXME: This is currently very inefficient. func isValid(binding: BoundVersion, for container: Container) -> Bool { switch binding { case .excluded: // A package can be excluded if there are no constraints on the // package (it has not been requested by any other package in the // assignment). return constraints[container.identifier] == nil case .version(let version): // A version is valid if it is contained in the constraints, or there are no constraints. if let versionSet = constraints[container.identifier] { return versionSet.contains(version) } else { return true } } } /// Check if the assignment is valid and complete. func checkIfValidAndComplete() -> Bool { // Validity should hold trivially, because it is an invariant of the collection. for assignment in assignments.values { if !isValid(binding: assignment.binding, for: assignment.container) { return false } } // Check completeness, by simply looking at all the entries in the induced constraints. for identifier in constraints.containerIdentifiers { // Verify we have a non-excluded entry for this key. switch assignments[identifier]?.binding { case .version?: continue case .excluded?, nil: return false } } return true } // MARK: Sequence Conformance // FIXME: This should really be a collection, but that takes significantly // more work given our current backing collection. typealias Iterator = AnyIterator<(Container, BoundVersion)> func makeIterator() -> Iterator { var it = assignments.values.makeIterator() return AnyIterator{ if let next = it.next() { return (next.container, next.binding) } else { return nil } } } } /// A general purpose package dependency resolver. /// /// This is a general purpose solver for the problem of: /// /// Given an input list of constraints, where each constraint identifies a /// container and version requirements, and, where each container supplies a /// list of additional constraints ("dependencies") for an individual version, /// then, choose an assignment of containers to versions such that: /// /// 1. The assignment is complete: there exists an assignment for each container /// listed in the union of the input constraint list and the dependency list for /// every container in the assignment at the assigned version. /// /// 2. The assignment is correct: the assigned version satisfies each constraint /// referencing its matching container. /// /// 3. The assignment is maximal: there is no other assignment satisfying #1 and /// #2 such that all assigned version are greater than or equal to the versions /// assigned in the result. /// /// NOTE: It does not follow from #3 that this solver attempts to give an /// "optimal" result. There may be many possible solutions satisfying #1, #2, /// and #3, and optimality requires additional information (e.g. a /// prioritization among packages). /// /// As described, this problem is NP-complete (*). However, this solver does /// *not* currently attempt to solve the full NP-complete problem, rather it /// proceeds by first always attempting to choose the latest version of each /// container under consideration. However, if this version is unavailable due /// to the current choice of assignments, it will be rejected and no longer /// considered. /// /// This algorithm is sound (a valid solution satisfies the assignment /// guarantees above), but *incomplete*; it may fail to find a valid solution to /// a satisfiable input. /// /// (*) Via reduction from 3-SAT: Introduce a package for each variable, with /// two versions representing true and false. For each clause `C_n`, introduce a /// package `P(C_n)` representing the clause, with three versions; one for each /// satisfying assignment of values to a literal with the corresponding precise /// constraint on the input packages. Finally, construct an input constraint /// list including a dependency on each clause package `P(C_n)` and an /// open-ended version constraint. The given input is satisfiable iff the input /// 3-SAT instance is. public class DependencyResolver< P: PackageContainerProvider, D: DependencyResolverDelegate > where P.Container.Identifier == D.Identifier { public typealias Provider = P public typealias Delegate = D public typealias Container = Provider.Container public typealias Identifier = Container.Identifier /// The type of the constraints the resolver operates on. /// /// Technically this is a container constraint, but that is currently the /// only kind of constraints we operate on. public typealias Constraint = PackageContainerConstraint<Identifier> /// The type of constraint set the resolver operates on. typealias ConstraintSet = PackageContainerConstraintSet<Container> /// The type of assignment the resolver operates on. typealias AssignmentSet = VersionAssignmentSet<Container> /// The container provider used to load package containers. public let provider: Provider /// The resolver's delegate. public let delegate: Delegate public init(_ provider: Provider, _ delegate: Delegate) { self.provider = provider self.delegate = delegate } /// Execute the resolution algorithm to find a valid assignment of versions. /// /// - Parameters: /// - constraints: The contraints to solve. /// - Returns: A satisfying assignment of containers and versions. /// - Throws: DependencyResolverError, or errors from the underlying package provider. public func resolve(constraints: [Constraint]) throws -> [(container: Identifier, version: Version)] { // Create an assignment for the input constraints. guard let assignment = try merge( constraints: constraints, into: AssignmentSet(), subjectTo: ConstraintSet(), excluding: [:]) else { throw DependencyResolverError.unsatisfiable } return assignment.map { (container, binding) in guard case .version(let version) = binding else { fatalError("unexpected exclude binding") } return (container: container.identifier, version: version) } } /// Resolve an individual container dependency tree. /// /// This is the primary method in our bottom-up algorithm for resolving /// dependencies. The inputs define an active set of constraints and set of /// versions to exclude (conceptually the latter could be merged with the /// former, but it is convenient to separate them in our /// implementation). The result is an assignment for this container's /// subtree. /// /// - Parameters: /// - container: The container to resolve. /// - constraints: The external constraints which must be honored by the solution. /// - exclusions: The list of individually excluded package versions. /// - Returns: A sequence of feasible solutions, starting with the most preferable. /// - Throws: Only rethrows errors from the container provider. // // FIXME: This needs to a way to return information on the failure, or we // will need to have it call the delegate directly. // // FIXME: @testable private func resolveSubtree( _ container: Container, subjectTo allConstraints: ConstraintSet, excluding allExclusions: [Identifier: Set<Version>] ) throws -> AssignmentSet? { func validVersions(_ container: Container) -> AnyIterator<Version> { let constraints = allConstraints[container.identifier] ?? .any let exclusions = allExclusions[container.identifier] ?? Set() var it = container.versions.reversed().makeIterator() return AnyIterator { () -> Version? in while let version = it.next() { if constraints.contains(version) && !exclusions.contains(version) { return version } } return nil } } // Attempt to select each valid version in order. // // FIXME: We must detect recursion here. for version in validVersions(container) { // Create an assignment for this container and version. var assignment = AssignmentSet() assignment[container] = .version(version) // Get the constraints for this container version and update the // assignment to include each one. if let result = try merge( constraints: try container.getDependencies(at: version), into: assignment, subjectTo: allConstraints, excluding: allExclusions) { // We found a complete valid assignment. assert(result.checkIfValidAndComplete()) return result } } // We were unable to find a valid solution. return nil } /// Solve the `constraints` and merge the results into the `assignment`. /// /// - Parameters: /// - constraints: The input list of constraints to solve. /// - assignment: The assignment to merge the result into. /// - allConstraints: An additional set of constraints on the viable solutions. /// - allExclusions: A set of package assignments to exclude from consideration. /// - Returns: A satisfying assignment, if solvable. private func merge( constraints: [Constraint], into assignment: AssignmentSet, subjectTo allConstraints: ConstraintSet, excluding allExclusions: [Identifier: Set<Version>] ) throws -> AssignmentSet? { var assignment = assignment var allConstraints = allConstraints // Update the active constraint set to include all active constraints. // // We want to put all of these constraints in up front so that we are // more likely to get back a viable solution. // // FIXME: We should have a test for this, probably by adding some kind // of statistics on the number of backtracks. for constraint in constraints { if !allConstraints.merge(constraint) { return nil } } for constraint in constraints { // Get the container. // // Failures here will immediately abort the solution, although in // theory one could imagine attempting to find a solution not // requiring this container. It isn't clear that is something we // would ever want to handle at this level. // // FIXME: We want to ask for all of these containers up-front to // allow for async cloning. let container = try getContainer(for: constraint.identifier) // Solve for an assignment with the current constraints. guard let subtreeAssignment = try resolveSubtree( container, subjectTo: allConstraints, excluding: allExclusions) else { // If we couldn't find an assignment, we need to backtrack in some way. throw DependencyResolverError.unimplemented } // We found a valid assignment, attempt to merge it with the current solution. // // FIXME: It is rather important, subtle, and confusing that this // `merge` doesn't mutate the assignment but the one on the // constraint set does. We should probably make them consistent. guard assignment.merge(subtreeAssignment) else { // The assignment couldn't be merged with the current // assignment, or the constraint sets couldn't be merged. // // This happens when (a) the subtree has a package overlapping // with a previous subtree assignment, and (b) the subtrees // needed to resolve different versions due to constraints not // present in the top-down constraint set. throw DependencyResolverError.unimplemented } // Merge the working constraint set. // // This should always be feasible, because all prior constraints // were part of the input constraint request (see comment around // initial `merge` outside the loop). let mergable = allConstraints.merge(subtreeAssignment.constraints) precondition(mergable) } return assignment } // MARK: Container Management /// The active set of managed containers. private var containers: [Identifier: Container] = [:] /// Get the container for the given identifier, loading it if necessary. private func getContainer(for identifier: Identifier) throws -> Container { // Return the cached container, if available. if let container = containers[identifier] { return container } // Otherwise, load it. return try addContainer(for: identifier) } /// Add a managed container. // // FIXME: In order to support concurrent fetching of dependencies, we need // to have some measure of asynchronicity here. private func addContainer(for identifier: Identifier) throws -> Container { assert(!containers.keys.contains(identifier)) let container = try provider.getContainer(for: identifier) containers[identifier] = container // Validate the versions in the container. let versions = container.versions assert(versions.sorted() == versions, "container versions are improperly ordered") // Inform the delegate we are considering a new container. delegate.added(container: identifier) return container } }
apache-2.0
801bd4cbbf7d5083b531c5c25882017b
38.208223
110
0.651321
5.120908
false
false
false
false
ctime95/AJMListApp
AJMListApp/AJMCircularLayout.swift
1
3222
// // AJMCircularLayout.swift // AJMListApp // // Created by Angel Jesse Morales Karam Kairuz on 07/09/17. // Copyright © 2017 TheKairuzBlog. All rights reserved. // import UIKit class CircularCollectionViewLayoutAttributes : UICollectionViewLayoutAttributes { var anchorPoint = CGPoint(x: 0.5, y: 0.5) var angle : CGFloat = 0 { didSet { zIndex = Int(angle * 1000000) transform = CGAffineTransform(rotationAngle: angle) } } override func copy(with zone: NSZone? = nil) -> Any { let copiedAttributes: CircularCollectionViewLayoutAttributes = super.copy(with: zone) as! CircularCollectionViewLayoutAttributes copiedAttributes.anchorPoint = self.anchorPoint copiedAttributes.angle = self.angle return copiedAttributes } } class AJMCircularLayout: UICollectionViewLayout { let itemSize = CGSize(width: 300, height: 300) var attributesList = [CircularCollectionViewLayoutAttributes]() var radius : CGFloat = 500 { didSet { invalidateLayout() } } var anglePerItem : CGFloat { return atan(itemSize.width / 200) } var angleAtExtreme: CGFloat { return collectionView!.numberOfItems(inSection: 0) > 0 ? -CGFloat(collectionView!.numberOfItems(inSection: 0) - 1) * anglePerItem : 0 } var angle: CGFloat { return angleAtExtreme * collectionView!.contentOffset.x / (collectionViewContentSize.width - collectionView!.bounds.width) } override var collectionViewContentSize: CGSize { return CGSize(width: CGFloat(collectionView!.numberOfItems(inSection: 0)) * itemSize.width, height: collectionView!.bounds.height) } override class var layoutAttributesClass: Swift.AnyClass { return CircularCollectionViewLayoutAttributes.self } override func prepare() { super.prepare() let centerX = collectionView!.contentOffset.x + (collectionView!.bounds.width / 2.0) let anchorPointY = ((itemSize.height / 2.0) + radius) / itemSize.height attributesList = (0..<collectionView!.numberOfItems(inSection: 0)).map { (i) -> CircularCollectionViewLayoutAttributes in // 1 let attributes = CircularCollectionViewLayoutAttributes(forCellWith: IndexPath(item: i, section: 0)) attributes.size = self.itemSize attributes.anchorPoint = CGPoint(x: 0.5, y: anchorPointY) // 2 attributes.center = CGPoint(x: centerX, y: self.collectionView!.bounds.midY) // 3 attributes.angle = self.angle + (self.anglePerItem * CGFloat(i)) return attributes } } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return attributesList } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return attributesList[indexPath.row] } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } }
mit
c8d9620b90c18e68d3caf471f5e2facc
30.578431
138
0.651971
5.048589
false
false
false
false
FabrizioBrancati/SwiftyBot
Sources/Telegram/Response/Response.swift
1
4708
// // Response.swift // SwiftyBot // // The MIT License (MIT) // // Copyright (c) 2016 - 2019 Fabrizio Brancati. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import BFKit import Foundation import Vapor /// Telegram response public struct Response: Codable { /// Response method. public enum Method: String, Codable { /// Send message method. case sendMessage } /// Response method. public private(set) var method: Method /// Response chat ID. public private(set) var chatID: Int /// Response text. public private(set) var text: String /// Coding keys, used by Codable protocol. private enum CodingKeys: String, CodingKey { case method case chatID = "chat_id" case text } } // MARK: - Response Extension /// Response extension. public extension Response { /// Declared in an extension to not override default `init` function. /// /// - Parameter request: Message request. /// - Throws: Decoding errors. init(for request: Vapor.Request) throws { /// Decode the request. let messageRequest = try request.content.syncDecode(Request.self) /// Creates the initial response, with a default message for empty user's message. method = .sendMessage chatID = messageRequest.message.chat.id text = "I'm sorry but your message is empty 😢" /// Check if the message is not empty if !messageRequest.message.text.isEmpty { /// Check if it's a command. if messageRequest.message.text.hasPrefix("/") { /// Check if it's a `start` command. if let command = Command(messageRequest.message.text), command.command == "start" { text = """ Welcome to SwiftyBot \(messageRequest.message.from.firstName)! To list all available commands type /help """ /// Check if it's a `help` command. } else if let command = Command(messageRequest.message.text), command.command == "help" { text = """ Welcome to SwiftyBot, an example on how to create a Telegram bot with Swift using Vapor. https://www.fabriziobrancati.com/SwiftyBot /start - Welcome message /help - Help message Any text - Returns the reversed message """ /// It's not a valid command. } else { text = """ Unrecognized command. To list all available commands type /help """ } /// It's a normal message, so reverse it. } else { text = messageRequest.message.text.reversed(preserveFormat: true) } } } } // MARK: - Response Handling /// Response extension. public extension Response { /// Create a response for a request. /// /// - Parameter request: Telegram request. /// - Returns: Returns the message `HTTPResponse`. /// - Throws: Decoding errors. func create(on request: Vapor.Request) throws -> HTTPResponse { /// Create the JSON response. /// More info [here](https://core.telegram.org/bots/api#sendmessage). var httpResponse = HTTPResponse(status: .ok, headers: ["Content-Type": "application/json"]) /// Encode the response. try JSONEncoder().encode(self, to: &httpResponse, on: request.eventLoop) return httpResponse } }
mit
4cf604a522181d6653374712e69e9587
37.252033
108
0.610202
4.791242
false
false
false
false
MHaroonBaig/Swift-JumpStart
Advanced.playground/section-1.swift
1
4939
// Playground - noun: a place where people can play import UIKit // Type Checking var button = UIButton() var barButton = UIBarButtonItem() var dialog = UIAlertView() var objects: [Any] objects = [button, barButton, dialog] for i in objects{ /* There are many ways to extract the type from as? and then force unwrapping it. But, using if let makes our task easy as it automatically force unwraps all the things for us. We dont have to worry about 'nil' too. A magic indeed. */ if let item = i as? UIAlertView{ println("This is an alert instance") } if let item = i as? UIBarButtonItem { println("This is a bar button instance") } if let items = i as? UIButton { println("This is an instance of a button") } } // AnyObjects and Any var someValue: Any someValue = "Hello this is Any type object" someValue = 66 /* Here we apply the type check to the variable 'somValue'. If it's a String, do some String operations. Or else, display the value. We can store anything in a variable if it's declared with the 'AnyObject' or 'Any' type. */ if (someValue is String){ var someValue2 = someValue as String // If we were using AnyObject, we wouldnt do this. Example Given below var wordsArray = someValue2.componentsSeparatedByString(" ") } else { println("Wasn't a String so displaying the value. The value is \(someValue)") } var anyValue: AnyObject anyValue = "This is another String but this time we're using AnyObject instead of Any" anyValue = 90 if (anyValue is String){ var hipHop = anyValue.componentsSeparatedByString(" ") } else{ println(anyValue) } // Protocols /* marking this protocol with @objc makes sure that this protocol contains optional functions which a class ight not require. This protocol with the attribute @objc is only applicable to classes. To use it with structures, remove that attribute. */ @objc protocol myProtocol { /* In protocols, we just have to write the function's name, parameters and the return type, which we want our class to implement */ func display (name:String) -> String // A class which conforms to this protocol might not want to implement that function. optional func optionalFunc (name:String) -> Int // We specify either the property should be read-only or read-write computed property. var someProperty: Int { get } // read-only Computed Property } class myClass: myProtocol { /* Do whatever we want here in this class but as we extended the protocol, we must fulfill the needs, i.e. impplement all the things specified in the protocol. We aren't bound to implement functions which are marked as optionals. */ func display (name:String) -> String { return ("hey \(name), We've implemented a protocol method, yayy!") } var someProperty:Int { return 90 } } var myObject = myClass() myObject.display("Haroon") myObject.someProperty // Extensions extension String { // Here, we will add a method to the String data type for more productivity. func reverseWords () -> String { var wordsArray = self.componentsSeparatedByString(" ") wordsArray = wordsArray.reverse() var combineString:String = " " for i in wordsArray { combineString += i + " " } return combineString } // A function which returns the length of a String. func len() -> Int { var count: Int = 0 for i in self{ count++ } return count } } var myString = "Hello I am Haroon" myString.len() myString.reverseWords() extension Int { // Extending the Int thing. func display () { println(self) } func isEven () -> Bool { if (self%2 == 0){ return true } else{ return false } } func isOdd () -> Bool { if (self%2 == 0){ return false } else{ return true } } } var someInt: Int someInt = 9 someInt.display() someInt.isEven() someInt.isOdd() // Extending the Arrays extension Array { func display () { for i in self { print(i) print(" ") } println() } } var intArray = [1,2,3,4,5,6] intArray.display() // Generics /* They automaticaly inferrs the type. We don't have to check manually through 'as?' or any downcasting etc. They are much more like Any or AnyObject but they are intelligent enough to inferr the type. */ func printArray <T> (array: [T]) -> Int{ var count :Int = 0 for i in array{ print(i) print(" ") count++ } println() return count++ } var arrayInt = [1,2,3,4,5,6,7] var arrayString = ["ab", "cd", "ef", "gh"] printArray(arrayInt) printArray(arrayString)
cc0-1.0
000c603d8715b79c1eb8d394907d63ab
21.655963
204
0.631099
4.143456
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Components/ThumbnailView/ThumbnailView.swift
1
1043
// Copyright © Blockchain Luxembourg S.A. All rights reserved. public final class ThumbnailView: UIView { // MARK: - Injected public var viewModel: ThumbnailViewModel! { didSet { guard let viewModel = viewModel else { return } imageView.set(viewModel.imageViewContent) backgroundColor = viewModel.backgroundColor } } // MARK: - UI Properties private let imageView: UIImageView! // MARK: - Setup public init(edge: CGFloat) { imageView = UIImageView() let size = CGSize(edge: edge) super.init(frame: .init(origin: .zero, size: size)) clipsToBounds = true layer.cornerRadius = edge / 2 imageView.addSubview(imageView) imageView.layoutToSuperview(.centerX, .centerY) imageView.layoutToSuperview(.width, .height, ratio: 0.86) layout(size: size) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
lgpl-3.0
e09088eec0fdbfdcffb8f4fc5ceb0fbb
27.162162
65
0.62572
4.714932
false
false
false
false
InsectQY/HelloSVU_Swift
HelloSVU_Swift/Classes/Module/Map/Search/View/MaxInteritemSpacingFlowLayout.swift
1
1465
// // MaxInteritemSpacingFlowLayout.swift // HelloSVU_Swift // // Created by Insect on 2017/10/14. // Copyright © 2017年 Insect. All rights reserved. // import UIKit class MaxInteritemSpacingFlowLayout: UICollectionViewFlowLayout { var maximumInteritemSpacing: CGFloat = 8.0 override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let attributes = super.layoutAttributesForElements(in: rect) if let attributes = attributes { //第0个 cell 没有上一个 cell,所以从1开始 for i in 1 ..< attributes.count { let curAttr = attributes[i] let preAttr = attributes[i - 1] let origin = preAttr.frame.maxX //根据 maximumInteritemSpacing 计算出的新的 x 位置 let targetX = origin + maximumInteritemSpacing // 只有系统计算的间距大于 maximumInteritemSpacing 时才进行调整 if curAttr.frame.maxX > targetX { if targetX + curAttr.frame.width < collectionViewContentSize.width { var frame = curAttr.frame frame.origin.x = targetX curAttr.frame = frame } } } } return attributes } }
apache-2.0
618e8db8ffbffa5843fe74517424d155
31.904762
103
0.544139
5.335907
false
false
false
false
CoderST/XMLYDemo
XMLYDemo/XMLYDemo/Class/Home/Controller/SubViewController/ListViewController/View/FocusView.swift
1
1089
// // FocusCell.swift // XMLYDemo // // Created by xiudou on 2016/12/27. // Copyright © 2016年 CoderST. All rights reserved. // import UIKit class FocusView: UIView { fileprivate lazy var iconImageView : UIImageView = { let iconImageView = UIImageView() iconImageView.contentMode = .scaleAspectFill iconImageView.clipsToBounds = true return iconImageView }() var focusModel : FocusModel?{ didSet{ guard let focusModel = focusModel else { return } iconImageView.sd_setImage( with: URL(string: focusModel.pic ), placeholderImage: UIImage(named: "placeholder_image")) } } override init(frame: CGRect) { super.init(frame: frame) addSubview(iconImageView) iconImageView.snp.makeConstraints { (make) in make.left.top.bottom.right.equalTo(self) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
6be9e16bfc6c245de7b7ae0020a50897
22.106383
129
0.589319
4.848214
false
false
false
false
vector-im/riot-ios
Riot/Modules/Settings/Discovery/ThreePidDetails/SettingsDiscoveryThreePidDetailsViewController.swift
1
11489
// File created from ScreenTemplate // $ createScreen.sh Details SettingsDiscoveryThreePidDetails /* Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit final class SettingsDiscoveryThreePidDetailsViewController: UIViewController { // MARK: - Properties // MARK: Outlets @IBOutlet private weak var scrollView: UIScrollView! @IBOutlet private weak var threePidBackgroundView: UIView! @IBOutlet private weak var threePidTitleLabel: UILabel! @IBOutlet private weak var threePidAdressLabel: UILabel! @IBOutlet private weak var operationButton: UIButton! @IBOutlet private weak var informationLabel: UILabel! // MARK: Private private var viewModel: SettingsDiscoveryThreePidDetailsViewModelType! private var theme: Theme! private var keyboardAvoider: KeyboardAvoider? private var errorPresenter: MXKErrorPresentation! private var activityPresenter: ActivityIndicatorPresenter! private weak var presentedAlertController: UIAlertController? private var displayMode: SettingsDiscoveryThreePidDetailsDisplayMode? // MARK: - Setup class func instantiate(with viewModel: SettingsDiscoveryThreePidDetailsViewModelType) -> SettingsDiscoveryThreePidDetailsViewController { let viewController = StoryboardScene.SettingsDiscoveryThreePidDetailsViewController.initialScene.instantiate() viewController.viewModel = viewModel viewController.theme = ThemeService.shared().theme return viewController } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setupViews() self.keyboardAvoider = KeyboardAvoider(scrollViewContainerView: self.view, scrollView: self.scrollView) self.activityPresenter = ActivityIndicatorPresenter() self.errorPresenter = MXKErrorAlertPresentation() self.registerThemeServiceDidChangeThemeNotification() self.update(theme: self.theme) self.viewModel.viewDelegate = self self.viewModel.process(viewAction: .load) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.keyboardAvoider?.startAvoiding() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.keyboardAvoider?.stopAvoiding() } override var preferredStatusBarStyle: UIStatusBarStyle { return self.theme.statusBarStyle } // MARK: - Private private func update(theme: Theme) { self.theme = theme self.view.backgroundColor = theme.headerBackgroundColor if let navigationBar = self.navigationController?.navigationBar { theme.applyStyle(onNavigationBar: navigationBar) } self.threePidBackgroundView.backgroundColor = theme.backgroundColor self.threePidTitleLabel.textColor = theme.textPrimaryColor self.threePidAdressLabel.textColor = theme.textSecondaryColor self.informationLabel.textColor = theme.textSecondaryColor self.operationButton.backgroundColor = theme.backgroundColor theme.applyStyle(onButton: self.operationButton) } private func registerThemeServiceDidChangeThemeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil) } @objc private func themeDidChange() { self.update(theme: ThemeService.shared().theme) } private func setupViews() { self.scrollView.keyboardDismissMode = .interactive self.render(threePid: self.viewModel.threePid) } private func render(threePid: MX3PID) { let title: String let threePidTitle: String let informationText: String let formattedThreePid: String switch threePid.medium { case .email: title = VectorL10n.settingsDiscoveryThreePidDetailsTitleEmail threePidTitle = VectorL10n.settingsEmailAddress informationText = VectorL10n.settingsDiscoveryThreePidDetailsInformationEmail formattedThreePid = threePid.address case .msisdn: title = VectorL10n.settingsDiscoveryThreePidDetailsTitlePhoneNumber threePidTitle = VectorL10n.settingsPhoneNumber informationText = VectorL10n.settingsDiscoveryThreePidDetailsInformationPhoneNumber formattedThreePid = MXKTools.readableMSISDN(threePid.address) default: title = "" threePidTitle = "" informationText = "" formattedThreePid = "" } self.title = title self.threePidTitleLabel.text = threePidTitle self.threePidAdressLabel.text = formattedThreePid self.informationLabel.text = informationText } private func render(viewState: SettingsDiscoveryThreePidDetailsViewState) { switch viewState { case .loading: self.renderLoading() case .loaded(displayMode: let displayMode): self.renderLoaded(displayMode: displayMode) case .error(let error): self.render(error: error) } } private func renderLoaded(displayMode: SettingsDiscoveryThreePidDetailsDisplayMode) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) let operationButtonTitle: String? let operationButtonColor: UIColor? let operationButtonEnabled: Bool self.presentedAlertController?.dismiss(animated: false, completion: nil) switch displayMode { case .share: operationButtonTitle = VectorL10n.settingsDiscoveryThreePidDetailsShareAction operationButtonColor = self.theme.tintColor operationButtonEnabled = true case .revoke: operationButtonTitle = VectorL10n.settingsDiscoveryThreePidDetailsRevokeAction operationButtonColor = self.theme.warningColor operationButtonEnabled = true case .pendingThreePidVerification: switch self.viewModel.threePid.medium { case .email: self.presentPendingEmailVerificationAlert() case .msisdn: self.presentPendingMSISDNVerificationAlert() default: break } operationButtonTitle = nil operationButtonColor = nil operationButtonEnabled = false } if let operationButtonTitle = operationButtonTitle { self.operationButton.setTitle(operationButtonTitle, for: .normal) } if let operationButtonColor = operationButtonColor { self.operationButton.setTitleColor(operationButtonColor, for: .normal) } self.operationButton.isEnabled = operationButtonEnabled self.displayMode = displayMode } private func renderLoading() { if self.activityPresenter.isPresenting == false { self.activityPresenter.presentActivityIndicator(on: self.view, animated: true) } self.operationButton.isEnabled = false } private func render(error: Error) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.errorPresenter.presentError(from: self, forError: error, animated: true, handler: { self.viewModel.process(viewAction: .cancelThreePidValidation) }) self.operationButton.isEnabled = true } private func presentPendingEmailVerificationAlert() { let alert = UIAlertController(title: Bundle.mxk_localizedString(forKey: "account_email_validation_title"), message: Bundle.mxk_localizedString(forKey: "account_email_validation_message"), preferredStyle: .alert) alert.addAction(UIAlertAction(title: VectorL10n.continue, style: .default, handler: { _ in self.viewModel.process(viewAction: .confirmEmailValidation) })) alert.addAction(UIAlertAction(title: Bundle.mxk_localizedString(forKey: "cancel"), style: .cancel, handler: { _ in self.viewModel.process(viewAction: .cancelThreePidValidation) })) self.present(alert, animated: true, completion: nil) self.presentedAlertController = alert } private func presentPendingMSISDNVerificationAlert() { let alert = UIAlertController(title: Bundle.mxk_localizedString(forKey: "account_msisdn_validation_title"), message: Bundle.mxk_localizedString(forKey: "account_msisdn_validation_message"), preferredStyle: .alert) alert.addTextField { (textField) in textField.placeholder = nil textField.keyboardType = .phonePad } alert.addAction(UIAlertAction(title: VectorL10n.continue, style: .default, handler: { _ in guard let textField = alert.textFields?.first, let smsCode = textField.text, smsCode.isEmpty == false else { return } self.viewModel.process(viewAction: .confirmMSISDNValidation(code: smsCode)) })) alert.addAction(UIAlertAction(title: Bundle.mxk_localizedString(forKey: "cancel"), style: .cancel, handler: { _ in self.viewModel.process(viewAction: .cancelThreePidValidation) })) self.present(alert, animated: true, completion: nil) self.presentedAlertController = alert } // MARK: - Actions @IBAction private func operationButtonAction(_ sender: Any) { guard let displayMode = self.displayMode else { return } let viewAction: SettingsDiscoveryThreePidDetailsViewAction? switch displayMode { case .share: viewAction = .share case .revoke: viewAction = .revoke default: viewAction = nil } if let viewAction = viewAction { self.viewModel.process(viewAction: viewAction) } } } // MARK: - SettingsDiscoveryThreePidDetailsViewModelViewDelegate extension SettingsDiscoveryThreePidDetailsViewController: SettingsDiscoveryThreePidDetailsViewModelViewDelegate { func settingsDiscoveryThreePidDetailsViewModel(_ viewModel: SettingsDiscoveryThreePidDetailsViewModelType, didUpdateViewState viewSate: SettingsDiscoveryThreePidDetailsViewState) { self.render(viewState: viewSate) } }
apache-2.0
a8f56dd349ab09bc06648b28d397a84c
36.917492
184
0.667073
5.799596
false
false
false
false
Jnosh/swift
stdlib/public/core/ThreadLocalStorage.swift
4
5519
//===--- ThreadLocalStorage.swift -----------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims // For testing purposes, a thread-safe counter to guarantee that destructors get // called by pthread. #if INTERNAL_CHECKS_ENABLED public // @testable let _destroyTLSCounter = _stdlib_AtomicInt() #endif // Thread local storage for all of the Swift standard library // // @moveonly/@pointeronly: shouldn't be used as a value, only through its // pointer. Similarly, shouldn't be created, except by // _initializeThreadLocalStorage. // internal struct _ThreadLocalStorage { // TODO: might be best to absract uBreakIterator handling and caching into // separate struct. That would also make it easier to maintain multiple ones // and other TLS entries side-by-side. // Save a pre-allocated UBreakIterator, as they are very expensive to set up. // Each thread can reuse their unique break iterator, being careful to reset // the text when it has changed (see below). Even with a naive always-reset // policy, grapheme breaking is 30x faster when using a pre-allocated // UBreakIterator than recreating one. // // private var uBreakIterator: OpaquePointer // TODO: Consider saving two, e.g. for character-by-character comparison // The below cache key tries to avoid resetting uBreakIterator's text when // operating on the same String as before. Avoiding the reset gives a 50% // speedup on grapheme breaking. // // As a invalidation check, save the base address from the last used // StringCore. We can skip resetting the uBreakIterator's text when operating // on a given StringCore when both of these associated references/pointers are // equal to the StringCore's. Note that the owner is weak, to force it to // compare unequal if a new StringCore happens to be created in the same // memory. // // TODO: unowned reference to string owner, base address, and _countAndFlags // private: Should only be called by _initializeThreadLocalStorage init(_uBreakIterator: OpaquePointer) { self.uBreakIterator = _uBreakIterator } // Get the current thread's TLS pointer. On first call for a given thread, // creates and initializes a new one. static internal func getPointer() -> UnsafeMutablePointer<_ThreadLocalStorage> { let tlsRawPtr = _swift_stdlib_pthread_getspecific(_tlsKey) if _fastPath(tlsRawPtr != nil) { return tlsRawPtr._unsafelyUnwrappedUnchecked.assumingMemoryBound( to: _ThreadLocalStorage.self) } return _initializeThreadLocalStorage() } // Retrieve our thread's local uBreakIterator and set it up for the given // StringCore. Checks our TLS cache to avoid excess text resetting. static internal func getUBreakIterator( for core: _StringCore ) -> OpaquePointer { let tlsPtr = getPointer() let brkIter = tlsPtr[0].uBreakIterator _sanityCheck(core._owner != nil || core._baseAddress != nil, "invalid StringCore") var err = __swift_stdlib_U_ZERO_ERROR let corePtr: UnsafeMutablePointer<UTF16.CodeUnit> corePtr = core.startUTF16 __swift_stdlib_ubrk_setText(brkIter, corePtr, Int32(core.count), &err) _precondition(err.isSuccess, "unexpected ubrk_setUText failure") return brkIter } } // Destructor to register with pthreads. Responsible for deallocating any memory // owned. internal func _destroyTLS(_ ptr: UnsafeMutableRawPointer?) { _sanityCheck(ptr != nil, "_destroyTLS was called, but with nil...") let tlsPtr = ptr!.assumingMemoryBound(to: _ThreadLocalStorage.self) __swift_stdlib_ubrk_close(tlsPtr[0].uBreakIterator) tlsPtr.deinitialize(count: 1) tlsPtr.deallocate(capacity: 1) #if INTERNAL_CHECKS_ENABLED // Log the fact we've destroyed our storage _destroyTLSCounter.fetchAndAdd(1) #endif } // Lazily created global key for use with pthread TLS internal let _tlsKey: __swift_pthread_key_t = { let sentinelValue = __swift_pthread_key_t.max var key: __swift_pthread_key_t = sentinelValue let success = _swift_stdlib_pthread_key_create(&key, _destroyTLS) _sanityCheck(success == 0, "somehow failed to create TLS key") _sanityCheck(key != sentinelValue, "Didn't make a new key") return key }() @inline(never) internal func _initializeThreadLocalStorage() -> UnsafeMutablePointer<_ThreadLocalStorage> { _sanityCheck(_swift_stdlib_pthread_getspecific(_tlsKey) == nil, "already initialized") // Create and initialize one. var err = __swift_stdlib_U_ZERO_ERROR let newUBreakIterator = __swift_stdlib_ubrk_open( /*type:*/ __swift_stdlib_UBRK_CHARACTER, /*locale:*/ nil, /*text:*/ nil, /*textLength:*/ 0, /*status:*/ &err) _precondition(err.isSuccess, "unexpected ubrk_open failure") let tlsPtr: UnsafeMutablePointer<_ThreadLocalStorage> = UnsafeMutablePointer<_ThreadLocalStorage>.allocate( capacity: 1 ) tlsPtr.initialize( to: _ThreadLocalStorage(_uBreakIterator: newUBreakIterator) ) let success = _swift_stdlib_pthread_setspecific(_tlsKey, tlsPtr) _sanityCheck(success == 0, "setspecific failed") return tlsPtr }
apache-2.0
d9849709603b089c434862ad55cfc83c
36.290541
80
0.713535
4.155873
false
false
false
false
devxoul/Drrrible
Drrrible/Sources/ViewControllers/MainTabBarController.swift
1
2729
// // MainTabBarController.swift // Drrrible // // Created by Suyeol Jeon on 10/03/2017. // Copyright © 2017 Suyeol Jeon. All rights reserved. // import UIKit import ReactorKit import RxCocoa import RxSwift final class MainTabBarController: UITabBarController, View { // MARK: Constants fileprivate struct Metric { static let tabBarHeight = 44.f } // MARK: Properties var disposeBag = DisposeBag() // MARK: Initializing init( reactor: MainTabBarViewReactor, shotListViewController: ShotListViewController, settingsViewController: SettingsViewController ) { defer { self.reactor = reactor } super.init(nibName: nil, bundle: nil) self.viewControllers = [shotListViewController, settingsViewController] .map { viewController -> UINavigationController in let navigationController = UINavigationController(rootViewController: viewController) navigationController.tabBarItem.title = nil navigationController.tabBarItem.imageInsets.top = 5 navigationController.tabBarItem.imageInsets.bottom = -5 return navigationController } } required convenience init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Configuring func bind(reactor: MainTabBarViewReactor) { self.rx.didSelect .scan((nil, nil)) { state, viewController in return (state.1, viewController) } // if select the view controller first time or select the same view controller again .filter { state in state.0 == nil || state.0 === state.1 } .map { state in state.1 } .filterNil() .subscribe(onNext: { [weak self] viewController in self?.scrollToTop(viewController) // scroll to top }) .disposed(by: self.disposeBag) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if #available(iOS 11.0, *) { self.tabBar.height = Metric.tabBarHeight + self.view.safeAreaInsets.bottom } else { self.tabBar.height = Metric.tabBarHeight } self.tabBar.bottom = self.view.height } func scrollToTop(_ viewController: UIViewController) { if let navigationController = viewController as? UINavigationController { let topViewController = navigationController.topViewController let firstViewController = navigationController.viewControllers.first if let viewController = topViewController, topViewController === firstViewController { self.scrollToTop(viewController) } return } guard let scrollView = viewController.view.subviews.first as? UIScrollView else { return } scrollView.setContentOffset(.zero, animated: true) } }
mit
8f612e5d6d6ab2ac26294481956eacd4
28.021277
94
0.703812
5.014706
false
false
false
false
terflogag/GBHFacebookImagePicker
GBHFacebookImagePicker/Classes/Model/FacebookAlbum.swift
2
1029
// // FacebookAlbumModel.swift // GBHFacebookImagePicker // // Created by Florian Gabach on 29/09/2016. // Copyright (c) 2016 Florian Gabach <[email protected]> class FacebookAlbum { // MARK: - Var /// Album's name var name: String? /// Album's pictures number var count: Int? /// Album's cover url var coverUrl: URL? /// Album's id var albumId: String? /// Contains album's picture var photos: [FacebookImage] = [] // MARK: - Init /// Initialize the album (from the retrieved information given by the Graph API) /// /// - Parameters: /// - name: the album's name /// - count: the number of picture in the album /// - coverUrl: the string url of the cover picture /// - albmId: the album id init(name: String, count: Int? = nil, coverUrl: URL? = nil, albmId: String) { self.name = name self.albumId = albmId self.coverUrl = coverUrl self.count = count } }
mit
4307a8a3465f3e96e7fba86b81cadf71
21.866667
84
0.581147
3.883019
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Venue
iOS/Venue/View Models/PlaceInviteViewModel.swift
1
2704
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import Foundation import ReactiveCocoa /// View model to handle keeping track of users selected for a place invite class PlaceInviteViewModel: NSObject { let location: POI var selectedUsers = [User]() init(location: POI) { self.location = location super.init() } func setupPeopleTableViewCell(cell: PeopleTableViewCell) { let person = cell.user if isSelectedWithId(person.id) { cell.selectedImageView.hidden = false cell.isSelectedForInvite = true } else { cell.selectedImageView.hidden = true cell.isSelectedForInvite = false } } func setupAvatarImageCollectionCell(cell: AvatarImageCollectionViewCell, row: Int) -> AvatarImageCollectionViewCell { let person = selectedUsers[row] if person.pictureUrl != "" { cell.avatarImageView.image = UIImage(named: person.pictureUrl) } cell.avatarPlaceholderLabel.text = person.initials return cell } func markSelectedAndUpdateCollection(cell: PeopleTableViewCell, indexPath: NSIndexPath, avatarCollectionView: UICollectionView) { cell.isSelectedForInvite = true let user = cell.user selectedUsers.append(user) cell.selectedImageView.hidden = false avatarCollectionView.insertItemsAtIndexPaths([NSIndexPath(forRow: selectedUsers.count - 1, inSection: 0)]) } func markDeselectedAndUpdateCollection(cell: PeopleTableViewCell, indexPath: NSIndexPath, avatarCollectionView: UICollectionView) { cell.isSelectedForInvite = false cell.selectedImageView.hidden = true if let index = getAvatarCollectionIndex(cell) { selectedUsers.removeAtIndex(index) avatarCollectionView.deleteItemsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)]) } } /** Method searches through selected users and returns if the user is present - parameter id: user id */ private func isSelectedWithId(id:Int) -> Bool { return Bool(selectedUsers.filter({$0.id == id}).count) } /** Method searches through selected users and returns position of user if present - parameter id: user id */ private func getAvatarCollectionIndex(cell: PeopleTableViewCell) -> Int? { for (index, user) in selectedUsers.enumerate() { if user.id == cell.user.id { return index } } return nil } }
epl-1.0
d79a4a956d1fdc48a26766079ca06502
30.44186
135
0.642989
5.218147
false
false
false
false
kotdark/Swift
UIImagePickerControllerCamera/UIImagePickerControllerCamera/ViewController.swift
32
3090
// // ViewController.swift // UIImagePickerControllerCamera // // Created by Carlos Butron on 08/12/14. // Copyright (c) 2014 Carlos Butron. // // This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later // version. // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License along with this program. If not, see // http:/www.gnu.org/licenses/. // import UIKit import MediaPlayer import MobileCoreServices class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @IBOutlet weak var myImage: UIImageView! @IBAction func useCamera(sender: UIButton) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.Camera //to select only camera controls, not video imagePicker.mediaTypes = [kUTTypeImage] imagePicker.showsCameraControls = true //imagePicker.allowsEditing = true self.presentViewController(imagePicker, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]){ let image = info[UIImagePickerControllerOriginalImage] as! UIImage let imageData = UIImagePNGRepresentation(image) as NSData //save in photo album UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil) //save in documents let documentsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as! NSString let filePath = documentsPath.stringByAppendingPathComponent("pic.png") imageData.writeToFile(filePath, atomically: true) myImage.image = image self.dismissViewControllerAnimated(true, completion: nil) } func image(image: UIImage, didFinishSavingWithError error: NSErrorPointer, contextInfo: UnsafePointer<()>){ if(error != nil){ println("ERROR IMAGE \(error.debugDescription)") } } func imagePickerControllerDidCancel(picker: UIImagePickerController){ self.dismissViewControllerAnimated(true, completion: nil) } }
gpl-3.0
c0900d632450cea1a56f5a635cd229e3
36.682927
167
0.71068
5.711645
false
false
false
false
BeitIssieShapira/IssieBoard
IssieBoard.xcodeproj/ConfigurableKeyboard/KeyboardModel.swift
3
3442
// // KeyboardModel.swift // EducKeyboard // // Created by Bezalel, Orit on 2/26/15. // Copyright (c) 2015 sap. All rights reserved. import Foundation var counter = 0 class Keyboard { var pages: [Page] init() { self.pages = [] } func addKey(key: Key, row: Int, page: Int) { if self.pages.count <= page { for i in self.pages.count...page { self.pages.append(Page()) } } self.pages[page].addKey(key, row: row) } } class Page { var rows: [[Key]] init() { self.rows = [] } func addKey(key: Key, row: Int) { if self.rows.count <= row { for i in self.rows.count...row { self.rows.append([]) } } self.rows[row].append(key) } } class Key: Hashable { enum KeyType { case Character case Backspace case ModeChange case KeyboardChange case Space case Return case Undo case Restore case DismissKeyboard case CustomCharSetOne case CustomCharSetTwo case CustomCharSetThree case SpecialKeys case HiddenKey case Other } var type: KeyType var keyTitle : String? var keyOutput : String? var pageNum: Int var toMode: Int? //if type is ModeChange toMode holds the page it links to var hasOutput : Bool {return (keyOutput != nil)} var hasTitle : Bool {return (keyTitle != nil)} var isCharacter: Bool { get { switch self.type { case .Character, .CustomCharSetOne, .CustomCharSetTwo, .CustomCharSetThree, .HiddenKey, .SpecialKeys: return true default: return false } } } var isSpecial: Bool { get { switch self.type { case .Backspace, .ModeChange, .KeyboardChange, .Space, .DismissKeyboard, .Return, .Undo, .Restore : return true default: return false } } } var hashValue: Int init(_ type: KeyType) { self.type = type self.hashValue = counter counter += 1 pageNum = -1 } convenience init(_ key: Key) { self.init(key.type) self.keyTitle = key.keyTitle self.keyOutput = key.keyOutput self.toMode = key.toMode self.pageNum = key.getPage() } func setKeyTitle(keyTitle: String) { self.keyTitle = keyTitle } func getKeyTitle () -> String { if (keyTitle != nil) { return keyTitle! } else { return "" } } func setKeyOutput(keyOutput: String) { self.keyOutput = keyOutput } func getKeyOutput () -> String { if (keyOutput != nil) { return keyOutput! } else { return "" } } func setPage(pageNum : Int) { self.pageNum = pageNum } func getPage() -> Int { return self.pageNum } } func ==(lhs: Key, rhs: Key) -> Bool { return lhs.hashValue == rhs.hashValue }
apache-2.0
50310176cc07ad680eb2c644cd49f8d1
19.610778
78
0.480244
4.475943
false
false
false
false
cabarique/TheProposalGame
MyProposalGame/Libraries/SG-Engine/SGExtensions.swift
1
4087
/* * Copyright (c) 2015 Neil North. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import SpriteKit public extension SKNode { /** Position this node relative to the visible area of the screen as a percentage float from 0.0 to 1.0. */ public func posByScreen(x: CGFloat, y: CGFloat) { self.position = CGPoint(x: CGFloat((SKMUIRect!.width * x) + SKMUIRect!.origin.x), y: CGFloat((SKMUIRect!.height * y) + SKMUIRect!.origin.y)) } /** Position this node releative to the total size of the scene as a percentage float from 0.0 to 1.0. */ public func posByCanvas(x: CGFloat, y: CGFloat) { self.position = CGPoint(x: CGFloat(SKMSceneSize!.width * x), y: CGFloat(SKMSceneSize!.height * y)) } } public extension CGSize { /** Set size of object based on current screen size and scale for different screen sizes while maintaining aspect ratio. */ public init(screenWidth: CGFloat, screenHeight: CGFloat) { if (SKMSceneSize != nil && SKMViewSize != nil) { self.init(width: screenWidth * (SKMViewSize!.height / SKMSceneSize!.height), height: screenHeight * (SKMViewSize!.height / SKMSceneSize!.height)) } else { self.init(width: screenWidth, height: screenHeight) } } /** Set size of object based size of scene alone, does not scale and for now it only passes value to the regular init with size function. Left in for possible future enhancements and uniformity. */ public init(canvasWidth: CGFloat, canvasHeight: CGFloat) { self.init(width: canvasWidth, height: canvasHeight) } } public extension CGPoint { /** Position this point relative to the visible area of the screen as a percentage float from 0.0 to 1.0. */ public init(screenX: CGFloat, screenY: CGFloat) { self.init(x: CGFloat((SKMUIRect!.width * screenX) + SKMUIRect!.origin.x), y: CGFloat((SKMUIRect!.height * screenY) + SKMUIRect!.origin.y)) } /** Position this point releative to the total size of the scene as a percentage float from 0.0 to 1.0. */ public init(canvasX: CGFloat, canvasY: CGFloat) { self.init(x: CGFloat(SKMSceneSize!.width * canvasX), y: CGFloat(SKMSceneSize!.height * canvasY)) } /** Position this point at a specific radius and degrees from CGPointZero. */ public init(radius:CGFloat, degrees:CGFloat) { self.init(x: radius * cos(degrees),y: radius * sin(degrees)) } /** Position this point at a specific radius and degrees from another CGPoint. */ public init(point:CGPoint, radius:CGFloat, degrees:CGFloat) { let newPoint = point + CGPoint(radius: radius, degrees: degrees) self.init(x:newPoint.x,y:newPoint.y) } } public extension CGFloat { /** Returns the float as a string limited to a set number of decimal points. */ public func string(fractionDigits:Int) -> String { let formatter = NSNumberFormatter() formatter.minimumFractionDigits = fractionDigits formatter.maximumFractionDigits = fractionDigits return formatter.stringFromNumber(self)! } }
mit
4175d24269094020ab0826cca658db39
31.181102
151
0.71128
4.002938
false
false
false
false
GraphKit/MaterialKit
Sources/iOS/TabBar.swift
2
9525
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit @objc(TabBarLineAlignment) public enum TabBarLineAlignment: Int { case top case bottom } @objc(TabBarDelegate) public protocol TabBarDelegate { /** A delegation method that is executed when the button will trigger the animation to the next tab. - Parameter tabBar: A TabBar. - Parameter button: A UIButton. */ @objc optional func tabBar(tabBar: TabBar, willSelect button: UIButton) /** A delegation method that is executed when the button did complete the animation to the next tab. - Parameter tabBar: A TabBar. - Parameter button: A UIButton. */ @objc optional func tabBar(tabBar: TabBar, didSelect button: UIButton) } open class TabBar: Bar { /// A boolean indicating if the TabBar line is in an animation state. open internal(set) var isAnimating = false /// A delegation reference. open weak var delegate: TabBarDelegate? /// The currently selected button. open internal(set) var selected: UIButton? /// A preset wrapper around contentEdgeInsets. open override var contentEdgeInsetsPreset: EdgeInsetsPreset { get { return contentView.grid.contentEdgeInsetsPreset } set(value) { contentView.grid.contentEdgeInsetsPreset = value } } /// A reference to EdgeInsets. @IBInspectable open override var contentEdgeInsets: EdgeInsets { get { return contentView.grid.contentEdgeInsets } set(value) { contentView.grid.contentEdgeInsets = value } } /// A preset wrapper around interimSpace. open override var interimSpacePreset: InterimSpacePreset { get { return contentView.grid.interimSpacePreset } set(value) { contentView.grid.interimSpacePreset = value } } /// A wrapper around contentView.grid.interimSpace. @IBInspectable open override var interimSpace: InterimSpace { get { return contentView.grid.interimSpace } set(value) { contentView.grid.interimSpace = value } } /// Buttons. open var buttons = [UIButton]() { didSet { for b in oldValue { b.removeFromSuperview() } centerViews = buttons as [UIView] layoutSubviews() } } /// A boolean to animate the line when touched. @IBInspectable open var isLineAnimated = true { didSet { for b in buttons { if isLineAnimated { prepareLineAnimationHandler(button: b) } else { removeLineAnimationHandler(button: b) } } } } /// A reference to the line UIView. open let line = UIView() /// The line color. open var lineColor: UIColor? { get { return line.backgroundColor } set(value) { line.backgroundColor = value } } /// A value for the line alignment. open var lineAlignment = TabBarLineAlignment.bottom { didSet { layoutSubviews() } } /// The line height. open var lineHeight: CGFloat { get { return line.height } set(value) { line.height = value } } open override func layoutSubviews() { super.layoutSubviews() guard willLayout else { return } guard 0 < buttons.count else { return } for b in buttons { b.grid.columns = 0 b.cornerRadius = 0 b.contentEdgeInsets = .zero if isLineAnimated { prepareLineAnimationHandler(button: b) } } contentView.grid.axis.columns = buttons.count contentView.grid.reload() if nil == selected { selected = buttons.first } line.frame = CGRect(x: selected!.x, y: .bottom == lineAlignment ? height - lineHeight : 0, width: selected!.width, height: lineHeight) } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepare method to initialize property values and other setup operations. The super.prepare method should always be called immediately when subclassing. */ open override func prepare() { super.prepare() contentEdgeInsetsPreset = .none interimSpacePreset = .none prepareLine() prepareDivider() } } extension TabBar { // Prepares the line. fileprivate func prepareLine() { line.zPosition = 6000 lineColor = Color.blue.base lineHeight = 3 addSubview(line) } /// Prepares the divider. fileprivate func prepareDivider() { dividerAlignment = .top } /** Prepares the line animation handlers. - Parameter button: A UIButton. */ fileprivate func prepareLineAnimationHandler(button: UIButton) { removeLineAnimationHandler(button: button) button.addTarget(self, action: #selector(handleButton(button:)), for: .touchUpInside) } /** Removes the line animation handlers. - Parameter button: A UIButton. */ fileprivate func removeLineAnimationHandler(button: UIButton) { button.removeTarget(self, action: #selector(handleButton(button:)), for: .touchUpInside) } } extension TabBar { /// Handles the button touch event. @objc internal func handleButton(button: UIButton) { animate(to: button, isTriggeredByUserInteraction: true) } } extension TabBar { /** Selects a given index from the buttons array. - Parameter at index: An Int. - Paramater completion: An optional completion block. */ open func select(at index: Int, completion: ((UIButton) -> Void)? = nil) { guard -1 < index, index < buttons.count else { return } animate(to: buttons[index], isTriggeredByUserInteraction: false, completion: completion) } /** Animates to a given button. - Parameter to button: A UIButton. - Parameter completion: An optional completion block. */ open func animate(to button: UIButton, completion: ((UIButton) -> Void)? = nil) { animate(to: button, isTriggeredByUserInteraction: false, completion: completion) } /** Animates to a given button. - Parameter to button: A UIButton. - Parameter isTriggeredByUserInteraction: A boolean indicating whether the state was changed by a user interaction, true if yes, false otherwise. - Parameter completion: An optional completion block. */ fileprivate func animate(to button: UIButton, isTriggeredByUserInteraction: Bool, completion: ((UIButton) -> Void)? = nil) { if isTriggeredByUserInteraction { delegate?.tabBar?(tabBar: self, willSelect: button) } selected = button isAnimating = true UIView.animate(withDuration: 0.25, animations: { [weak self, button = button] in guard let s = self else { return } s.line.center.x = button.center.x s.line.width = button.width }) { [weak self, button = button, completion = completion] _ in guard let s = self else { return } s.isAnimating = false if isTriggeredByUserInteraction { s.delegate?.tabBar?(tabBar: s, didSelect: button) } completion?(button) } } }
agpl-3.0
75547f558b2ef0f123678f32b7665105
29.528846
142
0.615643
5.04235
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceClipLogic/Sources/EurofurenceClipLogic/AppClip+Components.swift
1
4298
import ComponentBase import DealerComponent import DealersComponent import EurofurenceModel import EventDetailComponent import PreloadComponent import ScheduleComponent import TutorialComponent import UIKit extension AppClip { struct Components { let tutorialComponent: TutorialComponentFactory let preloadComponent: PreloadComponentFactory let scheduleComponentFactory: ScheduleComponentFactory let eventDetailComponentFactory: EventDetailComponentFactory let dealersComponentFactory: DealersComponentFactory let dealerDetailModuleProviding: DealerDetailComponentFactory // swiftlint:disable function_body_length init( window: UIWindow, dependencies: AppClip.Dependencies, repositories: Repositories, services: Services ) { let alertRouter = WindowAlertRouter(window: window) let shareService = ActivityShareService(window: window) let activityFactory = PlatformActivityFactory() tutorialComponent = TutorialModuleBuilder(alertRouter: alertRouter).build() let preloadInteractor = ApplicationPreloadInteractor(refreshService: services.refresh) preloadComponent = PreloadComponentBuilder( preloadInteractor: preloadInteractor, alertRouter: alertRouter ).build() let scheduleViewModelFactory = DefaultScheduleViewModelFactory( eventsService: repositories.events, hoursDateFormatter: FoundationHoursDateFormatter.shared, shortFormDateFormatter: FoundationShortFormDateFormatter.shared, shortFormDayAndTimeFormatter: FoundationShortFormDayAndTimeFormatter.shared, refreshService: services.refresh, shareService: shareService ) scheduleComponentFactory = ScheduleModuleBuilder( scheduleViewModelFactory: scheduleViewModelFactory ).build() let eventInteractionRecorder = SystemEventInteractionsRecorder( eventsService: repositories.events, eventIntentDonor: dependencies.eventIntentDonor, activityFactory: activityFactory ) let eventDetailViewModelFactory = DefaultEventDetailViewModelFactory( dateRangeFormatter: FoundationDateRangeFormatter.shared, eventsService: repositories.events, markdownRenderer: DefaultDownMarkdownRenderer(), shareService: shareService, calendarRepository: EventKitCalendarEventRepository( eventStore: EventKitEventStore(window: window), scheduleRepository: repositories.events ) ) eventDetailComponentFactory = EventDetailComponentBuilder( eventDetailViewModelFactory: eventDetailViewModelFactory, interactionRecorder: eventInteractionRecorder ).build() let dealersViewModelFactory = DefaultDealersViewModelFactory( dealersService: services.dealers, refreshService: services.refresh ) dealersComponentFactory = DealersComponentBuilder( dealersViewModelFactory: dealersViewModelFactory ).build() let dealerInteractionRecorder = DonateIntentDealerInteractionRecorder( viewDealerIntentDonor: dependencies.dealerIntentDonor, dealersService: services.dealers, activityFactory: activityFactory ) let dealerDetailViewModelFactory = DefaultDealerDetailViewModelFactory( dealersService: services.dealers, shareService: shareService ) dealerDetailModuleProviding = DealerDetailComponentBuilder( dealerDetailViewModelFactory: dealerDetailViewModelFactory, dealerInteractionRecorder: dealerInteractionRecorder ).build() } } }
mit
e3fb2d5e0a486063e31bb4130f0332a7
40.326923
98
0.644486
7.513986
false
false
false
false
ello/ello-ios
Sources/Model/CategoryPartial.swift
1
710
//// /// CategoryPartial.swift // class CategoryPartial: NSObject, NSCoding { let id: String let name: String let slug: String init(id: String, name: String, slug: String) { self.id = id self.name = name self.slug = slug } required init(coder: NSCoder) { let decoder = Coder(coder) self.id = decoder.decodeKey("id") self.name = decoder.decodeKey("name") self.slug = decoder.decodeKey("slug") } func encode(with encoder: NSCoder) { let coder = Coder(encoder) coder.encodeObject(id, forKey: "id") coder.encodeObject(name, forKey: "name") coder.encodeObject(slug, forKey: "slug") } }
mit
98feeafc0398a84059a921ed43f6bb60
23.482759
50
0.588732
3.901099
false
false
false
false
dannyYassine/DYECamera
DYECameraViewController.swift
1
9275
// // DYECameraViewController.swift // DYECamera // // Created by Danny Yassine on 2015-12-28. // Copyright © 2015 Danny Yassine. All rights reserved. // import UIKit import AVKit import AVFoundation import AssetsLibrary import Photos import MediaPlayer import MobileCoreServices class DYECameraViewController: UIViewController, AVCaptureFileOutputRecordingDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { var captureSession: AVCaptureSession! var previewLayer: AVCaptureVideoPreviewLayer! var movieFileOutPut: AVCaptureMovieFileOutput! var imageFileOutPut: AVCaptureStillImageOutput! @IBOutlet weak var previewCameraView: UIView! var frontCameraOn: Bool = false @IBOutlet weak var cameraButton: DYECameraButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. var audioMicrophone: AVCaptureDevice! for device in AVCaptureDevice.devices() { print(device.localizedName) if device.hasMediaType(AVMediaTypeVideo) { if device.position == AVCaptureDevicePosition.Back { print("Device position : back"); } else { print("Device position : front"); } } else if device.hasMediaType(AVMediaTypeAudio) { print("Device has media type audio") audioMicrophone = device as! AVCaptureDevice } } let backCamera = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo).first! let deviceInput = try! AVCaptureDeviceInput(device: backCamera as! AVCaptureDevice) let deviceAudioInput = try! AVCaptureDeviceInput(device: audioMicrophone) self.captureSession = AVCaptureSession() self.captureSession!.sessionPreset = AVCaptureSessionPresetHigh self.captureSession.addInput(deviceInput) self.captureSession.addInput(deviceAudioInput) self.movieFileOutPut = AVCaptureMovieFileOutput() movieFileOutPut.maxRecordedDuration = CMTime(seconds: 8, preferredTimescale: 30) movieFileOutPut.minFreeDiskSpaceLimit = 1024 * 1024 self.captureSession.addOutput(movieFileOutPut) self.imageFileOutPut = AVCaptureStillImageOutput() self.imageFileOutPut.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG] self.captureSession.addOutput(self.imageFileOutPut) self.previewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession) self.previewLayer!.frame = self.view.bounds self.previewLayer!.videoGravity = AVLayerVideoGravityResizeAspect self.previewLayer!.connection?.videoOrientation = AVCaptureVideoOrientation.Portrait self.previewCameraView.layer.addSublayer(self.previewLayer) self.captureSession.startRunning() self.cameraButton.duration = 8.0 let longPress = UILongPressGestureRecognizer(target: self, action: "longPressGuesture:") longPress.minimumPressDuration = 1.0 longPress.allowableMovement = 1000 self.cameraButton.addGestureRecognizer(longPress) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } func longPressGuesture(longPress: UILongPressGestureRecognizer) { if longPress.state == .Began { self.startVideoRecording() } else if longPress.state == .Ended { self.stopRecording() } } func captureOutput(captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAtURL fileURL: NSURL!, fromConnections connections: [AnyObject]!) { } func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) { // A problem occurred: Find out if the recording was successful. var recordedSuccessfully: Bool = true if error != nil { let value = error.userInfo[AVErrorRecordingSuccessfullyFinishedKey] if ((value) != nil) { recordedSuccessfully = value!.boolValue print("recordedSuccessfully: ", recordedSuccessfully) } } if recordedSuccessfully { // Save let photoLibrary = PHPhotoLibrary.sharedPhotoLibrary() photoLibrary.performChanges({ () -> Void in PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(outputFileURL) }) { (done, error) -> Void in print("done: ", done, "error: ", error) } } } @IBAction func startRecording(sender: AnyObject?) { if self.movieFileOutPut.recording == true { return } if self.cameraButton.isAnimating == true { self.stopRecording() } else { var videoConnection: AVCaptureConnection! for connection in self.imageFileOutPut.connections { for port in connection.inputPorts as! [AVCaptureInputPort] { if port.mediaType == AVMediaTypeVideo { videoConnection = connection as! AVCaptureConnection break } } if videoConnection != nil { break } } self.imageFileOutPut.captureStillImageAsynchronouslyFromConnection(videoConnection) { (sampleBuffer, error) -> Void in if (sampleBuffer != nil) { let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer) let dataProvider = CGDataProviderCreateWithCFData(imageData) let cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, CGColorRenderingIntent.RenderingIntentDefault) let image = UIImage(CGImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.Left) let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 75, height: 100)) imageView.image = image self.view.addSubview(imageView) } } } } func startVideoRecording() { let documentsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first! let moviePath = documentsPath + "/movie\(NSDate()).mov" let url = NSURL(fileURLWithPath: moviePath) print(url) self.movieFileOutPut.startRecordingToOutputFileURL(url, recordingDelegate: self) self.cameraButton.setRecording() } func stopRecording() { self.movieFileOutPut.stopRecording() self.cameraButton.stoppedRecording() } @IBAction func toggleCameraButtonPressed(sender: AnyObject) { var devicePosition: AVCaptureDevicePosition if frontCameraOn { devicePosition = .Back } else { devicePosition = .Front } captureSession.beginConfiguration() let device = self.switchCameras(devicePosition) var input = AVCaptureDeviceInput?() do { input = try AVCaptureDeviceInput(device: device) let inputs = self.captureSession.inputs as! [AVCaptureInput] self.frontCameraOn = !self.frontCameraOn for input in inputs { if let deviceInput = input as? AVCaptureDeviceInput { if deviceInput.device.hasMediaType(AVMediaTypeVideo) { self.captureSession.removeInput(input) } } } self.captureSession.addInput(input!) } catch _ { input = nil } captureSession.commitConfiguration() } func switchCameras(devicePosition: AVCaptureDevicePosition) -> AVCaptureDevice? { let deviceArrays = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) for device in deviceArrays { if device.position == devicePosition { return device as? AVCaptureDevice } } return nil } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func presentMovie(movieURL: NSURL) { let moviePlayerMovieController = AVPlayerViewController() let playerItem = AVPlayerItem(URL: movieURL) let player = AVPlayer(playerItem: playerItem) moviePlayerMovieController.player = player self.presentViewController(moviePlayerMovieController, animated: true) { () -> Void in } } }
mit
92c99ede73dde04d424d8d2d89ffafdb
36.546559
180
0.619582
6.125495
false
false
false
false
CSSE497/pathfinder-ios
framework/Pathfinder/Transport.swift
1
8796
// // Transport.swift // Pathfinder // // Created by Adam Michael on 10/15/15. // Copyright © 2015 Pathfinder. All rights reserved. // import Foundation import CoreLocation /** A registered transport that can be routed to transport commodities. This class should never be instantiated directly because it represents the state of the data from the Pathfinder backend. Instead, connect your device as a transport. The standard use case involves creating a new transport within a known cluster. This can be accomplished as follows: ```swift let pathfinder = Pathfinder(pathfinderAppId, userCreds) let metadata = ["passenger": 3, "suitecase": 4] let transport = pathfinder.cluster("/USA/West/Seattle").createTransport(metadata) transport.delegate = self transport.connect() ``` */ public class Transport: NSObject { let locationUpdateTimerInterval: Double = 5 var lastLocationUpdate: Double = 0 // MARK: - Enums - /// All transports exist in one of two states, online or offline. On creation, transports are placed into the offline state. Transports that are offline will not receive routes. public enum Status: String, CustomStringConvertible { case Offline = "Offline" case Online = "Online" public var description: String { switch self { case .Offline: return "Offline" case .Online: return "Online" } } } // MARK: - Instance Variables - /// The delegate that will receive notifications when any aspect of the cluster is updated. public var delegate: TransportDelegate? /// The route to which the transport is currently assigned, if there is one. public var route: Route? /// Various parameters that are used for routing and profile information. Routing parameters should be configured by the web UI. public var metadata: [String:AnyObject]? /// The current state of the transports online/offline status. public var status: Status /// The current location of the transport. public var location: CLLocationCoordinate2D? /// The unique id of the transport, as generated by Pathfinder. public var id: Int? var connected: Bool = false // MARK: - Methods - /** Connects the local transport instance to the Pathfinder backend. Location updates will be send periodically to aid in routing calculations. The connection is not made until it is confirmed that the end-user has allowed the application to access his/her location. Pathfinder will not function if the user does not allow for the application to access his/her location. */ public func connect() { locationManager = CLLocationManager() locationManager?.delegate = self locationManager?.desiredAccuracy = kCLLocationAccuracyBest locationManager?.requestAlwaysAuthorization() locationManager?.startUpdatingLocation() } /** Subscribes to updates for the model. On each update to the transport in the Pathfinder service, a push notification will be sent and the corresponding method on the delegate will be called. Updates will be send on the following events: * The transport moved. * The transport was assigned a new route. * The transport picked up or dropped off a commodity. * The transport was removed or went offline. */ public func subscribe() { self.cluster.conn.subscribe(self) } /// Stops the Pathfinder service from sending update notifications. public func unsubscribe() { self.cluster.conn.unsubscribe(self) } /** Retrieve the next action that the driver of the transport will need to undertake. Currently, this is only pickups and dropoffs of commodities. If you want the entire queue of upcoming events, see the route field. - seealso: route */ public func nextRouteAction() -> RouteAction? { if route?.actions.count > 1 { return route?.actions[1] } else { return nil } } /// Indicates that a transport has successfully completed one route action. It is the transports responsibility to indicate that they have picked up and dropped off their commodities. This method must be called, preferrably as the result of a UI interaction, when the driver acknowledges that they have picked up or dropped off a commodity on their route. public func completeNextRouteAction() { let routeAction = nextRouteAction() let commodity = routeAction!.commodity! switch routeAction!.action { case RouteAction.Action.Pickup: commodity.status = Commodity.Status.PickedUp commodity.transport = self case RouteAction.Action.Dropoff: commodity.status = Commodity.Status.DroppedOff commodity.transport = nil default: break } cluster.conn.update(commodity) { (CommodityResponse) -> Void in print("Commodity status updated") } } /** Adds the transport to the set of active transports that can be routed. If commodities are waiting to be picked up, the transport will be routed immediately. When the transport is successfully set to online, the corresponding method on its delegate will be called. */ public func goOnline() { status = .Online if id != nil { cluster.conn.update(self) { (TransportResponse) -> Void in self.delegate?.didGoOnline(self) } } } /** Removes the transport from the set of active transports that can be routed. If the transport is on route to pick up commodities, all of those commodities will be rerouted with a new transport. If the transport is currently transporting passengers, it cannot go offline. When the transport is successfully taken offline, the corresponding method on its delegate will be called. */ public func goOffline() { status = .Offline cluster.conn.update(self) { (TransportResponse) -> Void in self.delegate?.didGoOffline(self) } } var cluster: Cluster! var locationManager: CLLocationManager? init(cluster: Cluster, id: Int) { self.cluster = cluster self.id = id status = .Offline } init(id: Int, metadata: [String:AnyObject], location: CLLocationCoordinate2D, status: Status) { self.id = id self.metadata = metadata self.location = location self.status = status } init(cluster: Cluster, metadata: [String:AnyObject], status: Status) { self.cluster = cluster self.metadata = metadata self.status = status } init(clusterId: String, id: Int, metadata: [String:AnyObject], location: CLLocationCoordinate2D, status: Status) { self.id = id self.metadata = metadata self.location = location self.status = status } class func parse(message: NSDictionary) -> Transport? { if let id = message["id"] as? Int { if let metadata = message["metadata"] as? [String:AnyObject] { if let latitude = message["latitude"] as? Double { if let longitude = message["longitude"] as? Double { if let statusStr = message["status"] as? String { let status = Status(rawValue: statusStr) return Transport(id: id, metadata: metadata, location: CLLocationCoordinate2D(latitude: latitude, longitude: longitude), status: status!) } } } } } return nil } func sendLocationUpdate() { if id != nil && status == .Online && location != nil { cluster.conn.update(self) { _ in } } } } extension Transport: CLLocationManagerDelegate { /// :nodoc: public func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { print("LocationManager authorization status changed: \(status)") //NSTimer.scheduledTimerWithTimeInterval(locationUpdateTimerInterval, target: self, selector: "sendLocationUpdate", userInfo: nil, repeats: true) if status == CLAuthorizationStatus.AuthorizedAlways { if location != nil { register() } } } /// :nodoc: public func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { location = locations[0].coordinate print("Time is \(NSDate.timeIntervalSinceReferenceDate())") if connected { if (NSDate.timeIntervalSinceReferenceDate() > lastLocationUpdate + locationUpdateTimerInterval) { print("Transport location updated to \(locations[0].coordinate)") lastLocationUpdate = NSDate.timeIntervalSinceReferenceDate() self.cluster.conn.update(self) { (resp: TransportResponse) -> Void in print("Location update acknowedged") } } } else { register() } } private func register() { self.cluster.connect() { (cluster: Cluster) -> Void in self.cluster.conn.create(self) { (resp: TransportResponse) -> Void in self.connected = true self.id = resp.id self.delegate?.connected(self) } } } }
mit
62088c192851325fc833e3fe11030c8f
34.18
357
0.70631
4.54522
false
false
false
false
ben-ng/swift
test/SILGen/objc_protocols.swift
1
12153
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -disable-objc-attr-requires-foundation-module | %FileCheck %s // REQUIRES: objc_interop import gizmo import objc_protocols_Bas @objc protocol NSRuncing { func runce() -> NSObject func copyRuncing() -> NSObject func foo() static func mince() -> NSObject } @objc protocol NSFunging { func funge() func foo() } protocol Ansible { func anse() } // CHECK-LABEL: sil hidden @_TF14objc_protocols12objc_generic func objc_generic<T : NSRuncing>(_ x: T) -> (NSObject, NSObject) { return (x.runce(), x.copyRuncing()) // -- Result of runce is autoreleased according to default objc conv // CHECK: [[METHOD:%.*]] = witness_method [volatile] {{\$.*}}, #NSRuncing.runce!1.foreign // CHECK: [[RESULT1:%.*]] = apply [[METHOD]]<T>([[THIS1:%.*]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : NSRuncing> (τ_0_0) -> @autoreleased NSObject // -- Result of copyRuncing is received copy_valued according to -copy family // CHECK: [[METHOD:%.*]] = witness_method [volatile] {{\$.*}}, #NSRuncing.copyRuncing!1.foreign // CHECK: [[RESULT2:%.*]] = apply [[METHOD]]<T>([[THIS2:%.*]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : NSRuncing> (τ_0_0) -> @owned NSObject // -- Arguments are not consumed by objc calls // CHECK: destroy_value [[THIS2]] } // CHECK-LABEL: sil hidden @_TF14objc_protocols26objc_generic_partial_applyuRxS_9NSRuncingrFxT_ : $@convention(thin) <T where T : NSRuncing> (@owned T) -> () { func objc_generic_partial_apply<T : NSRuncing>(_ x: T) { // CHECK: bb0([[ARG:%.*]] : $T): // CHECK: [[FN:%.*]] = function_ref @[[THUNK1:_TTOFP14objc_protocols9NSRuncing5runceFT_CSo8NSObject]] : // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[METHOD:%.*]] = apply [[FN]]<T>([[ARG_COPY]]) // CHECK: destroy_value [[METHOD]] _ = x.runce // CHECK: [[FN:%.*]] = function_ref @[[THUNK1]] : // CHECK: [[METHOD:%.*]] = partial_apply [[FN]]<T>() // CHECK: destroy_value [[METHOD]] _ = T.runce // CHECK: [[FN:%.*]] = function_ref @[[THUNK2:_TTOZFP14objc_protocols9NSRuncing5minceFT_CSo8NSObject]] // CHECK: [[METATYPE:%.*]] = metatype $@thick T.Type // CHECK: [[METHOD:%.*]] = apply [[FN]]<T>([[METATYPE]]) // CHECK: destroy_value [[METHOD:%.*]] _ = T.mince // CHECK: destroy_value [[ARG]] } // CHECK: } // end sil function '_TF14objc_protocols26objc_generic_partial_applyuRxS_9NSRuncingrFxT_' // CHECK: sil shared [thunk] @[[THUNK1]] : // CHECK: bb0([[SELF:%.*]] : $Self): // CHECK: [[FN:%.*]] = function_ref @[[THUNK1_THUNK:_TTOFP14objc_protocols9NSRuncing5runcefT_CSo8NSObject]] : // CHECK: [[METHOD:%.*]] = partial_apply [[FN]]<Self>([[SELF]]) // CHECK: return [[METHOD]] // CHECK: } // end sil function '[[THUNK1]]' // CHECK: sil shared [thunk] @[[THUNK1_THUNK]] // CHECK: bb0([[SELF:%.*]] : $Self): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[FN:%.*]] = witness_method $Self, #NSRuncing.runce!1.foreign // CHECK: [[RESULT:%.*]] = apply [[FN]]<Self>([[SELF_COPY]]) // CHECK: destroy_value [[SELF_COPY]] // CHECK: return [[RESULT]] // CHECK: } // end sil function '[[THUNK1_THUNK]]' // CHECK: sil shared [thunk] @[[THUNK2]] : // CHECK: [[FN:%.*]] = function_ref @[[THUNK2_THUNK:_TTOZFP14objc_protocols9NSRuncing5mincefT_CSo8NSObject]] // CHECK: [[METHOD:%.*]] = partial_apply [[FN]]<Self>(%0) // CHECK: return [[METHOD]] // CHECK: } // end sil function '[[THUNK2]]' // CHECK: sil shared [thunk] @[[THUNK2_THUNK]] : // CHECK: [[FN:%.*]] = witness_method $Self, #NSRuncing.mince!1.foreign // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<Self>(%0) // CHECK-NEXT: return [[RESULT]] // CHECK: } // end sil function '[[THUNK2_THUNK]]' // CHECK-LABEL: sil hidden @_TF14objc_protocols13objc_protocol func objc_protocol(_ x: NSRuncing) -> (NSObject, NSObject) { return (x.runce(), x.copyRuncing()) // -- Result of runce is autoreleased according to default objc conv // CHECK: [[THIS1:%.*]] = open_existential_ref [[THIS1_ORIG:%.*]] : $NSRuncing to $[[OPENED:@opened(.*) NSRuncing]] // CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED]], #NSRuncing.runce!1.foreign // CHECK: [[RESULT1:%.*]] = apply [[METHOD]]<[[OPENED]]>([[THIS1]]) // -- Result of copyRuncing is received copy_valued according to -copy family // CHECK: [[THIS2:%.*]] = open_existential_ref [[THIS2_ORIG:%.*]] : $NSRuncing to $[[OPENED2:@opened(.*) NSRuncing]] // CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED2]], #NSRuncing.copyRuncing!1.foreign // CHECK: [[RESULT2:%.*]] = apply [[METHOD]]<[[OPENED2]]>([[THIS2:%.*]]) // -- Arguments are not consumed by objc calls // CHECK: destroy_value [[THIS2_ORIG]] } // CHECK-LABEL: sil hidden @_TF14objc_protocols27objc_protocol_partial_applyFPS_9NSRuncing_T_ : $@convention(thin) (@owned NSRuncing) -> () { func objc_protocol_partial_apply(_ x: NSRuncing) { // CHECK: bb0([[ARG:%.*]] : $NSRuncing): // CHECK: [[OPENED_ARG:%.*]] = open_existential_ref [[ARG]] : $NSRuncing to $[[OPENED:@opened(.*) NSRuncing]] // CHECK: [[FN:%.*]] = function_ref @_TTOFP14objc_protocols9NSRuncing5runceFT_CSo8NSObject // CHECK: [[OPENED_ARG_COPY:%.*]] = copy_value [[OPENED_ARG]] // CHECK: [[RESULT:%.*]] = apply [[FN]]<[[OPENED]]>([[OPENED_ARG_COPY]]) // CHECK: destroy_value [[RESULT]] // CHECK: destroy_value [[ARG]] _ = x.runce // FIXME: rdar://21289579 // _ = NSRuncing.runce } // CHECK : } // end sil function '_TF14objc_protocols27objc_protocol_partial_applyFPS_9NSRuncing_T_' // CHECK-LABEL: sil hidden @_TF14objc_protocols25objc_protocol_composition func objc_protocol_composition(_ x: NSRuncing & NSFunging) { // CHECK: [[THIS:%.*]] = open_existential_ref [[THIS_ORIG:%.*]] : $NSFunging & NSRuncing to $[[OPENED:@opened(.*) NSFunging & NSRuncing]] // CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED]], #NSRuncing.runce!1.foreign // CHECK: apply [[METHOD]]<[[OPENED]]>([[THIS]]) x.runce() // CHECK: [[THIS:%.*]] = open_existential_ref [[THIS_ORIG:%.*]] : $NSFunging & NSRuncing to $[[OPENED:@opened(.*) NSFunging & NSRuncing]] // CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED]], #NSFunging.funge!1.foreign // CHECK: apply [[METHOD]]<[[OPENED]]>([[THIS]]) x.funge() } // -- ObjC thunks get emitted for ObjC protocol conformances class Foo : NSRuncing, NSFunging, Ansible { // -- NSRuncing @objc func runce() -> NSObject { return NSObject() } @objc func copyRuncing() -> NSObject { return NSObject() } @objc static func mince() -> NSObject { return NSObject() } // -- NSFunging @objc func funge() {} // -- Both NSRuncing and NSFunging @objc func foo() {} // -- Ansible func anse() {} } // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Foo5runce // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Foo11copyRuncing // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Foo5funge // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Foo3foo // CHECK-NOT: sil hidden @_TToF{{.*}}anse{{.*}} class Bar { } extension Bar : NSRuncing { @objc func runce() -> NSObject { return NSObject() } @objc func copyRuncing() -> NSObject { return NSObject() } @objc func foo() {} @objc static func mince() -> NSObject { return NSObject() } } // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Bar5runce // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Bar11copyRuncing // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Bar3foo // class Bas from objc_protocols_Bas module extension Bas : NSRuncing { // runce() implementation from the original definition of Bas @objc func copyRuncing() -> NSObject { return NSObject() } @objc func foo() {} @objc static func mince() -> NSObject { return NSObject() } } // CHECK-LABEL: sil hidden [thunk] @_TToFE14objc_protocolsC18objc_protocols_Bas3Bas11copyRuncing // CHECK-LABEL: sil hidden [thunk] @_TToFE14objc_protocolsC18objc_protocols_Bas3Bas3foo // -- Inherited objc protocols protocol Fungible : NSFunging { } class Zim : Fungible { @objc func funge() {} @objc func foo() {} } // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Zim5funge // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Zim3foo // class Zang from objc_protocols_Bas module extension Zang : Fungible { // funge() implementation from the original definition of Zim @objc func foo() {} } // CHECK-LABEL: sil hidden [thunk] @_TToFE14objc_protocolsC18objc_protocols_Bas4Zang3foo // -- objc protocols with property requirements in extensions // <rdar://problem/16284574> @objc protocol NSCounting { var count: Int {get} } class StoredPropertyCount { @objc let count = 0 } extension StoredPropertyCount: NSCounting {} // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC14objc_protocols19StoredPropertyCountg5countSi class ComputedPropertyCount { @objc var count: Int { return 0 } } extension ComputedPropertyCount: NSCounting {} // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols21ComputedPropertyCountg5countSi // -- adding @objc protocol conformances to native ObjC classes should not // emit thunks since the methods are already available to ObjC. // Gizmo declared in Inputs/usr/include/Gizmo.h extension Gizmo : NSFunging { } // CHECK-NOT: _TTo{{.*}}5Gizmo{{.*}} @objc class InformallyFunging { @objc func funge() {} @objc func foo() {} } extension InformallyFunging: NSFunging { } @objc protocol Initializable { init(int: Int) } // CHECK-LABEL: sil hidden @_TF14objc_protocols28testInitializableExistentialFTPMPS_13Initializable_1iSi_PS0__ : $@convention(thin) (@thick Initializable.Type, Int) -> @owned Initializable { func testInitializableExistential(_ im: Initializable.Type, i: Int) -> Initializable { // CHECK: bb0([[META:%[0-9]+]] : $@thick Initializable.Type, [[I:%[0-9]+]] : $Int): // CHECK: [[I2_BOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <Initializable> // CHECK: [[PB:%.*]] = project_box [[I2_BOX]] // CHECK: [[ARCHETYPE_META:%[0-9]+]] = open_existential_metatype [[META]] : $@thick Initializable.Type to $@thick (@opened([[N:".*"]]) Initializable).Type // CHECK: [[ARCHETYPE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[ARCHETYPE_META]] : $@thick (@opened([[N]]) Initializable).Type to $@objc_metatype (@opened([[N]]) Initializable).Type // CHECK: [[I2_ALLOC:%[0-9]+]] = alloc_ref_dynamic [objc] [[ARCHETYPE_META_OBJC]] : $@objc_metatype (@opened([[N]]) Initializable).Type, $@opened([[N]]) Initializable // CHECK: [[INIT_WITNESS:%[0-9]+]] = witness_method [volatile] $@opened([[N]]) Initializable, #Initializable.init!initializer.1.foreign, [[ARCHETYPE_META]]{{.*}} : $@convention(objc_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @owned τ_0_0) -> @owned τ_0_0 // CHECK: [[I2_COPY:%.*]] = copy_value [[I2_ALLOC]] // CHECK: [[I2:%[0-9]+]] = apply [[INIT_WITNESS]]<@opened([[N]]) Initializable>([[I]], [[I2_COPY]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @owned τ_0_0) -> @owned τ_0_0 // CHECK: [[I2_EXIST_CONTAINER:%[0-9]+]] = init_existential_ref [[I2]] : $@opened([[N]]) Initializable : $@opened([[N]]) Initializable, $Initializable // CHECK: store [[I2_EXIST_CONTAINER]] to [init] [[PB]] : $*Initializable // CHECK: [[I2:%[0-9]+]] = load [copy] [[PB]] : $*Initializable // CHECK: destroy_value [[I2_BOX]] : $<τ_0_0> { var τ_0_0 } <Initializable> // CHECK: return [[I2]] : $Initializable var i2 = im.init(int: i) return i2 } // CHECK: } // end sil function '_TF14objc_protocols28testInitializableExistentialFTPMPS_13Initializable_1iSi_PS0__' class InitializableConformer: Initializable { @objc required init(int: Int) {} } // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols22InitializableConformerc final class InitializableConformerByExtension { init() {} } extension InitializableConformerByExtension: Initializable { @objc convenience init(int: Int) { self.init() } } // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols33InitializableConformerByExtensionc
apache-2.0
213e2c24229d111051ee989ba07e46b7
42.031915
265
0.650927
3.519432
false
false
false
false
kripple/bti-watson
ios-app/Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/ObjectMapper/Carthage/Checkouts/Nimble/Nimble/Matchers/Contain.swift
189
4119
import Foundation /// A Nimble matcher that succeeds when the actual sequence contains the expected value. public func contain<S: SequenceType, T: Equatable where S.Generator.Element == T>(items: T...) -> NonNilMatcherFunc<S> { return contain(items) } private func contain<S: SequenceType, T: Equatable where S.Generator.Element == T>(items: [T]) -> NonNilMatcherFunc<S> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "contain <\(arrayAsString(items))>" if let actual = try actualExpression.evaluate() { return all(items) { return actual.contains($0) } } return false } } /// A Nimble matcher that succeeds when the actual string contains the expected substring. public func contain(substrings: String...) -> NonNilMatcherFunc<String> { return contain(substrings) } private func contain(substrings: [String]) -> NonNilMatcherFunc<String> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "contain <\(arrayAsString(substrings))>" if let actual = try actualExpression.evaluate() { return all(substrings) { let scanRange = Range(start: actual.startIndex, end: actual.endIndex) let range = actual.rangeOfString($0, options: [], range: scanRange, locale: nil) return range != nil && !range!.isEmpty } } return false } } /// A Nimble matcher that succeeds when the actual string contains the expected substring. public func contain(substrings: NSString...) -> NonNilMatcherFunc<NSString> { return contain(substrings) } private func contain(substrings: [NSString]) -> NonNilMatcherFunc<NSString> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "contain <\(arrayAsString(substrings))>" if let actual = try actualExpression.evaluate() { return all(substrings) { actual.rangeOfString($0.description).length != 0 } } return false } } /// A Nimble matcher that succeeds when the actual collection contains the expected object. public func contain(items: AnyObject?...) -> NonNilMatcherFunc<NMBContainer> { return contain(items) } private func contain(items: [AnyObject?]) -> NonNilMatcherFunc<NMBContainer> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "contain <\(arrayAsString(items))>" let actual = try actualExpression.evaluate() return all(items) { item in return actual != nil && actual!.containsObject(item) } } } extension NMBObjCMatcher { public class func containMatcher(expected: [NSObject]) -> NMBObjCMatcher { return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in let location = actualExpression.location let actualValue = try! actualExpression.evaluate() if let value = actualValue as? NMBContainer { let expr = Expression(expression: ({ value as NMBContainer }), location: location) // A straightforward cast on the array causes this to crash, so we have to cast the individual items let expectedOptionals: [AnyObject?] = expected.map({ $0 as AnyObject? }) return try! contain(expectedOptionals).matches(expr, failureMessage: failureMessage) } else if let value = actualValue as? NSString { let expr = Expression(expression: ({ value as String }), location: location) return try! contain(expected as! [String]).matches(expr, failureMessage: failureMessage) } else if actualValue != nil { failureMessage.postfixMessage = "contain <\(arrayAsString(expected))> (only works for NSArrays, NSSets, NSHashTables, and NSStrings)" } else { failureMessage.postfixMessage = "contain <\(arrayAsString(expected))>" } return false } } }
mit
6c2254b706b337d52269572549571c81
44.263736
149
0.664724
5.247134
false
false
false
false
triestpa/GetHome-iOS
GetHome/MapViewController.swift
1
10030
// // FirstViewController.swift // GetHome // // Created by Patrick on 12/2/14. // Copyright (c) 2014 Patrick Triest. All rights reserved. // import UIKit import MapKit class MapViewController: UIViewController, MKMapViewDelegate, DirectionsDelegate, EAIntroDelegate { @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var refreshButton: UIButton! @IBAction func refreshButtonTouch(sender: AnyObject) { showOptions() } var myRoute : MKRoute? var directionManager: DirectionsManager? var plistDict: NSMutableDictionary? var homePoint: CLLocationCoordinate2D? var homeAddress: String? override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self mapView.setUserTrackingMode(MKUserTrackingMode.Follow, animated: true) var myDict: NSDictionary? if let path = NSBundle.mainBundle().pathForResource("AddressInfo", ofType: "plist") { plistDict = NSMutableDictionary(contentsOfFile: path) println(plistDict!) if (plistDict!["Address"] as String == "none"){ showIntroPage() } else { homePoint = CLLocationCoordinate2D(latitude: plistDict!["Latitude"] as Double, longitude: plistDict!["Longitude"] as Double) println(homePoint) homeAddress = plistDict!["Address"] as? String self.directionManager = DirectionsManager(directions: self, homeLocation: homePoint!) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! { var myLineRenderer = MKPolylineRenderer(polyline: myRoute?.polyline!) myLineRenderer.strokeColor = UIColor.redColor() myLineRenderer.lineWidth = 3 return myLineRenderer } func updateView(route: MKRoute) { //center on user let span = MKCoordinateSpanMake(0.02, 0.02) let currentLocaton: CLLocationCoordinate2D? = directionManager?.locationHelper.lastLocation?.coordinate let region = MKCoordinateRegionMake(currentLocaton! , span) self.mapView.setRegion(region, animated: true) //update the map directions self.mapView.removeOverlay(self.myRoute?.polyline) self.myRoute = route self.mapView.addOverlay(self.myRoute?.polyline) } func showError(errorMessage: String) { //Show Error Dialog var alert = UIAlertController(title: "Error", message: errorMessage, preferredStyle: UIAlertControllerStyle.Alert) var okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: { action in return }) alert.addAction(okAction) self.presentViewController(alert, animated: true, completion: nil) } func showUberMessage(uberMessage: String, pickupLocation: CLLocationCoordinate2D, dropOffLocation: CLLocationCoordinate2D) { //Show Error Dialog var alert = UIAlertController(title: "Uber", message: uberMessage, preferredStyle: UIAlertControllerStyle.Alert) var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: { action in return }) alert.addAction(cancelAction) var okAction = UIAlertAction(title: "Open Uber", style: UIAlertActionStyle.Default, handler: { action in // The only required property - pickupLocation var pickupLocation = CLLocationCoordinate2D(latitude: pickupLocation.latitude, longitude: pickupLocation.longitude) var uber = UberHelper(pickupLocation: pickupLocation) uber.dropoffLocation = CLLocationCoordinate2D(latitude: pickupLocation.latitude, longitude: pickupLocation.longitude) uber.deepLink() return }) alert.addAction(okAction) self.presentViewController(alert, animated: true, completion: nil) } func showOptions() { var optionsController = UIAlertController(title: "How Do You Want to Travel?", message: nil, preferredStyle: .Alert) var walkAction = UIAlertAction(title: "Walking", style: UIAlertActionStyle.Default, handler: { action in self.directionManager?.getDirections(MKDirectionsTransportType.Walking) return }) optionsController.addAction(walkAction) var driveAction = UIAlertAction(title: "Driving", style: UIAlertActionStyle.Default, handler: { action in self.directionManager?.getDirections(MKDirectionsTransportType.Automobile) return }) optionsController.addAction(driveAction) var uberAction = UIAlertAction(title: "Uber", style: UIAlertActionStyle.Default, handler: { action in self.directionManager?.findUber() return}) optionsController.addAction(uberAction) var resetAddress = UIAlertAction(title: "Reset Home Address", style: UIAlertActionStyle.Default, handler: { action in self.getUserAddress() return}) optionsController.addAction(resetAddress) var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: { action in return}) optionsController.addAction(cancelAction) self.presentViewController(optionsController, animated: true, completion: nil) } func showProgress() { MRProgressOverlayView.showOverlayAddedTo(self.view, animated: true) } func hideProgress() { MRProgressOverlayView.dismissOverlayForView(self.view, animated: true) } func showIntroPage() { var introPage1 = EAIntroPage() introPage1.title = "Welcome!" introPage1.desc = "Ever wish there was an easier way to find your way home from anywhere?" introPage1.titlePositionY = 500 introPage1.descPositionY = 450 introPage1.bgImage = UIImage(named: "nightcity") var introPage2 = EAIntroPage() introPage2.title = "We've got good news!" introPage2.desc = "Get Home will help you find your way home from anywhere, all you need to do is open the app and we'll do the rest." introPage2.titlePositionY = 500 introPage2.descPositionY = 450 introPage2.bgImage = UIImage(named: "budapest") var introPage3 = EAIntroPage() introPage3.title = "There's Even More!" introPage3.desc = "We'll give you the option between driving or walking home, and you can even order an Uber home directly from the app. Give it a whirl!" introPage3.bgImage = UIImage(named: "citystreet") var intro = EAIntroView(frame: self.view.bounds, andPages: [introPage1, introPage2, introPage3]) intro.delegate = self intro.useMotionEffects = true intro.showInView(self.view, animateDuration: 0.0) } func introDidFinish(introView: EAIntroView!) { getUserAddress() } func getUserAddress() { var alert = UIAlertController(title: "Set your Home Address", message: nil, preferredStyle: UIAlertControllerStyle.Alert) alert.addTextFieldWithConfigurationHandler(nil) let locationTextField = alert.textFields?.last as UITextField if (homeAddress == nil) { locationTextField.placeholder = "Enter Home Address" } else { locationTextField.placeholder = homeAddress } alert.addAction(UIAlertAction(title: "Set", style: UIAlertActionStyle.Default, handler: { action in let homeAddress = locationTextField.text self.geocodeAddress(homeAddress) })) self.presentViewController(alert, animated: true, completion: nil) } func geocodeAddress(address: String) { let addressLookup: CLGeocoder = CLGeocoder() addressLookup.geocodeAddressString(address, completionHandler: {(placemarks, error)->Void in if (error == nil) { let firstCoordinate: CLPlacemark = placemarks[0] as CLPlacemark let homeCoordinate: CLLocationCoordinate2D = firstCoordinate.location.coordinate println("Lat: " + "\(homeCoordinate.latitude)" + "\nLong: " + "\(homeCoordinate.longitude)") self.plistDict!["Address"] = address self.plistDict!["Latitude"] = Double(homeCoordinate.latitude) self.plistDict!["Longitude"] = Double(homeCoordinate.longitude) if let path = NSBundle.mainBundle().pathForResource("AddressInfo", ofType: "plist") { self.plistDict?.writeToFile(path, atomically: true) println(self.plistDict?) self.directionManager = DirectionsManager(directions: self, homeLocation: homeCoordinate) } } else { self.showError("Address Not Found") } }) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if segue.identifier == "chooseLocationController" { // let destinationViewController = segue.destinationViewController // as chooseLocationController } else if segue.identifier == "showList" { let navigationController = segue.destinationViewController as UINavigationController let destinationViewController = navigationController.topViewController as DirectionsTableViewController if (directionManager?.thisRoute != nil) { destinationViewController.route = directionManager?.thisRoute? } } } }
gpl-2.0
7fbd14182f5547ee46dafa5dda3dbfbd
41.680851
162
0.650249
5.273396
false
false
false
false
exponent/exponent
packages/expo-dev-menu/ios/Interceptors/DevMenuMotionInterceptor.swift
2
964
// Copyright 2015-present 650 Industries. All rights reserved. import Foundation import UIKit class DevMenuMotionInterceptor { /** Returns bool value whether the dev menu shake gestures are being intercepted. */ static var isInstalled: Bool = false { willSet { if isInstalled != newValue { // Capture shake gesture from any window by swizzling default implementation from UIWindow. swizzle() } } } static var isEnabled: Bool = true static private func swizzle() { DevMenuUtils.swizzle( selector: #selector(UIWindow.motionEnded(_:with:)), withSelector: #selector(UIWindow.EXDevMenu_motionEnded(_:with:)), forClass: UIWindow.self ) } } extension UIWindow { @objc func EXDevMenu_motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { if event?.subtype == .motionShake && DevMenuMotionInterceptor.isEnabled { DevMenuManager.shared.toggleMenu() } } }
bsd-3-clause
1f87dc95bee90eff4f66bbb35dccee20
25.054054
99
0.689834
4.590476
false
false
false
false
avaidyam/Parrot
Parrot/LocationHelper.swift
1
1306
import CoreLocation /// Locate the device's current location; return true from the handler to stop. public func locate(reason: String, _ handler: @escaping (CLLocation?, Error?) -> (Bool)) { class CLLocator: NSObject, CLLocationManagerDelegate { var _self: CLLocator? = nil let manager = CLLocationManager() let handler: (CLLocation?, Error?) -> (Bool) init(_ reason: String, _ handler: @escaping (CLLocation?, Error?) -> (Bool)) { self.handler = handler super.init() _self = self self.manager.desiredAccuracy = 10.0 self.manager.delegate = self self.manager.purpose = reason self.manager.startUpdatingLocation() } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { if handler(nil, error) { self.manager.stopUpdatingLocation() _self = nil } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if handler(locations.last, nil) { self.manager.stopUpdatingLocation() _self = nil } } } _ = CLLocator(reason, handler) }
mpl-2.0
b3527e217fddea8744cba5612c3b4027
36.314286
104
0.570444
5.203187
false
false
false
false
bhajian/raspi-remote
Carthage/Checkouts/ios-sdk/Source/AlchemyLanguageV1/Models/Keywords.swift
1
1628
/** * Copyright IBM Corporation 2015 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import Freddy /** **Keywords** Response object for **Keyword** related calls */ public struct Keywords: JSONDecodable { /** the number of transactions made by the call */ public let totalTransactions: Int? /** extracted language */ public let language: String? /** the URL information was requested for */ public let url: String? /** see **Keyword** */ public let keywords: [Keyword]? /** document text */ public let text: String? /// Used internally to initialize a Keywords object public init(json: JSON) throws { if let totalTransactionsString = try? json.string("totalTransactions") { totalTransactions = Int(totalTransactionsString) } else { totalTransactions = 1 } language = try? json.string("language") url = try? json.string("url") keywords = try? json.arrayOf("keywords", type: Keyword.self) text = try? json.string("text") } }
mit
5327279fa56fb9347e66683e0d3754ff
27.068966
80
0.657248
4.547486
false
false
false
false
nghiaphunguyen/NKit
NKit/Source/NKCollectionView/NKBaseCollectionViewCell.swift
1
1533
// // NKBaseCollectionViewCell.swift // FastSell // // Created by Nghia Nguyen on 5/21/16. // Copyright © 2016 vn.fastsell. All rights reserved. // import UIKit open class NKBaseCollectionViewCell: UICollectionViewCell { public override init(frame: CGRect) { super.init(frame: frame) self.setupView() self.setupRx() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupView() self.setupRx() } @objc dynamic open func setupView() {} @objc dynamic open func setupRx() {} // open override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { // guard let autoFitDimension = self.autoFitDimension else { // return layoutAttributes // } // // let attributes = super.preferredLayoutAttributesFitting(layoutAttributes) // // self.setNeedsLayout() // self.layoutIfNeeded() // // let size = self.contentView.systemLayoutSizeFitting(UILayoutFittingCompressedSize) // var newFrame = layoutAttributes.frame //// if autoFitDimension.contains(NKDimension.Width) { // newFrame.size.width = size.width //// } // //// if autoFitDimension.contains(NKDimension.Height) { // newFrame.size.height = size.height //// } // // attributes.frame = newFrame // return attributes // } }
mit
d774bb30e05b379eb19e24fa7beb0641
29.039216
149
0.627937
4.614458
false
false
false
false
xuech/OMS-WH
OMS-WH/Classes/TakeOrder/线下处理/View/OfflineReasonView.swift
1
719
// // OfflineReasonView.swift // OMS-WH // // Created by xuech on 2017/10/26. // Copyright © 2017年 medlog. All rights reserved. // import UIKit class OfflineReasonView: UIView,NibLoadableView { @IBOutlet weak var reasonView: OMSPlaceholdTextView! override func awakeFromNib() { super.awakeFromNib() reasonView.placeholderColor = kAppearanceColor reasonView.placeholder = "请输入详细原因描述(100字以内)" reasonView.font = UIFont.systemFont(ofSize: 13) reasonView.layer.borderColor = UIColor.groupTableViewBackground.cgColor reasonView.layer.borderWidth = 1 self.autoresizingMask = .flexibleBottomMargin } }
mit
d635a7591d6404af5d7cd827c50f11b1
25.461538
79
0.690407
4.246914
false
false
false
false
twtstudio/WePeiYang-iOS
WePeiYang/Library/Controller/LibraryFavoriteTableViewController.swift
1
5647
// // LibraryFavoriteTableViewController.swift // WePeiYang // // Created by Qin Yubo on 16/4/27. // Copyright © 2016年 Qin Yubo. All rights reserved. // import UIKit import DZNEmptyDataSet class LibraryFavoriteTableViewController: UITableViewController, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate { var dataArr: [LibraryDataItem] = [] override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.tintColor = UIColor(red: 22/255.0, green: 151/255.0, blue: 166/255.0, alpha: 1.0) } override func viewDidLoad() { super.viewDidLoad() self.title = "收藏夹" self.jz_navigationBarBackgroundHidden = false // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. self.navigationItem.rightBarButtonItem = self.editButtonItem() self.tableView.registerNib(UINib(nibName: "LibraryTableViewCell", bundle: nil), forCellReuseIdentifier: "libCellIdentifier") self.tableView.emptyDataSetSource = self self.tableView.emptyDataSetDelegate = self self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.estimatedRowHeight = 98.0 self.tableView.tableFooterView = UIView() self.dataArr = LibraryDataManager.favoriteLibraryItems() self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArr.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("libCellIdentifier") as! LibraryTableViewCell cell.setLibraryItem(dataArr[indexPath.row]) return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source for tmpIndexPath in [indexPath] { LibraryDataManager.removeLibraryItem(self.dataArr[tmpIndexPath.row]) self.dataArr.removeAtIndex(tmpIndexPath.row) } tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) if self.dataArr.count == 0 { tableView.reloadData() } } // else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view // } } /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - EmptyDataSet func imageForEmptyDataSet(scrollView: UIScrollView!) -> UIImage! { return UIImage(named: "libEmpty") } func titleForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! { let text = "暂无收藏" let attr = [ NSFontAttributeName: UIFont.boldSystemFontOfSize(18.0), NSForegroundColorAttributeName: UIColor.darkGrayColor() ] return NSAttributedString(string: text, attributes: attr) } func descriptionForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! { let text = "请在搜索页面将书目左滑以加入收藏夹" let para = NSMutableParagraphStyle() para.lineBreakMode = .ByWordWrapping para.alignment = .Center let attr = [ NSFontAttributeName: UIFont.systemFontOfSize(14.0), NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSParagraphStyleAttributeName: para ] return NSAttributedString(string: text, attributes: attr) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
8ee27dc48026df0961c629654d234059
37.593103
157
0.682273
5.546085
false
false
false
false
wujianguo/YouPlay-iOS
YouPlay-iOS/YouPlayItem.swift
1
4124
// // YouPlayItem.swift // YouPlay-iOS // // Created by 吴建国 on 16/1/4. // Copyright © 2016年 wujianguo. All rights reserved. // import UIKit import Alamofire private var api = "https://youplay.leanapp.cn/api/v1" struct YouPlayItem { var status = "" var rating = "" var thumb = "" var title = "" var detail = "" var actors = [String]() } struct YouPlaySource { var status = "" var site = "" var name = "" var icon = "" var urls = [String]() var titles = [String]() } struct YouPlayDetail { var status = "" var rating = "" var thumb = "" var title = "" var pub = "" var sum = "" var actors = [String]() var sources = [YouPlaySource]() } enum YouPlaychannel: Int, CustomStringConvertible { case Teleplay = 0 case Anime var description: String { switch self { case .Teleplay: return "teleplaylist" case .Anime: return "animelist" } } } func queryItems(channel: YouPlaychannel, page: Int, complete: ([YouPlayItem], Bool) -> Void) { Alamofire.request(.GET, "\(api)/channel/\(channel)?page=\(page)").responseJSON { (data) -> Void in guard data.result.isSuccess && data.data != nil else { complete([], false) return } let json = JSON(data: data.data!) guard json["err"].int == 0 else { complete([], false) return } var l: [YouPlayItem] = [] for item in json["data"].arrayValue { var actors = [String]() for actor in item["actors"].arrayValue { actors.append(actor.stringValue) } l.append(YouPlayItem( status: item["status"].stringValue, rating: item["rating"].stringValue, thumb: item["thumb"].stringValue, title: item["title"].stringValue, detail: item["detail"].stringValue, actors: actors )) } complete(l, true) } } func queryDetail(detailApi: String, complete: (YouPlayDetail?) -> Void) { Alamofire.request(.GET, "\(api)\(detailApi)").responseJSON { (data) -> Void in guard data.result.isSuccess && data.data != nil else { complete(nil) return } let json = JSON(data: data.data!) guard json["err"].int == 0 else { complete(nil) return } var detail = YouPlayDetail() detail.status = json["data"]["status"].stringValue detail.rating = json["data"]["rating"].stringValue detail.thumb = json["data"]["thumb"].stringValue detail.title = json["data"]["name"].stringValue detail.pub = json["data"]["pub"].stringValue detail.sum = json["data"]["sum"].stringValue for s in json["data"]["sources"].arrayValue { var source = YouPlaySource() source.status = s["status"].stringValue source.site = s["site"].stringValue source.name = s["name"].stringValue source.icon = s["icon"].stringValue for it in s["episodes"].arrayValue { source.urls.append(it["url"].stringValue) source.titles.append(it["title"].stringValue) } detail.sources.append(source) } complete(detail) } } private extension String { var base64Value: String { return self.dataUsingEncoding(NSUTF8StringEncoding)!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) } } func queryStreamUrls(url: String, complete: ([String]) -> Void) { Alamofire.request(.GET, "\(api)/videos2/\(url.base64Value)").responseJSON { (data) -> Void in guard data.result.isSuccess && data.data != nil else { complete([]) return } var us = [String]() let json = JSON(data: data.data!) for u in json["entries"].arrayValue { us.append(u["url"].stringValue) } complete(us) } }
gpl-2.0
ad5e229c166750c8b07af95ec26f1114
27.576389
133
0.548238
4.237899
false
false
false
false
lorentey/swift
stdlib/public/core/UnicodeScalarProperties.swift
11
58538
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Exposes advanced properties of Unicode.Scalar defined by the Unicode // Standard. //===----------------------------------------------------------------------===// import SwiftShims extension Unicode.Scalar { /// A value that provides access to properties of a Unicode scalar that are /// defined by the Unicode standard. public struct Properties { @usableFromInline internal var _scalar: Unicode.Scalar internal init(_ scalar: Unicode.Scalar) { self._scalar = scalar } // Provide the value as UChar32 to make calling the ICU APIs cleaner internal var icuValue: __swift_stdlib_UChar32 { return __swift_stdlib_UChar32(bitPattern: self._scalar._value) } } /// Properties of this scalar defined by the Unicode standard. /// /// Use this property to access the Unicode properties of a Unicode scalar /// value. The following code tests whether a string contains any math /// symbols: /// /// let question = "Which is larger, 3 * 3 * 3 or 10 + 10 + 10?" /// let hasMathSymbols = question.unicodeScalars.contains(where: { /// $0.properties.isMath /// }) /// // hasMathSymbols == true public var properties: Properties { return Properties(self) } } /// Boolean properties that are defined by the Unicode Standard (i.e., not /// ICU-specific). extension Unicode.Scalar.Properties { internal func _hasBinaryProperty( _ property: __swift_stdlib_UProperty ) -> Bool { return __swift_stdlib_u_hasBinaryProperty(icuValue, property) != 0 } /// A Boolean value indicating whether the scalar is alphabetic. /// /// Alphabetic scalars are the primary units of alphabets and/or syllabaries. /// /// This property corresponds to the "Alphabetic" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isAlphabetic: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_ALPHABETIC) } /// A Boolean value indicating whether the scalar is an ASCII character /// commonly used for the representation of hexadecimal numbers. /// /// The only scalars for which this property is `true` are: /// /// * U+0030...U+0039: DIGIT ZERO...DIGIT NINE /// * U+0041...U+0046: LATIN CAPITAL LETTER A...LATIN CAPITAL LETTER F /// * U+0061...U+0066: LATIN SMALL LETTER A...LATIN SMALL LETTER F /// /// This property corresponds to the "ASCII_Hex_Digit" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isASCIIHexDigit: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_ASCII_HEX_DIGIT) } /// A Boolean value indicating whether the scalar is a format control /// character that has a specific function in the Unicode Bidrectional /// Algorithm. /// /// This property corresponds to the "Bidi_Control" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isBidiControl: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_BIDI_CONTROL) } /// A Boolean value indicating whether the scalar is mirrored in /// bidirectional text. /// /// This property corresponds to the "Bidi_Mirrored" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isBidiMirrored: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_BIDI_MIRRORED) } /// A Boolean value indicating whether the scalar is a punctuation /// symbol explicitly called out as a dash in the Unicode Standard or a /// compatibility equivalent. /// /// This property corresponds to the "Dash" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isDash: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_DASH) } /// A Boolean value indicating whether the scalar is a default-ignorable /// code point. /// /// Default-ignorable code points are those that should be ignored by default /// in rendering (unless explicitly supported). They have no visible glyph or /// advance width in and of themselves, although they may affect the display, /// positioning, or adornment of adjacent or surrounding characters. /// /// This property corresponds to the "Default_Ignorable_Code_Point" property /// in the [Unicode Standard](http://www.unicode.org/versions/latest/). public var isDefaultIgnorableCodePoint: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_DEFAULT_IGNORABLE_CODE_POINT) } /// A Boolean value indicating whether the scalar is deprecated. /// /// Scalars are never removed from the Unicode Standard, but the usage of /// deprecated scalars is strongly discouraged. /// /// This property corresponds to the "Deprecated" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isDeprecated: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_DEPRECATED) } /// A Boolean value indicating whether the scalar is a diacritic. /// /// Diacritics are scalars that linguistically modify the meaning of another /// scalar to which they apply. Scalars for which this property is `true` are /// frequently, but not always, combining marks or modifiers. /// /// This property corresponds to the "Diacritic" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isDiacritic: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_DIACRITIC) } /// A Boolean value indicating whether the scalar's principal function is /// to extend the value or shape of a preceding alphabetic scalar. /// /// Typical extenders are length and iteration marks. /// /// This property corresponds to the "Extender" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isExtender: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_EXTENDER) } /// A Boolean value indicating whether the scalar is excluded from /// composition when performing Unicode normalization. /// /// This property corresponds to the "Full_Composition_Exclusion" property in /// the [Unicode Standard](http://www.unicode.org/versions/latest/). public var isFullCompositionExclusion: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_FULL_COMPOSITION_EXCLUSION) } /// A Boolean value indicating whether the scalar is a grapheme base. /// /// A grapheme base can be thought of as a space-occupying glyph above or /// below which other non-spacing modifying glyphs can be applied. For /// example, when the character `é` is represented in its decomposed form, /// the grapheme base is "e" (U+0065 LATIN SMALL LETTER E) and it is followed /// by a single grapheme extender, U+0301 COMBINING ACUTE ACCENT. /// /// The set of scalars for which `isGraphemeBase` is `true` is disjoint by /// definition from the set for which `isGraphemeExtend` is `true`. /// /// This property corresponds to the "Grapheme_Base" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isGraphemeBase: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_GRAPHEME_BASE) } /// A Boolean value indicating whether the scalar is a grapheme extender. /// /// A grapheme extender can be thought of primarily as a non-spacing glyph /// that is applied above or below another glyph. For example, when the /// character `é` is represented in its decomposed form, the grapheme base is /// "e" (U+0065 LATIN SMALL LETTER E) and it is followed by a single grapheme /// extender, U+0301 COMBINING ACUTE ACCENT. /// /// The set of scalars for which `isGraphemeExtend` is `true` is disjoint by /// definition from the set for which `isGraphemeBase` is `true`. /// /// This property corresponds to the "Grapheme_Extend" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isGraphemeExtend: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_GRAPHEME_EXTEND) } /// A Boolean value indicating whether the scalar is one that is commonly /// used for the representation of hexadecimal numbers or a compatibility /// equivalent. /// /// This property is `true` for all scalars for which `isASCIIHexDigit` is /// `true` as well as for their CJK halfwidth and fullwidth variants. /// /// This property corresponds to the "Hex_Digit" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isHexDigit: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_HEX_DIGIT) } /// A Boolean value indicating whether the scalar is one which is /// recommended to be allowed to appear in a non-starting position in a /// programming language identifier. /// /// Applications that store identifiers in NFKC normalized form should instead /// use `isXIDContinue` to check whether a scalar is a valid identifier /// character. /// /// This property corresponds to the "ID_Continue" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isIDContinue: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_ID_CONTINUE) } /// A Boolean value indicating whether the scalar is one which is /// recommended to be allowed to appear in a starting position in a /// programming language identifier. /// /// Applications that store identifiers in NFKC normalized form should instead /// use `isXIDStart` to check whether a scalar is a valid identifier /// character. /// /// This property corresponds to the "ID_Start" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isIDStart: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_ID_START) } /// A Boolean value indicating whether the scalar is considered to be a /// CJKV (Chinese, Japanese, Korean, and Vietnamese) or other siniform /// (Chinese writing-related) ideograph. /// /// This property roughly defines the class of "Chinese characters" and does /// not include characters of other logographic scripts such as Cuneiform or /// Egyptian Hieroglyphs. /// /// This property corresponds to the "Ideographic" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isIdeographic: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_IDEOGRAPHIC) } /// A Boolean value indicating whether the scalar is an ideographic /// description character that determines how the two ideographic characters /// or ideographic description sequences that follow it are to be combined to /// form a single character. /// /// Ideographic description characters are technically printable characters, /// but advanced rendering engines may use them to approximate ideographs that /// are otherwise unrepresentable. /// /// This property corresponds to the "IDS_Binary_Operator" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isIDSBinaryOperator: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_IDS_BINARY_OPERATOR) } /// A Boolean value indicating whether the scalar is an ideographic /// description character that determines how the three ideographic characters /// or ideographic description sequences that follow it are to be combined to /// form a single character. /// /// Ideographic description characters are technically printable characters, /// but advanced rendering engines may use them to approximate ideographs that /// are otherwise unrepresentable. /// /// This property corresponds to the "IDS_Trinary_Operator" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isIDSTrinaryOperator: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_IDS_TRINARY_OPERATOR) } /// A Boolean value indicating whether the scalar is a format control /// character that has a specific function in controlling cursive joining and /// ligation. /// /// There are two scalars for which this property is `true`: /// /// * When U+200C ZERO WIDTH NON-JOINER is inserted between two characters, it /// directs the rendering engine to render them separately/disconnected when /// it might otherwise render them as a ligature. For example, a rendering /// engine might display "fl" in English as a connected glyph; inserting the /// zero width non-joiner would force them to be rendered as disconnected /// glyphs. /// /// * When U+200D ZERO WIDTH JOINER is inserted between two characters, it /// directs the rendering engine to render them as a connected glyph when it /// would otherwise render them independently. The zero width joiner is also /// used to construct complex emoji from sequences of base emoji characters. /// For example, the various "family" emoji are encoded as sequences of man, /// woman, or child emoji that are interleaved with zero width joiners. /// /// This property corresponds to the "Join_Control" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isJoinControl: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_JOIN_CONTROL) } /// A Boolean value indicating whether the scalar requires special handling /// for operations involving ordering, such as sorting and searching. /// /// This property applies to a small number of spacing vowel letters occurring /// in some Southeast Asian scripts like Thai and Lao, which use a visual /// order display model. Such letters are stored in text ahead of /// syllable-initial consonants. /// /// This property corresponds to the "Logical_Order_Exception" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isLogicalOrderException: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_LOGICAL_ORDER_EXCEPTION) } /// A Boolean value indicating whether the scalar's letterform is /// considered lowercase. /// /// This property corresponds to the "Lowercase" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isLowercase: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_LOWERCASE) } /// A Boolean value indicating whether the scalar is one that naturally /// appears in mathematical contexts. /// /// The set of scalars for which this property is `true` includes mathematical /// operators and symbols as well as specific Greek and Hebrew letter /// variants that are categorized as symbols. Notably, it does _not_ contain /// the standard digits or Latin/Greek letter blocks; instead, it contains the /// mathematical Latin, Greek, and Arabic letters and numbers defined in the /// Supplemental Multilingual Plane. /// /// This property corresponds to the "Math" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isMath: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_MATH) } /// A Boolean value indicating whether the scalar is permanently reserved /// for internal use. /// /// This property corresponds to the "Noncharacter_Code_Point" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isNoncharacterCodePoint: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_NONCHARACTER_CODE_POINT) } /// A Boolean value indicating whether the scalar is one that is used in /// writing to surround quoted text. /// /// This property corresponds to the "Quotation_Mark" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isQuotationMark: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_QUOTATION_MARK) } /// A Boolean value indicating whether the scalar is a radical component of /// CJK characters, Tangut characters, or Yi syllables. /// /// These scalars are often the components of ideographic description /// sequences, as defined by the `isIDSBinaryOperator` and /// `isIDSTrinaryOperator` properties. /// /// This property corresponds to the "Radical" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isRadical: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_RADICAL) } /// A Boolean value indicating whether the scalar has a "soft dot" that /// disappears when a diacritic is placed over the scalar. /// /// For example, "i" is soft dotted because the dot disappears when adding an /// accent mark, as in "í". /// /// This property corresponds to the "Soft_Dotted" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isSoftDotted: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_SOFT_DOTTED) } /// A Boolean value indicating whether the scalar is a punctuation symbol /// that typically marks the end of a textual unit. /// /// This property corresponds to the "Terminal_Punctuation" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isTerminalPunctuation: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_TERMINAL_PUNCTUATION) } /// A Boolean value indicating whether the scalar is one of the unified /// CJK ideographs in the Unicode Standard. /// /// This property is false for CJK punctuation and symbols, as well as for /// compatibility ideographs (which canonically decompose to unified /// ideographs). /// /// This property corresponds to the "Unified_Ideograph" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isUnifiedIdeograph: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_UNIFIED_IDEOGRAPH) } /// A Boolean value indicating whether the scalar's letterform is /// considered uppercase. /// /// This property corresponds to the "Uppercase" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isUppercase: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_UPPERCASE) } /// A Boolean value indicating whether the scalar is a whitespace /// character. /// /// This property is `true` for scalars that are spaces, separator characters, /// and other control characters that should be treated as whitespace for the /// purposes of parsing text elements. /// /// This property corresponds to the "White_Space" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isWhitespace: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_WHITE_SPACE) } /// A Boolean value indicating whether the scalar is one which is /// recommended to be allowed to appear in a non-starting position in a /// programming language identifier, with adjustments made for NFKC normalized /// form. /// /// The set of scalars `[:XID_Continue:]` closes the set `[:ID_Continue:]` /// under NFKC normalization by removing any scalars whose normalized form is /// not of the form `[:ID_Continue:]*`. /// /// This property corresponds to the "XID_Continue" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isXIDContinue: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_XID_CONTINUE) } /// A Boolean value indicating whether the scalar is one which is /// recommended to be allowed to appear in a starting position in a /// programming language identifier, with adjustments made for NFKC normalized /// form. /// /// The set of scalars `[:XID_Start:]` closes the set `[:ID_Start:]` under /// NFKC normalization by removing any scalars whose normalized form is not of /// the form `[:ID_Start:] [:ID_Continue:]*`. /// /// This property corresponds to the "XID_Start" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isXIDStart: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_XID_START) } /// A Boolean value indicating whether the scalar is a punctuation mark /// that generally marks the end of a sentence. /// /// This property corresponds to the "Sentence_Terminal" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isSentenceTerminal: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_S_TERM) } /// A Boolean value indicating whether the scalar is a variation selector. /// /// Variation selectors allow rendering engines that support them to choose /// different glyphs to display for a particular code point. /// /// This property corresponds to the "Variation_Selector" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isVariationSelector: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_VARIATION_SELECTOR) } /// A Boolean value indicating whether the scalar is recommended to have /// syntactic usage in patterns represented in source code. /// /// This property corresponds to the "Pattern_Syntax" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isPatternSyntax: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_PATTERN_SYNTAX) } /// A Boolean value indicating whether the scalar is recommended to be /// treated as whitespace when parsing patterns represented in source code. /// /// This property corresponds to the "Pattern_White_Space" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isPatternWhitespace: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_PATTERN_WHITE_SPACE) } /// A Boolean value indicating whether the scalar is considered to be /// either lowercase, uppercase, or titlecase. /// /// Though similar in name, this property is *not* equivalent to /// `changesWhenCaseMapped`. The set of scalars for which `isCased` is `true` /// is a superset of those for which `changesWhenCaseMapped` is `true`. For /// example, the Latin small capitals that are used by the International /// Phonetic Alphabet have a case, but do not change when they are mapped to /// any of the other cases. /// /// This property corresponds to the "Cased" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isCased: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CASED) } /// A Boolean value indicating whether the scalar is ignored for casing /// purposes. /// /// This property corresponds to the "Case_Ignorable" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isCaseIgnorable: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CASE_IGNORABLE) } /// A Boolean value indicating whether the scalar's normalized form differs /// from the `lowercaseMapping` of each constituent scalar. /// /// This property corresponds to the "Changes_When_Lowercased" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var changesWhenLowercased: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_LOWERCASED) } /// A Boolean value indicating whether the scalar's normalized form differs /// from the `uppercaseMapping` of each constituent scalar. /// /// This property corresponds to the "Changes_When_Uppercased" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var changesWhenUppercased: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_UPPERCASED) } /// A Boolean value indicating whether the scalar's normalized form differs /// from the `titlecaseMapping` of each constituent scalar. /// /// This property corresponds to the "Changes_When_Titlecased" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var changesWhenTitlecased: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_TITLECASED) } /// A Boolean value indicating whether the scalar's normalized form differs /// from the case-fold mapping of each constituent scalar. /// /// This property corresponds to the "Changes_When_Casefolded" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var changesWhenCaseFolded: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_CASEFOLDED) } /// A Boolean value indicating whether the scalar may change when it /// undergoes case mapping. /// /// This property is `true` whenever one or more of `changesWhenLowercased`, /// `changesWhenUppercased`, or `changesWhenTitlecased` are `true`. /// /// This property corresponds to the "Changes_When_Casemapped" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var changesWhenCaseMapped: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_CASEMAPPED) } /// A Boolean value indicating whether the scalar is one that is not /// identical to its NFKC case-fold mapping. /// /// This property corresponds to the "Changes_When_NFKC_Casefolded" property /// in the [Unicode Standard](http://www.unicode.org/versions/latest/). public var changesWhenNFKCCaseFolded: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_NFKC_CASEFOLDED) } #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) // FIXME: These properties were introduced in ICU 57, but Ubuntu 16.04 comes // with ICU 55 so the values won't be correct there. Exclude them on // non-Darwin platforms for now; bundling ICU with the toolchain would resolve // this and other inconsistencies (https://bugs.swift.org/browse/SR-6076). /// A Boolean value indicating whether the scalar has an emoji /// presentation, whether or not it is the default. /// /// This property is true for scalars that are rendered as emoji by default /// and also for scalars that have a non-default emoji rendering when followed /// by U+FE0F VARIATION SELECTOR-16. This includes some scalars that are not /// typically considered to be emoji: /// /// let scalars: [Unicode.Scalar] = ["😎", "$", "0"] /// for s in scalars { /// print(s, "-->", s.isEmoji) /// } /// // 😎 --> true /// // $ --> false /// // 0 --> true /// /// The final result is true because the ASCII digits have non-default emoji /// presentations; some platforms render these with an alternate appearance. /// /// Because of this behavior, testing `isEmoji` alone on a single scalar is /// insufficient to determine if a unit of text is rendered as an emoji; a /// correct test requires inspecting multiple scalars in a `Character`. In /// addition to checking whether the base scalar has `isEmoji == true`, you /// must also check its default presentation (see `isEmojiPresentation`) and /// determine whether it is followed by a variation selector that would modify /// the presentation. /// /// This property corresponds to the "Emoji" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). @available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *) public var isEmoji: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_EMOJI) } /// A Boolean value indicating whether the scalar is one that should be /// rendered with an emoji presentation, rather than a text presentation, by /// default. /// /// Scalars that have default to emoji presentation can be followed by /// U+FE0E VARIATION SELECTOR-15 to request the text presentation of the /// scalar instead. Likewise, scalars that default to text presentation can /// be followed by U+FE0F VARIATION SELECTOR-16 to request the emoji /// presentation. /// /// This property corresponds to the "Emoji_Presentation" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). @available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *) public var isEmojiPresentation: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_EMOJI_PRESENTATION) } /// A Boolean value indicating whether the scalar is one that can modify /// a base emoji that precedes it. /// /// The Fitzpatrick skin types are examples of emoji modifiers; they change /// the appearance of the preceding emoji base (that is, a scalar for which /// `isEmojiModifierBase` is true) by rendering it with a different skin tone. /// /// This property corresponds to the "Emoji_Modifier" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). @available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *) public var isEmojiModifier: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_EMOJI_MODIFIER) } /// A Boolean value indicating whether the scalar is one whose appearance /// can be changed by an emoji modifier that follows it. /// /// This property corresponds to the "Emoji_Modifier_Base" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). @available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *) public var isEmojiModifierBase: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_EMOJI_MODIFIER_BASE) } #endif } /// Case mapping properties. extension Unicode.Scalar.Properties { // The type of ICU case conversion functions. internal typealias _U_StrToX = ( /* dest */ UnsafeMutablePointer<__swift_stdlib_UChar>, /* destCapacity */ Int32, /* src */ UnsafePointer<__swift_stdlib_UChar>, /* srcLength */ Int32, /* locale */ UnsafePointer<Int8>, /* pErrorCode */ UnsafeMutablePointer<__swift_stdlib_UErrorCode> ) -> Int32 /// Applies the given ICU string mapping to the scalar. /// /// This function attempts first to write the mapping into a stack-based /// UTF-16 buffer capable of holding 16 code units, which should be enough for /// all current case mappings. In the event more space is needed, it will be /// allocated on the heap. internal func _applyMapping(_ u_strTo: _U_StrToX) -> String { // TODO(String performance): Stack buffer first and then detect real count let count = 64 var array = Array<UInt16>(repeating: 0, count: count) let len: Int = array.withUnsafeMutableBufferPointer { bufPtr in return _scalar.withUTF16CodeUnits { utf16 in var err = __swift_stdlib_U_ZERO_ERROR let correctSize = u_strTo( bufPtr.baseAddress._unsafelyUnwrappedUnchecked, Int32(bufPtr.count), utf16.baseAddress._unsafelyUnwrappedUnchecked, Int32(utf16.count), "", &err) guard err.isSuccess else { fatalError("Unexpected error case-converting Unicode scalar.") } // TODO: _internalInvariant(count == correctSize, "inconsistent ICU behavior") return Int(correctSize) } } // TODO: replace `len` with `count` return array[..<len].withUnsafeBufferPointer { return String._uncheckedFromUTF16($0) } } /// The lowercase mapping of the scalar. /// /// This property is a `String`, not a `Unicode.Scalar` or `Character`, /// because some mappings may transform a scalar into multiple scalars or /// graphemes. For example, the character "İ" (U+0130 LATIN CAPITAL LETTER I /// WITH DOT ABOVE) becomes two scalars (U+0069 LATIN SMALL LETTER I, U+0307 /// COMBINING DOT ABOVE) when converted to lowercase. /// /// This property corresponds to the "Lowercase_Mapping" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var lowercaseMapping: String { return _applyMapping(__swift_stdlib_u_strToLower) } /// The titlecase mapping of the scalar. /// /// This property is a `String`, not a `Unicode.Scalar` or `Character`, /// because some mappings may transform a scalar into multiple scalars or /// graphemes. For example, the ligature "fi" (U+FB01 LATIN SMALL LIGATURE FI) /// becomes "Fi" (U+0046 LATIN CAPITAL LETTER F, U+0069 LATIN SMALL LETTER I) /// when converted to titlecase. /// /// This property corresponds to the "Titlecase_Mapping" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var titlecaseMapping: String { return _applyMapping { ptr, cap, src, len, locale, err in return __swift_stdlib_u_strToTitle(ptr, cap, src, len, nil, locale, err) } } /// The uppercase mapping of the scalar. /// /// This property is a `String`, not a `Unicode.Scalar` or `Character`, /// because some mappings may transform a scalar into multiple scalars or /// graphemes. For example, the German letter "ß" (U+00DF LATIN SMALL LETTER /// SHARP S) becomes "SS" (U+0053 LATIN CAPITAL LETTER S, U+0053 LATIN CAPITAL /// LETTER S) when converted to uppercase. /// /// This property corresponds to the "Uppercase_Mapping" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var uppercaseMapping: String { return _applyMapping(__swift_stdlib_u_strToUpper) } } extension Unicode { /// A version of the Unicode Standard represented by its major and minor /// components. public typealias Version = (major: Int, minor: Int) } extension Unicode.Scalar.Properties { /// The earliest version of the Unicode Standard in which the scalar was /// assigned. /// /// This value is `nil` for code points that have not yet been assigned. /// /// This property corresponds to the "Age" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var age: Unicode.Version? { var versionInfo: __swift_stdlib_UVersionInfo = (0, 0, 0, 0) withUnsafeMutablePointer(to: &versionInfo) { tuplePtr in tuplePtr.withMemoryRebound(to: UInt8.self, capacity: 4) { versionInfoPtr in __swift_stdlib_u_charAge(icuValue, versionInfoPtr) } } guard versionInfo.0 != 0 else { return nil } return (major: Int(versionInfo.0), minor: Int(versionInfo.1)) } } extension Unicode { /// The most general classification of a Unicode scalar. /// /// The general category of a scalar is its "first-order, most usual /// categorization". It does not attempt to cover multiple uses of some /// scalars, such as the use of letters to represent Roman numerals. public enum GeneralCategory { /// An uppercase letter. /// /// This value corresponds to the category `Uppercase_Letter` (abbreviated /// `Lu`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case uppercaseLetter /// A lowercase letter. /// /// This value corresponds to the category `Lowercase_Letter` (abbreviated /// `Ll`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case lowercaseLetter /// A digraph character whose first part is uppercase. /// /// This value corresponds to the category `Titlecase_Letter` (abbreviated /// `Lt`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case titlecaseLetter /// A modifier letter. /// /// This value corresponds to the category `Modifier_Letter` (abbreviated /// `Lm`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case modifierLetter /// Other letters, including syllables and ideographs. /// /// This value corresponds to the category `Other_Letter` (abbreviated /// `Lo`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case otherLetter /// A non-spacing combining mark with zero advance width (abbreviated Mn). /// /// This value corresponds to the category `Nonspacing_Mark` (abbreviated /// `Mn`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case nonspacingMark /// A spacing combining mark with positive advance width. /// /// This value corresponds to the category `Spacing_Mark` (abbreviated `Mc`) /// in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case spacingMark /// An enclosing combining mark. /// /// This value corresponds to the category `Enclosing_Mark` (abbreviated /// `Me`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case enclosingMark /// A decimal digit. /// /// This value corresponds to the category `Decimal_Number` (abbreviated /// `Nd`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case decimalNumber /// A letter-like numeric character. /// /// This value corresponds to the category `Letter_Number` (abbreviated /// `Nl`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case letterNumber /// A numeric character of another type. /// /// This value corresponds to the category `Other_Number` (abbreviated `No`) /// in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case otherNumber /// A connecting punctuation mark, like a tie. /// /// This value corresponds to the category `Connector_Punctuation` /// (abbreviated `Pc`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case connectorPunctuation /// A dash or hyphen punctuation mark. /// /// This value corresponds to the category `Dash_Punctuation` (abbreviated /// `Pd`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case dashPunctuation /// An opening punctuation mark of a pair. /// /// This value corresponds to the category `Open_Punctuation` (abbreviated /// `Ps`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case openPunctuation /// A closing punctuation mark of a pair. /// /// This value corresponds to the category `Close_Punctuation` (abbreviated /// `Pe`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case closePunctuation /// An initial quotation mark. /// /// This value corresponds to the category `Initial_Punctuation` /// (abbreviated `Pi`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case initialPunctuation /// A final quotation mark. /// /// This value corresponds to the category `Final_Punctuation` (abbreviated /// `Pf`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case finalPunctuation /// A punctuation mark of another type. /// /// This value corresponds to the category `Other_Punctuation` (abbreviated /// `Po`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case otherPunctuation /// A symbol of mathematical use. /// /// This value corresponds to the category `Math_Symbol` (abbreviated `Sm`) /// in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case mathSymbol /// A currency sign. /// /// This value corresponds to the category `Currency_Symbol` (abbreviated /// `Sc`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case currencySymbol /// A non-letterlike modifier symbol. /// /// This value corresponds to the category `Modifier_Symbol` (abbreviated /// `Sk`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case modifierSymbol /// A symbol of another type. /// /// This value corresponds to the category `Other_Symbol` (abbreviated /// `So`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case otherSymbol /// A space character of non-zero width. /// /// This value corresponds to the category `Space_Separator` (abbreviated /// `Zs`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case spaceSeparator /// A line separator, which is specifically (and only) U+2028 LINE /// SEPARATOR. /// /// This value corresponds to the category `Line_Separator` (abbreviated /// `Zl`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case lineSeparator /// A paragraph separator, which is specifically (and only) U+2029 PARAGRAPH /// SEPARATOR. /// /// This value corresponds to the category `Paragraph_Separator` /// (abbreviated `Zp`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case paragraphSeparator /// A C0 or C1 control code. /// /// This value corresponds to the category `Control` (abbreviated `Cc`) in /// the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case control /// A format control character. /// /// This value corresponds to the category `Format` (abbreviated `Cf`) in /// the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case format /// A surrogate code point. /// /// This value corresponds to the category `Surrogate` (abbreviated `Cs`) in /// the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case surrogate /// A private-use character. /// /// This value corresponds to the category `Private_Use` (abbreviated `Co`) /// in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case privateUse /// A reserved unassigned code point or a non-character. /// /// This value corresponds to the category `Unassigned` (abbreviated `Cn`) /// in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case unassigned internal init(rawValue: __swift_stdlib_UCharCategory) { switch rawValue { case __swift_stdlib_U_UNASSIGNED: self = .unassigned case __swift_stdlib_U_UPPERCASE_LETTER: self = .uppercaseLetter case __swift_stdlib_U_LOWERCASE_LETTER: self = .lowercaseLetter case __swift_stdlib_U_TITLECASE_LETTER: self = .titlecaseLetter case __swift_stdlib_U_MODIFIER_LETTER: self = .modifierLetter case __swift_stdlib_U_OTHER_LETTER: self = .otherLetter case __swift_stdlib_U_NON_SPACING_MARK: self = .nonspacingMark case __swift_stdlib_U_ENCLOSING_MARK: self = .enclosingMark case __swift_stdlib_U_COMBINING_SPACING_MARK: self = .spacingMark case __swift_stdlib_U_DECIMAL_DIGIT_NUMBER: self = .decimalNumber case __swift_stdlib_U_LETTER_NUMBER: self = .letterNumber case __swift_stdlib_U_OTHER_NUMBER: self = .otherNumber case __swift_stdlib_U_SPACE_SEPARATOR: self = .spaceSeparator case __swift_stdlib_U_LINE_SEPARATOR: self = .lineSeparator case __swift_stdlib_U_PARAGRAPH_SEPARATOR: self = .paragraphSeparator case __swift_stdlib_U_CONTROL_CHAR: self = .control case __swift_stdlib_U_FORMAT_CHAR: self = .format case __swift_stdlib_U_PRIVATE_USE_CHAR: self = .privateUse case __swift_stdlib_U_SURROGATE: self = .surrogate case __swift_stdlib_U_DASH_PUNCTUATION: self = .dashPunctuation case __swift_stdlib_U_START_PUNCTUATION: self = .openPunctuation case __swift_stdlib_U_END_PUNCTUATION: self = .closePunctuation case __swift_stdlib_U_CONNECTOR_PUNCTUATION: self = .connectorPunctuation case __swift_stdlib_U_OTHER_PUNCTUATION: self = .otherPunctuation case __swift_stdlib_U_MATH_SYMBOL: self = .mathSymbol case __swift_stdlib_U_CURRENCY_SYMBOL: self = .currencySymbol case __swift_stdlib_U_MODIFIER_SYMBOL: self = .modifierSymbol case __swift_stdlib_U_OTHER_SYMBOL: self = .otherSymbol case __swift_stdlib_U_INITIAL_PUNCTUATION: self = .initialPunctuation case __swift_stdlib_U_FINAL_PUNCTUATION: self = .finalPunctuation default: fatalError("Unknown general category \(rawValue)") } } } } // Internal helpers extension Unicode.GeneralCategory { internal var _isSymbol: Bool { switch self { case .mathSymbol, .currencySymbol, .modifierSymbol, .otherSymbol: return true default: return false } } internal var _isPunctuation: Bool { switch self { case .connectorPunctuation, .dashPunctuation, .openPunctuation, .closePunctuation, .initialPunctuation, .finalPunctuation, .otherPunctuation: return true default: return false } } } extension Unicode.Scalar.Properties { /// The general category (most usual classification) of the scalar. /// /// This property corresponds to the "General_Category" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var generalCategory: Unicode.GeneralCategory { let rawValue = __swift_stdlib_UCharCategory( __swift_stdlib_UCharCategory.RawValue( __swift_stdlib_u_getIntPropertyValue( icuValue, __swift_stdlib_UCHAR_GENERAL_CATEGORY))) return Unicode.GeneralCategory(rawValue: rawValue) } } extension Unicode.Scalar.Properties { internal func _scalarName( _ choice: __swift_stdlib_UCharNameChoice ) -> String? { var err = __swift_stdlib_U_ZERO_ERROR let count = Int(__swift_stdlib_u_charName(icuValue, choice, nil, 0, &err)) guard count > 0 else { return nil } // ICU writes a trailing null, so we have to save room for it as well. var array = Array<UInt8>(repeating: 0, count: count + 1) return array.withUnsafeMutableBufferPointer { bufPtr in var err = __swift_stdlib_U_ZERO_ERROR let correctSize = __swift_stdlib_u_charName( icuValue, choice, UnsafeMutableRawPointer(bufPtr.baseAddress._unsafelyUnwrappedUnchecked) .assumingMemoryBound(to: Int8.self), Int32(bufPtr.count), &err) guard err.isSuccess else { fatalError("Unexpected error case-converting Unicode scalar.") } _internalInvariant(count == correctSize, "inconsistent ICU behavior") return String._fromASCII( UnsafeBufferPointer(rebasing: bufPtr[..<count])) } } /// The published name of the scalar. /// /// Some scalars, such as control characters, do not have a value for this /// property in the Unicode Character Database. For such scalars, this /// property is `nil`. /// /// This property corresponds to the "Name" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var name: String? { return _scalarName(__swift_stdlib_U_UNICODE_CHAR_NAME) } /// The normative formal alias of the scalar. /// /// The name of a scalar is immutable and never changed in future versions of /// the Unicode Standard. The `nameAlias` property is provided to issue /// corrections if a name was issued erroneously. For example, the `name` of /// U+FE18 is "PRESENTATION FORM FOR VERTICAL RIGHT WHITE LENTICULAR BRAKCET" /// (note that "BRACKET" is misspelled). The `nameAlias` property then /// contains the corrected name. /// /// If a scalar has no alias, this property is `nil`. /// /// This property corresponds to the "Name_Alias" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var nameAlias: String? { return _scalarName(__swift_stdlib_U_CHAR_NAME_ALIAS) } } extension Unicode { /// The classification of a scalar used in the Canonical Ordering Algorithm /// defined by the Unicode Standard. /// /// Canonical combining classes are used by the ordering algorithm to /// determine if two sequences of combining marks should be considered /// canonically equivalent (that is, identical in interpretation). Two /// sequences are canonically equivalent if they are equal when sorting the /// scalars in ascending order by their combining class. /// /// For example, consider the sequence `"\u{0041}\u{0301}\u{0316}"` (LATIN /// CAPITAL LETTER A, COMBINING ACUTE ACCENT, COMBINING GRAVE ACCENT BELOW). /// The combining classes of these scalars have the numeric values 0, 230, and /// 220, respectively. Sorting these scalars by their combining classes yields /// `"\u{0041}\u{0316}\u{0301}"`, so two strings that differ only by the /// ordering of those scalars would compare as equal: /// /// let aboveBeforeBelow = "\u{0041}\u{0301}\u{0316}" /// let belowBeforeAbove = "\u{0041}\u{0316}\u{0301}" /// print(aboveBeforeBelow == belowBeforeAbove) /// // Prints "true" /// /// Named and Unnamed Combining Classes /// =================================== /// /// Canonical combining classes are defined in the Unicode Standard as /// integers in the range `0...254`. For convenience, the standard assigns /// symbolic names to a subset of these combining classes. /// /// The `CanonicalCombiningClass` type conforms to `RawRepresentable` with a /// raw value of type `UInt8`. You can create instances of the type by using /// the static members named after the symbolic names, or by using the /// `init(rawValue:)` initializer. /// /// let overlayClass = Unicode.CanonicalCombiningClass(rawValue: 1) /// let overlayClassIsOverlay = overlayClass == .overlay /// // overlayClassIsOverlay == true public struct CanonicalCombiningClass: Comparable, Hashable, RawRepresentable { /// Base glyphs that occupy their own space and do not combine with others. public static let notReordered = CanonicalCombiningClass(rawValue: 0) /// Marks that overlay a base letter or symbol. public static let overlay = CanonicalCombiningClass(rawValue: 1) /// Diacritic nukta marks in Brahmi-derived scripts. public static let nukta = CanonicalCombiningClass(rawValue: 7) /// Combining marks that are attached to hiragana and katakana to indicate /// voicing changes. public static let kanaVoicing = CanonicalCombiningClass(rawValue: 8) /// Diacritic virama marks in Brahmi-derived scripts. public static let virama = CanonicalCombiningClass(rawValue: 9) /// Marks attached at the bottom left. public static let attachedBelowLeft = CanonicalCombiningClass(rawValue: 200) /// Marks attached directly below. public static let attachedBelow = CanonicalCombiningClass(rawValue: 202) /// Marks attached directly above. public static let attachedAbove = CanonicalCombiningClass(rawValue: 214) /// Marks attached at the top right. public static let attachedAboveRight = CanonicalCombiningClass(rawValue: 216) /// Distinct marks at the bottom left. public static let belowLeft = CanonicalCombiningClass(rawValue: 218) /// Distinct marks directly below. public static let below = CanonicalCombiningClass(rawValue: 220) /// Distinct marks at the bottom right. public static let belowRight = CanonicalCombiningClass(rawValue: 222) /// Distinct marks to the left. public static let left = CanonicalCombiningClass(rawValue: 224) /// Distinct marks to the right. public static let right = CanonicalCombiningClass(rawValue: 226) /// Distinct marks at the top left. public static let aboveLeft = CanonicalCombiningClass(rawValue: 228) /// Distinct marks directly above. public static let above = CanonicalCombiningClass(rawValue: 230) /// Distinct marks at the top right. public static let aboveRight = CanonicalCombiningClass(rawValue: 232) /// Distinct marks subtending two bases. public static let doubleBelow = CanonicalCombiningClass(rawValue: 233) /// Distinct marks extending above two bases. public static let doubleAbove = CanonicalCombiningClass(rawValue: 234) /// Greek iota subscript only (U+0345 COMBINING GREEK YPOGEGRAMMENI). public static let iotaSubscript = CanonicalCombiningClass(rawValue: 240) /// The raw integer value of the canonical combining class. public let rawValue: UInt8 /// Creates a new canonical combining class with the given raw integer /// value. /// /// - Parameter rawValue: The raw integer value of the canonical combining /// class. public init(rawValue: UInt8) { self.rawValue = rawValue } public static func == ( lhs: CanonicalCombiningClass, rhs: CanonicalCombiningClass ) -> Bool { return lhs.rawValue == rhs.rawValue } public static func < ( lhs: CanonicalCombiningClass, rhs: CanonicalCombiningClass ) -> Bool { return lhs.rawValue < rhs.rawValue } public var hashValue: Int { return rawValue.hashValue } public func hash(into hasher: inout Hasher) { hasher.combine(rawValue) } } } extension Unicode.Scalar.Properties { /// The canonical combining class of the scalar. /// /// This property corresponds to the "Canonical_Combining_Class" property in /// the [Unicode Standard](http://www.unicode.org/versions/latest/). public var canonicalCombiningClass: Unicode.CanonicalCombiningClass { let rawValue = UInt8(__swift_stdlib_u_getIntPropertyValue( icuValue, __swift_stdlib_UCHAR_CANONICAL_COMBINING_CLASS)) return Unicode.CanonicalCombiningClass(rawValue: rawValue) } } extension Unicode { /// The numeric type of a scalar. /// /// Scalars with a non-nil numeric type include numbers, fractions, numeric /// superscripts and subscripts, and circled or otherwise decorated number /// glyphs. /// /// Some letterlike scalars used in numeric systems, such as Greek or Latin /// letters, do not have a non-nil numeric type, in order to prevent programs /// from incorrectly interpreting them as numbers in non-numeric contexts. public enum NumericType { /// A digit that is commonly understood to form base-10 numbers. /// /// Specifically, scalars have this numeric type if they occupy a contiguous /// range of code points representing numeric values `0...9`. case decimal /// A digit that does not meet the requirements of the `decimal` numeric /// type. /// /// Scalars with this numeric type are often those that represent a decimal /// digit but would not typically be used to write a base-10 number, such /// as "④" (U+2463 CIRCLED DIGIT FOUR). /// /// As of Unicode 6.3, any new scalars that represent numbers but do not /// meet the requirements of `decimal` will have numeric type `numeric`, /// and programs can treat `digit` and `numeric` equivalently. case digit /// A digit that does not meet the requirements of the `decimal` numeric /// type or a non-digit numeric value. /// /// This numeric type includes fractions such as "⅕" (U+2155 VULGAR /// FRACITON ONE FIFTH), numerical CJK ideographs like "兆" (U+5146 CJK /// UNIFIED IDEOGRAPH-5146), and other scalars that are not decimal digits /// used positionally in the writing of base-10 numbers. /// /// As of Unicode 6.3, any new scalars that represent numbers but do not /// meet the requirements of `decimal` will have numeric type `numeric`, /// and programs can treat `digit` and `numeric` equivalently. case numeric internal init?(rawValue: __swift_stdlib_UNumericType) { switch rawValue { case __swift_stdlib_U_NT_NONE: return nil case __swift_stdlib_U_NT_DECIMAL: self = .decimal case __swift_stdlib_U_NT_DIGIT: self = .digit case __swift_stdlib_U_NT_NUMERIC: self = .numeric default: fatalError("Unknown numeric type \(rawValue)") } } } } /// Numeric properties of scalars. extension Unicode.Scalar.Properties { /// The numeric type of the scalar. /// /// For scalars that represent a number, `numericType` is the numeric type /// of the scalar. For all other scalars, this property is `nil`. /// /// let scalars: [Unicode.Scalar] = ["4", "④", "⅕", "X"] /// for scalar in scalars { /// print(scalar, "-->", scalar.properties.numericType) /// } /// // 4 --> decimal /// // ④ --> digit /// // ⅕ --> numeric /// // X --> nil /// /// This property corresponds to the "Numeric_Type" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var numericType: Unicode.NumericType? { let rawValue = __swift_stdlib_UNumericType( __swift_stdlib_UNumericType.RawValue( __swift_stdlib_u_getIntPropertyValue( icuValue, __swift_stdlib_UCHAR_NUMERIC_TYPE))) return Unicode.NumericType(rawValue: rawValue) } /// The numeric value of the scalar. /// /// For scalars that represent a numeric value, `numericValue` is the whole /// or fractional value. For all other scalars, this property is `nil`. /// /// let scalars: [Unicode.Scalar] = ["4", "④", "⅕", "X"] /// for scalar in scalars { /// print(scalar, "-->", scalar.properties.numericValue) /// } /// // 4 --> 4.0 /// // ④ --> 4.0 /// // ⅕ --> 0.2 /// // X --> nil /// /// This property corresponds to the "Numeric_Value" property in the [Unicode /// Standard](http://www.unicode.org/versions/latest/). public var numericValue: Double? { let icuNoNumericValue: Double = -123456789 let result = __swift_stdlib_u_getNumericValue(icuValue) return result != icuNoNumericValue ? result : nil } }
apache-2.0
4c0f19efa0d6e9bf62abe08aab70b86e
40.668803
86
0.692751
4.301691
false
false
false
false
krad/buffie
Sources/Buffie/Capture/Camera/DeviceHelpers.swift
1
1710
import Foundation import AVFoundation public extension AVCaptureDevice { public static func videoDevices() -> [AVCaptureDevice] { return AVCaptureDevice.devices(for: .video) } public static func audioDevices() -> [AVCaptureDevice] { return AVCaptureDevice.devices(for: .audio) } public static func videoDevicesDictionary() -> [String: String] { return self.dictionary(for: self.videoDevices()) } public static func audioDevicesDictionary() -> [String: String] { return self.dictionary(for: self.audioDevices()) } private static func dictionary(for devices: [AVCaptureDevice]) -> [String: String] { var result: [String: String] = [:] for device in devices { result[device.uniqueID] = device.localizedName } return result } static func firstDevice(for mediaType: AVMediaType, in position: AVCaptureDevice.Position) throws -> AVCaptureDevice { let devices = AVCaptureDevice.devices(for: mediaType).filter { $0.position != position } if let device = devices.first { return device } else { throw CaptureDeviceError.noDeviceAvailable(type: mediaType) } } } public extension AVCaptureDeviceInput { public static func input(for deviceID: String?) throws -> AVCaptureDeviceInput? { if let devID = deviceID { if let device = AVCaptureDevice(uniqueID: devID) { return try AVCaptureDeviceInput(device: device) } else { throw CaptureDeviceError.deviceNotFound(deviceID: devID) } } return nil } }
mit
ad853d7896daf5190790b637f790f7e8
30.666667
122
0.626316
5.089286
false
false
false
false
blockstack/blockstack-portal
native/macos/Blockstack/Pods/Swifter/Sources/HttpParser.swift
2
3598
// // HttpParser.swift // Swifter // // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved. // import Foundation enum HttpParserError: Error { case InvalidStatusLine(String) } public class HttpParser { public init() { } public func readHttpRequest(_ socket: Socket) throws -> HttpRequest { let statusLine = try socket.readLine() let statusLineTokens = statusLine.components(separatedBy: " ") if statusLineTokens.count < 3 { throw HttpParserError.InvalidStatusLine(statusLine) } let request = HttpRequest() request.method = statusLineTokens[0] request.path = statusLineTokens[1] request.queryParams = extractQueryParams(request.path) request.headers = try readHeaders(socket) if let contentLength = request.headers["content-length"], let contentLengthValue = Int(contentLength) { request.body = try readBody(socket, size: contentLengthValue) } return request } private func extractQueryParams(_ url: String) -> [(String, String)] { #if compiler(>=5.0) guard let questionMarkIndex = url.firstIndex(of: "?") else { return [] } #else guard let questionMarkIndex = url.index(of: "?") else { return [] } #endif let queryStart = url.index(after: questionMarkIndex) guard url.endIndex > queryStart else { return [] } #if swift(>=4.0) let query = String(url[queryStart..<url.endIndex]) #else guard let query = String(url[queryStart..<url.endIndex]) else { return [] } #endif return query.components(separatedBy: "&") .reduce([(String, String)]()) { (c, s) -> [(String, String)] in #if compiler(>=5.0) guard let nameEndIndex = s.firstIndex(of: "=") else { return c } #else guard let nameEndIndex = s.index(of: "=") else { return c } #endif guard let name = String(s[s.startIndex..<nameEndIndex]).removingPercentEncoding else { return c } let valueStartIndex = s.index(nameEndIndex, offsetBy: 1) guard valueStartIndex < s.endIndex else { return c + [(name, "")] } guard let value = String(s[valueStartIndex..<s.endIndex]).removingPercentEncoding else { return c + [(name, "")] } return c + [(name, value)] } } private func readBody(_ socket: Socket, size: Int) throws -> [UInt8] { return try socket.read(length: size) } private func readHeaders(_ socket: Socket) throws -> [String: String] { var headers = [String: String]() while case let headerLine = try socket.readLine() , !headerLine.isEmpty { let headerTokens = headerLine.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: true).map(String.init) if let name = headerTokens.first, let value = headerTokens.last { headers[name.lowercased()] = value.trimmingCharacters(in: .whitespaces) } } return headers } func supportsKeepAlive(_ headers: [String: String]) -> Bool { if let value = headers["connection"] { return "keep-alive" == value.trimmingCharacters(in: .whitespaces) } return false } }
mpl-2.0
b0e8f4552b290ffde4dd85a10d295097
34.613861
127
0.561579
4.66537
false
false
false
false
TheDarkCode/Example-Swift-Apps
Exercises and Basic Principles/favorite-place-exercise/favorite-place-exercise/FenwayPhotosVC.swift
1
2097
// // FenwayPhotosVC.swift // favorite-place-exercise // // Created by Mark Hamilton on 2/20/16. // Copyright © 2016 dryverless. All rights reserved. // import UIKit class FenwayPhotosVC: UIViewController { @IBOutlet weak var focusImage: UIImageView! @IBOutlet weak var photoOne: RoundedButton! @IBOutlet weak var photoTwo: RoundedButton! @IBOutlet weak var photoThree: RoundedButton! @IBOutlet weak var photoFour: RoundedButton! @IBOutlet weak var photoFive: RoundedButton! convenience init() { self.init(nibName: "FenwayPhotosVC", bundle: nil) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func photoOnePressed(sender: AnyObject) { if let img1 = photoOne.imageView!.image { focusImage.image = img1 } } @IBAction func photoTwoPressed(sender: AnyObject) { if let img2 = photoTwo.imageView!.image { focusImage.image = img2 } } @IBAction func photoThreePressed(sender: AnyObject) { if let img3 = photoThree.imageView!.image { focusImage.image = img3 } } @IBAction func photoFourPressed(sender: AnyObject) { if let img4 = photoFour.imageView!.image { focusImage.image = img4 } } @IBAction func photoFivePressed(sender: AnyObject) { if let img5 = photoFive.imageView!.image { focusImage.image = img5 } } @IBAction func backButtonPressed(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } }
mit
7f4016c309f32b9149b5277ab949394f
26.578947
84
0.637405
4.556522
false
false
false
false
mkj-is/FuntastyKit
Sources/Protocols/Keyboardable.swift
1
1729
// // Keyboardable.swift // FuntastyKit // // Created by Matěj Jirásek on 18/10/2016. // Copyright © 2016 FUNTASTY Digital s.r.o. All rights reserved. // import Foundation import UIKit public class KeyboardableToken { let center: NotificationCenter let changeFrameToken: NSObjectProtocol let hideToken: NSObjectProtocol init(changeFrameToken: NSObjectProtocol, hideToken: NSObjectProtocol, center: NotificationCenter) { self.changeFrameToken = changeFrameToken self.hideToken = hideToken self.center = center } deinit { center.removeObserver(changeFrameToken) center.removeObserver(hideToken) } } public protocol Keyboardable: class { func keyboardChanges(height: CGFloat) } public extension Keyboardable { func useKeyboard() -> KeyboardableToken { let center = NotificationCenter.default let keyboardChangeFrameBlock: (Notification) -> Void = { [weak self] notification in guard let rect = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } self?.keyboardChanges(height: rect.size.height) } let keyboardWillHideBlock: (Notification) -> Void = { [weak self] _ in self?.keyboardChanges(height: 0) } let changeFrameToken = center.addObserver(forName: .UIKeyboardWillChangeFrame, object: nil, queue: nil, using: keyboardChangeFrameBlock) let hideToken = center.addObserver(forName: .UIKeyboardWillHide, object: nil, queue: nil, using: keyboardWillHideBlock) return KeyboardableToken(changeFrameToken: changeFrameToken, hideToken: hideToken, center: center) } }
mit
d8b04d5b2ea812e96f9663ed7ca1eeae
31.566038
144
0.698146
4.566138
false
false
false
false
davefoxy/SwiftBomb
SwiftBomb/Classes/Resources/ConceptResource.swift
1
5493
// // ConceptResource.swift // SwiftBomb // // Created by David Fox on 16/04/2016. // Copyright © 2016 David Fox. All rights reserved. // import Foundation /** A class representing a *Concept* on the Giant Bomb wiki. Examples include *Free To Play* and *Quick Time Event*. To retrieve extended info for a concept, call `fetchExtendedInfo(_:)` upon it. */ final public class ConceptResource: ResourceUpdating { /// The resource type. public let resourceType = ResourceType.concept /// Array of aliases the concept is known by. public fileprivate(set) var aliases: [String]? /// URL pointing to the concept detail resource. public fileprivate(set) var api_detail_url: URL? /// Date the concept was added to Giant Bomb. public fileprivate(set) var date_added: Date? /// Date the concept was last updated on Giant Bomb. public fileprivate(set) var date_last_updated: Date? /// Brief summary of the concept. public fileprivate(set) var deck: String? /// Description of the concept. public fileprivate(set) var description: String? /// Franchise where the concept made its first appearance. public fileprivate(set) var first_appeared_in_franchise: FranchiseResource? /// Game where the concept made its first appearance. public fileprivate(set) var first_appeared_in_game: GameResource? /// Unique ID of the concept. public fileprivate(set) var id: Int? /// Main image of the concept. public fileprivate(set) var image: ImageURLs? /// Name of the concept. public fileprivate(set) var name: String? /// URL pointing to the concept on Giant Bomb. public fileprivate(set) var site_detail_url: URL? /// Extended info. public var extendedInfo: ConceptExtendedInfo? /// Used to create a `ConceptResource` from JSON. public init(json: [String : AnyObject]) { id = json["id"] as? Int update(json: json) } func update(json: [String : AnyObject]) { aliases = (json["aliases"] as? String)?.newlineSeparatedStrings() ?? aliases api_detail_url = (json["api_detail_url"] as? String)?.url() as URL?? ?? api_detail_url date_added = (json["date_added"] as? String)?.dateRepresentation() as Date?? ?? date_added date_last_updated = (json["date_last_updated"] as? String)?.dateRepresentation() as Date?? ?? date_last_updated deck = json["deck"] as? String ?? deck description = json["description"] as? String ?? description if let firstAppearedInFranchiseJSON = json["first_appeared_in_franchise"] as? [String: AnyObject] { first_appeared_in_franchise = FranchiseResource(json: firstAppearedInFranchiseJSON) } if let firstAppearedInGameJSON = json["first_appeared_in_game"] as? [String: AnyObject] { first_appeared_in_game = GameResource(json: firstAppearedInGameJSON) } name = json["name"] as? String ?? name site_detail_url = (json["site_detail_url"] as? String)?.url() as URL?? ?? site_detail_url if let imageJSON = json["image"] as? [String: AnyObject] { image = ImageURLs(json: imageJSON) } } /// Pretty description of the concept. public var prettyDescription: String { return name ?? "Concept \(id)" } } /** Struct containing extended information for `ConceptResource`s. To retrieve, call `fetchExtendedInfo(_:)` upon the original resource then access the data on the resource's `extendedInfo` property. */ public struct ConceptExtendedInfo: ResourceExtendedInfo { /// Characters related to the concept. public fileprivate(set) var characters: [CharacterResource]? /// Concepts related to the concept. public fileprivate(set) var concepts: [ConceptResource]? /// Franchises related to the concept. public fileprivate(set) var franchises: [FranchiseResource]? /// Games the concept has appeared in. public fileprivate(set) var games: [GameResource]? /// Locations related to the concept. public fileprivate(set) var locations: [LocationResource]? /// Objects related to the concept. public fileprivate(set) var objects: [ObjectResource]? /// People who have worked with the concept. public fileprivate(set) var people: [PersonResource]? /// Other concepts related to the concept. public fileprivate(set) var related_concepts: [ConceptResource]? /// Used to create a `ConceptExtendedInfo` from JSON. public init(json: [String : AnyObject]) { update(json) } /// A method used for updating structs. Usually after further requests for more field data. public mutating func update(_ json: [String : AnyObject]) { characters = json.jsonMappedResources("characters") ?? characters concepts = json.jsonMappedResources("concepts") ?? concepts franchises = json.jsonMappedResources("franchises") ?? franchises games = json.jsonMappedResources("games") ?? games locations = json.jsonMappedResources("locations") ?? locations objects = json.jsonMappedResources("objects") ?? objects people = json.jsonMappedResources("people") ?? people related_concepts = json.jsonMappedResources("related_concepts") ?? related_concepts } }
mit
1c91bcc8b9e8b779e3597cc2bb5498fd
36.616438
196
0.658048
4.40417
false
false
false
false
juergen/ImageUtil
ImageUtil/Utils.swift
1
6403
// // Utils.swift // ImageUtil // // Created by Juergen Baumann on 11.01.15. // Copyright (c) 2015 Juergen Baumann. All rights reserved. // import Foundation class Utils { // --------------------------------------------------------------------------- // MARK: - generall functions // --------------------------------------------------------------------------- class func p(_ printMe:AnyObject?) { if let pm: AnyObject = printMe { print("\(pm)") } else { print("nil") } } // --------------------------------------------------------------------------- // MARK: - Directory // --------------------------------------------------------------------------- /** will delete directory if it already exists before creating it */ class func createOrEmptyDirectory(_ path:NSString) -> Bool { let fm = FileManager.default let exists:Bool = fm.fileExists(atPath: path as String) if (exists) { try! fm.removeItem(atPath: path as String) } do { try FileManager.default.createDirectory(atPath: path as String, withIntermediateDirectories: true, attributes: nil) } catch { return false } return true } /** will add counter (and increase it) to path as long as directory already exists before ceating it */ class func createDirectory(_ path:String) -> String? { let fm = FileManager.default let basePath = path var currentPath = path var counter : Int = 1 while (fm.fileExists(atPath: currentPath as String)) { currentPath = "\(basePath)_\(counter)" counter = counter + 1 } do { try FileManager.default.createDirectory(atPath: currentPath as String, withIntermediateDirectories: true, attributes: nil) } catch { return nil } return currentPath } // --------------------------------------------------------------------------- // MARK: - Image // --------------------------------------------------------------------------- @discardableResult class func convertToJpg(_ imageSource:CGImageSource, path:String) -> Bool { let destinationUrl:URL = URL(fileURLWithPath: path) let destinationImage = CGImageDestinationCreateWithURL(destinationUrl as CFURL, kUTTypeJPEG, 1, nil) CGImageDestinationAddImageFromSource(destinationImage!, imageSource, 0, nil) let result: Bool = CGImageDestinationFinalize(destinationImage!) return result } @discardableResult class func resizeImage(_ imageUrl:URL, max:Int, destinationPath:String) -> Bool { // get CGImageSource from provided ulr if let imageSource:CGImageSource = CGImageSourceCreateWithURL(imageUrl as CFURL, nil) { let options : [AnyHashable: Any] = [ kCGImageSourceThumbnailMaxPixelSize as AnyHashable: max, kCGImageSourceCreateThumbnailFromImageAlways as AnyHashable: true ] // scale image let scaledImage : CGImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options as CFDictionary)! // save image to provided destinationPath let destinationUrl : URL = URL(fileURLWithPath: destinationPath) let destinationImage = CGImageDestinationCreateWithURL(destinationUrl as CFURL, kUTTypeJPEG, 1, nil) CGImageDestinationAddImage(destinationImage!, scaledImage, nil) let result: Bool = CGImageDestinationFinalize(destinationImage!) return result } return false } @discardableResult class func renameToNumberedFiles(_ dirPath:String, filterExtension:String) -> Bool { let fm = FileManager.default // check if dir exists var isDir:ObjCBool = ObjCBool(false) let exists:Bool = fm.fileExists(atPath: dirPath, isDirectory:&isDir) if (!exists && !isDir.boolValue) { return false } // read content of dir let dirUrl : URL = URL(fileURLWithPath: dirPath) let contents : [URL] do { try contents = fm.contentsOfDirectory(at: dirUrl, includingPropertiesForKeys: [URLResourceKey.creationDateKey], options: .skipsHiddenFiles) } catch { return false } // filter file names var filteredFiles = [String:URL]() for url in contents { let pathExtension : String = url.pathExtension let fileName:String = url.lastPathComponent if filterExtension.contains(pathExtension.lowercased()) { filteredFiles[fileName] = url } } // sort file names let sortedFileNames = filteredFiles.keys.sorted() // rename for (index, fileName) in sortedFileNames.enumerated() { // e.g. "1" -> "001" let baseName = String(format: "%03d", index + 1) let newName = "\(baseName).\(filterExtension)" let sourceUrl:URL = filteredFiles[fileName]! let newURL:URL = dirUrl.appendingPathComponent(newName) do { try fm.moveItem(at: sourceUrl, to:newURL) print("renamed \(sourceUrl.lastPathComponent) -> \(newURL.lastPathComponent)") } catch { continue } } return true } class func getDateTime(_ imageSource:CGImageSource) -> Date { let imageDict = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as! [String:Any] if let tiffDict = imageDict["{TIFF}"] as? [String:Any], let dateTimeString = tiffDict["DateTime"] as? String { return dateTimeString.parseDate("yyyy:MM:dd HH:mm:ss") } return Date.defaultDate() } @discardableResult class func setDateTime(_ imageUrl:URL, date:Date) -> Bool { // if let imageSource:CGImageSource = CGImageSourceCreateWithURL(imageUrl as CFURL, nil) { let dateString = date.formattedString(Constant.imageDateTimeFormat) // build dictionary to update date time let tiff = [kCGImagePropertyTIFFDateTime as String:dateString] let exif = [ kCGImagePropertyExifDateTimeOriginal as String:dateString, kCGImagePropertyExifDateTimeDigitized as String:dateString ] let metaData = [ kCGImagePropertyTIFFDictionary as String:tiff, kCGImagePropertyExifDictionary as String:exif ] // update image with meta data let destination = CGImageDestinationCreateWithURL(imageUrl as CFURL, kUTTypeJPEG, 1, nil) CGImageDestinationAddImageFromSource(destination!,imageSource,0, metaData as CFDictionary) let result: Bool = CGImageDestinationFinalize(destination!) return result } return false } }
mit
13f95c2df9a69fd128f1f73b06e8496a
36.226744
128
0.633765
5.077716
false
false
false
false
realami/Msic
weekTwo/weekTwo/Controllers/ThirdTableViewController.swift
1
4663
// // ThirdTableViewController.swift // weekTwo // // Created by Cyan on 28/10/2017. // Copyright © 2017 Cyan. All rights reserved. // import UIKit enum TodoType: Int { case tyep1 case tyep2 case tyep3 case tyep4 } class Todo { var type: TodoType = .tyep1 var title: String = "" var date: String = "" init(type: TodoType, title: String, date: String) { self.date = date self.title = title self.type = type } } class ThirdTableViewController: UITableViewController { var dataSource = [Todo]() override func viewDidLoad() { super.viewDidLoad() title = "Todos" tableView.tableFooterView = UIView() for i in 0...3 { let todo = Todo(type: TodoType.init(rawValue: i)!, title: "todo \(i)", date: "2017-11-2\(i)") dataSource.append(todo) } tableView.register(UINib(nibName: "TodoTableViewCell", bundle: nil), forCellReuseIdentifier: TodoTableViewCell.cellid) let btn = UIButton(type: .contactAdd).then { $0.addTarget(self, action: #selector(addAction), for: .touchUpInside) } let btb = UIButton().then { $0.setTitle("Edit", for: .normal) $0.setTitle("Done", for: .selected) $0.setTitleColor(.blue, for: .normal) $0.setTitleColor(.blue, for: .selected) $0.titleLabel?.font = UIFont.systemFont(ofSize: 13) $0.addTarget(self, action: #selector(editAction(btn:)), for: .touchUpInside) } self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: btn) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btb) } @objc func editAction(btn: UIButton) { btn.isSelected = !btn.isSelected self.tableView.setEditing(!tableView.isEditing, animated: true) } @objc func addAction() { let vc = EditTodoViewController() vc.handler = { [weak self] todo in self?.dataSource.append(todo) self?.tableView.reloadData() } self.navigationController?.pushViewController(vc, animated: true) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: TodoTableViewCell.cellid, for: indexPath) as! TodoTableViewCell cell.model = dataSource[indexPath.row] return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 66 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let model = dataSource[indexPath.row] let vc = EditTodoViewController() vc.model = model vc.handler = { [weak self] todo in self?.dataSource[indexPath.row] = todo tableView.reloadRows(at: [indexPath], with: .fade) } self.navigationController?.pushViewController(vc, animated: true) } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let action = UITableViewRowAction(style: .destructive, title: "Delete") { [weak self] (atcion, indexpath) in tableView.beginUpdates() self?.dataSource.remove(at: indexpath.row) tableView.deleteRows(at: [indexpath], with: .fade) tableView.endUpdates() } return [action] } override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { return .delete } override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { self.dataSource.insert(self.dataSource[sourceIndexPath.row], at: destinationIndexPath.row) dataSource.remove(at: sourceIndexPath.row + 1) } }
mit
506d4caed3c01498839666e896141301
32.3
129
0.630416
4.816116
false
false
false
false
abdelrahman-ahmed/QRScanner-iOS-Swift
QRScanner/QRScanner/Views/QRSCannerView.swift
1
5967
// // QRSCannerView.swift // QRScanner // // Created by Abdelrahman Ahmed on 5/18/16. // Copyright © 2016 Abdelrahman Ahmed. All rights reserved. // import UIKit @IBDesignable class QRSCannerView: UIView { var margin:CGFloat = 10 var cornerLength:CGFloat = 30 var lineWidth:CGFloat = 10 var strokeColor:UIColor = UIColor.greenColor() private var laserScanLineLayer:CALayer? override func drawRect(rect: CGRect) { super.drawRect(rect) strokeColor.setStroke() addMaskLayer() laserScanLineLayer = movingBarLayerWithShadow() layer.masksToBounds = true layer.addSublayer(laserScanLineLayer!) } //MARK:- Remove Laser Scanner Layer func removeLaserLayer(){ laserScanLineLayer?.removeAllAnimations() laserScanLineLayer?.removeFromSuperlayer() } //MARK:- func addMaskLayer(){ let path = topLeftMaskPath() path.appendPath(topRightMaskPath()) path.appendPath(bottomRightMaskPath()) path.appendPath(bottomLeftMaskPath()) path.lineWidth = lineWidth path.stroke() let maskLayer = CAShapeLayer() maskLayer.path = path.CGPath } //MARK:- func movingBarLayerWithShadow()->CALayer { let laserScanLineLayer = CALayer() laserScanLineLayer.frame = CGRect(x: margin + lineWidth / 2, y: margin + lineWidth / 2 , width: layer.bounds.width - 2 * margin - lineWidth, height: 2) laserScanLineLayer.backgroundColor = UIColor.redColor().CGColor laserScanLineLayer.masksToBounds = false laserScanLineLayer.shadowColor = UIColor.redColor().CGColor laserScanLineLayer.shadowOpacity = 0.5 laserScanLineLayer.shadowOffset = CGSizeMake(0, 0) laserScanLineLayer.rasterizationScale = 0.2 laserScanLineLayer.addAnimation(shadowAnimations(laserScanLineLayer.bounds), forKey: "shadowAnimation") laserScanLineLayer.addAnimation(yPositionAnimation(), forKey: "position.y") return laserScanLineLayer } //MARK:- Y motion animation private func yPositionAnimation()->CAAnimation { let animation = CABasicAnimation(keyPath: "position.y") animation.fromValue = margin + lineWidth / 2 animation.toValue = layer.bounds.height - margin - lineWidth / 2 animation.duration = 2.0 animation.autoreverses = true animation.repeatCount = Float.infinity return animation } //MARK: Ahadow animation func shadowAnimations(bounds:CGRect)->CAAnimationGroup { let path1 = UIBezierPath(rect: CGRectMake(0, 0, bounds.width, 0)) let path2 = UIBezierPath(rect:CGRectMake(0, -100, bounds.width, 100)) let path3 = UIBezierPath(rect:CGRectMake(0, 0, bounds.width, 100)) let shadowAnimation1 = shadowAinmationWithPath(path1, shadowPathTo: path2, beginTime: 0.0, duration: 1.0) let shadowAnimation2 = shadowAinmationWithPath(path2, shadowPathTo: path1, beginTime: 1.0, duration: 1.0) let shadowAnimation3 = shadowAinmationWithPath(path1, shadowPathTo: path3, beginTime: 2.0, duration: 1.0) let shadowAnimation4 = shadowAinmationWithPath(path3, shadowPathTo: path1, beginTime: 3.0, duration: 1.0) let shadowAnimationGroup: CAAnimationGroup = CAAnimationGroup() shadowAnimationGroup.animations = [shadowAnimation1, shadowAnimation2, shadowAnimation3, shadowAnimation4] shadowAnimationGroup.duration = 4.0 shadowAnimationGroup.autoreverses = false shadowAnimationGroup.repeatCount = Float.infinity shadowAnimationGroup.removedOnCompletion = true return shadowAnimationGroup } func shadowAinmationWithPath(shadowPathFrom:UIBezierPath, shadowPathTo:UIBezierPath, beginTime: CFTimeInterval, duration: CFTimeInterval) -> CABasicAnimation { let shadowAnimation = CABasicAnimation(keyPath: "shadowPath") shadowAnimation.fromValue = shadowPathFrom.CGPath shadowAnimation.toValue = shadowPathTo.CGPath shadowAnimation.beginTime = beginTime shadowAnimation.duration = duration shadowAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) return shadowAnimation } //MARK:- Corner pathes func topLeftMaskPath()->UIBezierPath { let path = UIBezierPath() path.moveToPoint(CGPoint(x: margin, y: margin + cornerLength)) path.addLineToPoint(CGPoint(x: margin, y: margin)) path.addLineToPoint(CGPoint(x: cornerLength + margin, y: margin)) return path } func topRightMaskPath()->UIBezierPath { let path = UIBezierPath() path.moveToPoint(CGPoint(x:bounds.width - margin - cornerLength, y: margin )) path.addLineToPoint(CGPoint(x: bounds.width - margin, y: margin)) path.addLineToPoint(CGPoint(x: bounds.width - margin, y: margin + cornerLength)) return path } func bottomRightMaskPath()->UIBezierPath { let path = UIBezierPath() path.moveToPoint(CGPoint(x:margin, y: bounds.height - margin - cornerLength)) path.addLineToPoint(CGPoint(x: margin, y: bounds.height - margin)) path.addLineToPoint(CGPoint(x: margin + cornerLength, y: bounds.height - margin)) return path } func bottomLeftMaskPath()->UIBezierPath { let path = UIBezierPath() path.moveToPoint(CGPoint(x: bounds.width - margin, y: bounds.height - margin - cornerLength)) path.addLineToPoint(CGPoint(x: bounds.width - margin, y: bounds.height - margin)) path.addLineToPoint(CGPoint(x: bounds.width - margin - cornerLength, y: bounds.height - margin)) return path } }
gpl-3.0
b0ab2a595b62bcc4429fbe97a8c0f977
34.939759
163
0.666443
4.866232
false
false
false
false
PokemonGoSucks/pgoapi-swift
PGoApi/Classes/Unknown6/subFuncB.swift
1
33852
// // subFuncA.swift // Pods // // Created by PokemonGoSucks on 2016-08-10 // // import Foundation internal class subFuncB { internal func subFuncB(_ input:inout Array<UInt32>) { var v = Array<UInt32>(repeating: 0, count: 518) v[0] = ~input[30] v[1] = input[79] v[2] = input[180] v[3] = ((v[0] & input[172]) ^ input[0]) v[4] = input[54] v[5] = (((v[3] & v[4]) ^ (v[0] & v[1])) ^ v[2]) v[6] = ((v[0] & v[1]) ^ v[2]) v[7] = input[127] let part0 = ((v[0] & v[2])) v[8] = ((v[4] & ~part0) ^ input[171]) v[9] = (input[171] & input[30]) v[10] = (v[0] & v[2]) v[11] = input[109] v[12] = (v[0] & input[0]) v[13] = input[30] v[14] = (input[46] ^ input[30]) v[15] = (v[2] | v[13]) v[16] = (input[171] | v[13]) v[17] = input[104] v[18] = input[97] v[19] = (v[12] ^ input[0]) v[20] = (input[30] | v[1]) v[21] = (input[46] | input[30]) v[22] = (input[30] | input[0]) v[23] = ((v[0] & v[1]) ^ input[171]) let part1 = (((input[123] ^ v[1]) ^ input[84])) v[24] = (part1 & input[62]) v[25] = (v[15] ^ v[1]) v[26] = (v[12] ^ v[2]) v[27] = input[174] v[28] = input[178] v[29] = input[130] v[30] = (v[28] | input[30]) v[31] = input[54] v[32] = ((v[0] & v[2]) ^ v[2]) input[127] = v[8] v[33] = (v[31] & ~v[19]) v[34] = (v[19] & v[31]) v[35] = (v[16] ^ v[28]) v[36] = input[172] v[37] = (v[30] ^ v[36]) v[38] = (v[20] ^ v[36]) v[39] = input[74] input[85] = v[14] input[109] = v[9] v[40] = (v[0] & v[39]) v[41] = input[0] input[97] = v[5] v[42] = (v[41] ^ v[40]) v[43] = (v[4] & ~v[22]) v[44] = (v[0] & v[4]) v[45] = ~input[63] v[46] = (v[4] & ~v[3]) v[47] = (v[21] ^ input[0]) let part2 = (((input[68] & v[45]) ^ input[88])) let part3 = ((input[87] | input[63])) v[48] = (((input[83] ^ input[12]) ^ part3) ^ (part2 & ~input[1])) v[49] = input[36] v[50] = ~input[36] v[51] = (v[48] & v[50]) v[52] = (v[48] | v[49]) v[53] = input[36] v[54] = (v[48] ^ v[49]) v[55] = (v[35] ^ v[24]) let part4 = ((input[126] ^ v[51])) v[56] = (part4 & input[4]) v[57] = ~input[28] let part5 = ((v[48] | v[49])) v[58] = (part5 & v[57]) v[59] = ~input[28] v[60] = ((v[48] ^ v[49]) | input[28]) v[61] = (v[53] & ~v[48]) let part6 = (((input[68] & v[45]) ^ input[88])) let part7 = ((input[87] | input[63])) v[62] = (((input[83] ^ input[12]) ^ part7) ^ (part6 & ~input[1])) v[63] = (v[57] & v[53]) v[64] = v[4] v[65] = (v[4] | ~v[32]) v[66] = (v[4] & ~v[38]) v[67] = (v[33] ^ v[25]) v[68] = v[34] v[69] = (v[1] ^ v[20]) v[70] = (v[4] & ~v[37]) v[71] = (v[37] & v[4]) v[72] = (v[4] & ~v[26]) input[178] = (input[30] ^ input[0]) v[73] = v[61] v[74] = (v[68] ^ v[23]) v[75] = (v[4] & ~v[42]) v[76] = v[23] v[77] = (v[0] & input[46]) v[78] = (v[10] ^ v[44]) v[79] = (input[91] ^ v[52]) v[80] = (v[52] | input[28]) v[81] = (v[63] & v[62]) v[82] = input[62] v[83] = (v[67] & v[82]) v[84] = (input[36] & ~v[73]) v[85] = (v[65] & v[82]) input[104] = (v[46] ^ v[25]) v[86] = ((v[75] ^ v[69]) ^ (v[82] & ~v[74])) v[87] = (v[70] ^ v[9]) input[82] = (v[71] ^ v[14]) v[88] = ((v[64] & ~v[47]) ^ input[178]) v[89] = (v[66] ^ v[77]) let part8 = ((v[43] ^ v[26])) v[90] = (part8 & input[62]) v[91] = (v[78] ^ input[74]) v[92] = (v[60] ^ v[62]) v[93] = (v[79] & ~input[4]) v[94] = ((v[6] & ~v[64]) ^ input[171]) v[95] = ((v[58] ^ v[56]) | input[20]) input[161] = (v[85] ^ input[104]) v[96] = (v[83] ^ v[5]) v[97] = (v[8] ^ input[59]) v[98] = (v[87] & input[62]) let part9 = ((v[55] ^ v[72])) v[99] = (part9 & input[38]) v[100] = (input[62] & ~v[89]) v[101] = (v[88] ^ input[61]) v[102] = (v[90] ^ input[82]) v[103] = (v[91] ^ input[9]) v[104] = ((v[73] ^ input[28]) ^ (input[4] & ~v[60])) v[105] = (input[62] & ~v[94]) v[106] = (input[38] & ~v[96]) v[107] = (input[161] ^ input[11]) v[108] = (input[38] & ~v[86]) let part10 = ((v[84] ^ v[81])) input[126] = ((((input[4] & ~part10) ^ v[80]) ^ v[54]) ^ v[95]) v[109] = (v[98] ^ v[97]) input[12] = v[62] v[110] = (v[107] ^ v[106]) v[111] = (v[109] ^ v[108]) v[112] = ((v[101] ^ v[99]) ^ v[105]) v[113] = input[20] v[114] = ((v[103] ^ v[100]) ^ (input[38] & ~v[102])) input[180] = v[25] v[115] = ~v[113] let part11 = (((v[93] ^ v[60]) ^ v[62])) v[116] = (part11 & ~v[113]) input[11] = v[110] v[117] = v[114] v[118] = v[76] v[119] = input[77] v[120] = ~v[112] v[121] = input[30] input[130] = v[118] v[122] = v[111] let part12 = ((v[121] | v[119])) v[123] = (part12 ^ v[18]) v[124] = (v[0] & input[22]) v[125] = input[158] input[59] = v[111] v[126] = v[124] input[174] = v[88] v[127] = (v[0] & v[125]) v[128] = v[112] input[61] = v[112] v[129] = input[30] input[91] = (v[104] ^ v[116]) v[130] = input[30] v[131] = (v[129] | input[117]) v[132] = (v[127] ^ v[29]) v[133] = (v[0] & input[136]) let part13 = ((v[130] | input[120])) v[134] = (part13 ^ v[7]) v[135] = ~v[117] let part14 = ((v[130] | input[102])) v[136] = (part14 ^ input[173]) let part15 = (((input[67] ^ (input[65] & v[45])) | input[1])) v[137] = (((part15 ^ (input[89] & v[45])) ^ input[40]) ^ input[90]) v[138] = input[56] v[139] = input[131] input[9] = v[117] v[140] = v[117] v[141] = (v[137] ^ v[139]) v[142] = input[24] v[143] = ~input[56] v[144] = ~input[56] v[145] = (~v[137] & input[2]) v[146] = (v[137] | input[56]) v[147] = ((v[137] & v[143]) & input[2]) v[148] = (~v[137] & input[56]) v[149] = ((v[146] & v[143]) ^ input[71]) let part16 = ((v[141] | v[142])) v[150] = (((part16 ^ v[147]) ^ v[137]) ^ v[138]) let part17 = ((v[137] & input[56])) v[151] = ~part17 v[152] = (v[148] & input[2]) let part18 = ((v[137] ^ v[138])) v[153] = (v[137] ^ (input[2] & part18)) v[154] = (v[146] & v[143]) v[155] = (v[137] ^ input[2]) v[156] = (input[2] & ~v[146]) v[157] = (v[151] & input[56]) let part19 = ((v[137] ^ v[138])) v[158] = (input[2] & ~part19) v[159] = ((v[147] ^ (v[146] & v[143])) | v[142]) let part20 = ((v[155] | v[142])) v[160] = (v[147] ^ part20) let part21 = ((v[153] | v[142])) v[161] = ((part21 ^ v[145]) ^ v[137]) let part22 = ((v[145] ^ v[137])) v[162] = ((v[142] & ~part22) ^ v[153]) v[163] = ((input[2] ^ input[1]) ^ v[157]) v[164] = ((v[151] & input[2]) ^ (v[137] & v[143])) v[165] = ~input[48] v[166] = (v[156] ^ v[137]) let part23 = (((v[152] ^ v[146]) | v[142])) v[167] = ((v[156] ^ v[146]) ^ part23) v[168] = (input[2] & ~v[157]) v[169] = (input[185] ^ v[148]) let part24 = ((v[137] | v[142])) let part25 = (((v[145] ^ v[137]) ^ part24)) let part26 = ((v[150] ^ (part25 & input[32]))) let part27 = ((v[149] | v[142])) v[170] = ((((input[56] ^ input[37]) ^ part27) ^ v[168]) ^ (part26 & v[165])) input[83] = (v[152] ^ v[154]) v[171] = input[32] v[172] = (v[168] ^ v[137]) let part28 = (((v[145] & v[142]) ^ v[137])) v[173] = (input[32] & ~part28) let part29 = (((v[168] ^ v[157]) | v[142])) v[174] = ((((v[161] & v[171]) ^ v[168]) ^ v[157]) ^ part29) let part30 = ((v[172] | v[142])) v[175] = ((input[83] ^ input[19]) ^ part30) v[176] = (v[142] & ~v[152]) let part31 = (((v[157] ^ v[158]) | v[142])) v[177] = (v[166] ^ part31) v[178] = (v[155] ^ input[15]) v[179] = (v[163] ^ (v[160] & v[171])) v[180] = (v[164] & ~v[142]) let part32 = ((((v[171] & ~v[162]) ^ input[186]) ^ v[159])) v[181] = (part32 & v[165]) v[182] = (~v[142] | ~v[169]) v[183] = (v[170] ^ (input[32] & ~v[167])) v[184] = (v[173] ^ input[80]) v[185] = input[48] v[186] = (v[175] ^ (v[177] & input[32])) v[187] = v[183] v[188] = ((v[179] ^ v[180]) ^ v[181]) v[189] = input[32] input[37] = v[183] input[40] = v[137] input[65] = (v[183] & v[128]) input[131] = (v[183] ^ v[128]) let part33 = ((v[174] | v[185])) v[190] = (v[186] ^ part33) input[84] = (v[183] & v[120]) input[87] = (v[128] | v[183]) let part34 = ((v[128] | v[183])) input[123] = (part34 & v[120]) input[1] = v[188] v[191] = (v[188] ^ v[140]) let part35 = ((v[184] | v[185])) v[192] = (((v[178] ^ v[176]) ^ (v[182] & v[189])) ^ part35) input[15] = v[192] v[193] = input[30] v[194] = ~v[183] v[195] = v[190] input[90] = (~v[183] & v[128]) input[19] = v[190] input[88] = (v[188] & v[140]) v[196] = (v[193] | input[69]) let part36 = ((~v[188] & v[140])) v[197] = (v[140] & ~part36) v[198] = (v[133] ^ input[78]) let part37 = ((input[146] | input[63])) v[199] = (part37 ^ input[142]) v[200] = (~v[188] & v[140]) let part38 = (((input[118] & v[45]) ^ input[141])) v[201] = ((input[10] ^ input[114]) ^ (part38 & input[39])) v[202] = input[18] v[203] = v[202] v[204] = (v[202] ^ v[201]) v[205] = (v[201] & ~v[203]) v[206] = (input[34] | v[204]) v[207] = (v[201] & input[18]) v[208] = (v[204] ^ input[177]) v[209] = (v[204] ^ input[75]) v[210] = (v[205] & ~input[34]) v[211] = (input[18] & ~v[201]) v[212] = ~input[34] v[213] = (v[206] ^ v[204]) v[214] = (v[201] ^ input[128]) v[215] = (input[18] ^ input[45]) v[216] = input[26] input[10] = v[201] v[217] = ~v[216] v[218] = (v[211] ^ input[129]) input[68] = v[205] input[177] = v[208] v[219] = ((v[206] ^ v[211]) ^ (v[218] & v[217])) v[220] = ((v[201] & ~v[205]) ^ (v[207] & v[212])) v[221] = ((v[207] & v[212]) ^ v[205]) v[222] = (v[205] | input[34]) v[223] = input[26] input[141] = v[221] v[224] = (v[220] | v[223]) v[225] = (v[212] & v[201]) input[118] = v[210] let part39 = (((v[208] & v[217]) ^ (v[212] & v[201]))) let part40 = ((v[207] ^ v[210])) v[226] = ((((part40 & v[217]) ^ v[221]) ^ (part39 & input[2])) | input[56]) v[227] = (v[213] | input[26]) v[228] = (v[213] & v[217]) v[229] = (v[81] ^ v[51]) let part41 = ((v[227] ^ v[201])) v[230] = (((v[209] ^ v[227]) ^ (part41 & input[2])) | input[56]) v[231] = ((v[204] ^ input[39]) ^ v[222]) v[232] = input[4] v[233] = (v[52] ^ input[184]) let part42 = ((v[84] ^ (v[62] & v[59]))) v[234] = (v[232] & ~part42) v[235] = (v[232] & ~v[229]) let part43 = ((input[175] ^ v[228])) v[236] = (input[2] & ~part43) v[237] = ((v[84] ^ input[28]) ^ v[234]) let part44 = ((v[84] ^ input[64])) v[238] = (((part44 & input[4]) ^ v[92]) | input[20]) let part45 = ((v[201] | input[34])) v[239] = (v[215] ^ part45) v[240] = (v[201] ^ input[34]) v[241] = ((input[76] ^ input[43]) ^ v[240]) v[242] = (v[45] & input[112]) v[243] = (((v[212] & v[201]) & input[26]) ^ v[208]) let part46 = ((v[201] | input[18])) v[244] = (((v[204] & v[212]) ^ part46) ^ v[224]) v[245] = input[34] let part47 = ((((v[214] & v[217]) ^ (v[204] & v[212])) ^ v[204])) let part48 = ((v[240] | input[26])) v[246] = ((v[239] ^ part48) ^ (input[2] & ~part47)) v[247] = v[245] v[248] = (v[245] ^ v[211]) v[249] = input[2] input[73] = v[248] let part49 = ((v[228] ^ v[248])) v[250] = (part49 & v[249]) let part50 = (((v[225] & v[217]) ^ v[210])) v[251] = (part50 & v[249]) let part51 = ((v[211] | v[247])) let part52 = ((part51 ^ (v[225] & v[217]))) v[252] = (part52 & v[249]) v[253] = input[33] v[254] = (input[2] & ~v[243]) v[255] = (v[210] ^ input[18]) v[256] = (v[210] & ~v[217]) v[257] = (v[242] ^ input[111]) v[258] = (v[250] ^ v[256]) input[71] = v[256] v[259] = input[25] v[260] = input[56] v[261] = ((input[60] ^ input[153]) ^ (input[39] & ~v[257])) input[60] = v[261] let part53 = ((v[258] | v[260])) v[262] = ((((v[255] & v[217]) ^ v[231]) ^ v[236]) ^ part53) input[80] = v[262] input[45] = (v[246] ^ v[230]) let part54 = ((v[251] ^ v[219])) v[263] = ((v[241] ^ v[254]) ^ (part54 & v[144])) input[43] = v[263] v[264] = (((v[244] ^ v[252]) ^ v[226]) ^ v[259]) v[265] = input[28] input[25] = v[264] v[266] = (v[261] & v[265]) v[267] = ~v[264] v[268] = v[264] v[269] = (v[253] ^ v[27]) v[270] = input[116] v[271] = ((v[261] & v[265]) ^ v[270]) v[272] = ~input[44] v[273] = ((v[269] ^ v[126]) ^ (v[261] & ~v[123])) let part55 = (((v[266] ^ input[162]) | input[44])) let part56 = (((part55 ^ v[266]) ^ input[94])) let part57 = ((v[266] ^ v[270])) let part58 = (((part57 & v[272]) ^ (part56 & input[6]))) let part59 = (((v[261] & input[164]) ^ v[270])) let part60 = ((((part59 & v[272]) ^ (v[261] & v[50])) ^ input[99])) let part61 = (((v[261] & v[50]) ^ input[164])) let part61a = ((input[17] ^ input[99]) ^ (v[261] & input[101])) v[274] = (((part61a ^ (part61 & v[272])) ^ (part60 & input[6])) ^ (input[52] & ~part58)) v[275] = input[29] v[276] = (((input[55] ^ v[17]) ^ v[131]) ^ (v[261] & ~v[132])) let part62 = ((v[188] ^ v[140])) v[277] = (part62 & v[274]) input[33] = v[273] input[55] = v[276] v[278] = (v[275] ^ v[11]) input[158] = (v[262] | v[276]) v[279] = (v[134] ^ input[51]) v[280] = (~v[188] & v[140]) input[136] = (v[262] & v[276]) v[281] = (v[261] & input[99]) input[17] = v[274] let part63 = ((v[262] & v[276])) input[69] = (v[276] & ~part63) let part64 = (((v[188] ^ v[274]) ^ (v[277] & v[273]))) input[153] = (((((v[274] & v[188]) & v[140]) ^ v[200]) ^ (v[197] & v[273])) ^ (~v[264] & part64)) v[282] = (v[262] ^ v[276]) let part65 = ((v[262] | v[276])) input[117] = (part65 & ~v[276]) input[185] = (v[262] & ~v[276]) input[76] = (v[276] & ~v[262]) v[283] = (v[281] ^ input[124]) v[284] = input[124] v[285] = v[282] v[286] = ((v[278] ^ v[196]) ^ (v[261] & ~v[198])) input[128] = v[285] v[287] = (v[261] & ~v[284]) v[288] = input[100] input[100] = (v[188] ^ v[274]) v[289] = input[101] input[102] = v[283] let part66 = (((v[188] & v[140]) ^ v[274])) let part67 = ((v[264] | (part66 & ~v[273]))) input[116] = (((part67 ^ v[280]) ^ (v[188] & v[274])) ^ ((v[135] & v[273]) & v[188])) v[290] = (v[261] ^ v[289]) v[291] = v[286] v[292] = (v[279] ^ (v[261] & ~v[136])) v[293] = ((input[44] & ~v[290]) ^ v[290]) input[51] = v[292] v[294] = v[286] input[172] = (v[280] ^ (v[188] & v[274])) v[295] = (v[261] & ~v[270]) v[296] = (v[287] ^ v[270]) input[29] = v[294] v[297] = (v[287] ^ input[99]) let part68 = (((v[45] & input[110]) ^ input[149])) v[298] = ((input[8] ^ v[199]) ^ (part68 & input[39])) v[299] = v[273] v[300] = (input[94] ^ v[288]) v[301] = ((input[164] ^ input[3]) ^ v[281]) v[302] = (~v[188] & v[274]) v[303] = ((((v[272] & v[59]) & v[261]) ^ (v[261] & v[50])) ^ input[36]) let part69 = ((v[287] ^ v[270])) v[304] = (part69 & v[272]) v[305] = (v[290] | input[44]) v[306] = ((v[295] ^ input[101]) ^ (v[290] & v[272])) v[307] = ((v[261] & v[272]) ^ v[295]) let part70 = ((v[188] | v[140])) v[308] = (v[302] ^ part70) let part71 = ((~v[188] ^ v[274])) v[309] = (part71 & v[140]) let part72 = ((v[188] | v[140])) let part73 = (((v[188] & v[274]) ^ (v[188] & v[140]))) v[310] = ((part73 & v[299]) ^ part72) let part74 = ((v[188] ^ v[140])) let part75 = (((v[274] & ~part74) ^ v[200])) v[311] = (v[299] & ~part75) let part76 = ((v[304] ^ v[283])) v[312] = (input[6] & ~part76) let part77 = ((v[296] | input[44])) v[313] = (v[301] ^ part77) v[314] = ((v[274] & v[135]) ^ v[140]) v[315] = (v[302] ^ v[140]) v[316] = v[314] v[317] = ((v[274] & v[135]) ^ v[188]) v[318] = (v[308] & v[299]) v[319] = (v[191] ^ v[274]) let part78 = (((v[261] & v[270]) ^ input[107])) v[320] = (part78 & input[6]) v[321] = ((v[299] & ~v[315]) ^ v[309]) let part79 = (((v[298] & ~input[163]) ^ input[169])) v[322] = (((input[103] ^ input[27]) ^ (v[298] & ~input[170])) ^ (input[32] & ~part79)) v[323] = (v[319] ^ (v[310] & ~v[264])) let part80 = ((v[317] ^ v[311])) v[324] = (part80 & ~v[264]) let part81 = ((v[200] ^ v[302])) let part82 = (((part81 & v[299]) ^ v[309])) v[325] = (part82 & ~v[264]) v[326] = ((v[315] & v[299]) ^ v[200]) v[327] = (v[264] | (v[309] ^ (v[200] & v[299]))) let part83 = (((v[305] ^ v[297]) ^ (input[6] & ~v[293]))) v[328] = ((v[313] ^ v[312]) ^ (input[52] & ~part83)) let part84 = ((v[271] | input[44])) v[329] = (((v[297] ^ input[5]) ^ part84) ^ (input[6] & ~v[306])) let part85 = ((((v[306] & input[6]) ^ v[307]) ^ input[36])) v[330] = (input[52] & ~part85) let part86 = (((input[6] & ~v[303]) ^ input[36])) v[331] = ((((v[300] ^ input[23]) ^ v[261]) ^ v[320]) ^ (part86 & input[52])) v[332] = (((~v[264] & v[299]) & ~v[316]) ^ v[315]) v[333] = (v[315] | v[299]) let part87 = ((input[168] ^ (v[298] & ~input[121]))) v[334] = (((input[13] ^ input[183]) ^ (v[298] & input[160])) ^ (part87 & input[32])) v[335] = (v[299] & ~v[197]) v[336] = (v[322] & ~v[292]) input[79] = (v[323] ^ v[335]) input[101] = (v[326] ^ v[324]) input[78] = (((v[327] ^ v[318]) ^ v[188]) ^ v[277]) input[129] = (v[328] & v[110]) input[27] = v[322] input[162] = (v[321] ^ v[325]) input[3] = v[328] v[337] = input[148] v[338] = (v[329] ^ v[330]) input[5] = (v[329] ^ v[330]) input[23] = v[331] let part88 = ((v[322] & ~v[292])) v[339] = (v[122] & ~part88) input[8] = v[298] input[77] = (v[333] ^ v[332]) let part89 = ((v[331] & v[128])) v[340] = ~part89 input[13] = v[334] v[341] = (v[340] & v[331]) v[342] = (input[63] | v[337]) v[343] = input[137] v[344] = input[138] input[170] = v[339] v[345] = (v[331] & v[120]) let part90 = (((input[159] & v[298]) ^ input[139])) v[346] = ((((input[32] & ~part90) ^ input[31]) ^ v[343]) ^ (v[298] & ~v[344])) v[347] = (v[192] & v[120]) v[348] = (v[346] & v[120]) v[349] = ((v[346] & v[128]) ^ v[128]) v[350] = (v[340] & v[346]) let part91 = ((v[331] ^ (v[346] & v[120]))) v[351] = (v[192] & ~part91) v[352] = ((v[346] & v[120]) ^ v[128]) v[353] = ((v[192] & v[346]) & v[128]) v[354] = ((input[41] ^ input[181]) ^ (input[108] & v[298])) let part92 = (((input[106] & v[298]) ^ input[179])) v[355] = (part92 & input[32]) v[356] = ((input[145] ^ input[58]) ^ v[342]) let part93 = (((v[45] & input[150]) ^ input[115])) v[357] = (input[39] & ~part93) v[358] = ((v[331] & v[128]) & v[346]) let part94 = ((v[331] | v[128])) v[359] = (part94 ^ v[348]) v[360] = input[28] input[31] = v[346] v[361] = (v[354] ^ v[355]) v[362] = (v[357] ^ v[356]) input[107] = (v[346] | v[285]) input[58] = (v[357] ^ v[356]) input[94] = (((v[331] & v[128]) ^ (v[192] & ~v[349])) ^ v[348]) input[138] = ((v[192] & v[349]) ^ v[359]) input[145] = (((((~v[331] & v[346]) & v[192]) ^ v[331]) ^ v[128]) ^ v[346]) let part95 = ((v[331] | v[128])) input[159] = (((v[192] & v[349]) ^ part95) ^ v[358]) input[114] = (((v[192] & ~v[346]) ^ v[345]) ^ v[358]) input[149] = (((v[351] ^ v[350]) ^ v[331]) ^ v[128]) input[124] = (v[359] ^ (v[192] & ~v[352])) let part96 = ((v[352] | v[192])) input[173] = (part96 ^ v[128]) let part97 = ((v[341] ^ (~v[331] & v[346]))) let part98 = ((v[331] | v[128])) input[139] = (((v[346] & ~part98) ^ v[128]) ^ (v[192] & ~part97)) let part99 = ((v[331] | v[128])) let part100 = ((v[346] ^ ~v[331])) input[74] = ((part100 & part99) ^ v[347]) let part101 = ((v[331] | v[128])) let part102 = ((part101 ^ (v[346] & v[128]))) input[164] = ((v[192] & ~part102) ^ v[358]) input[186] = (v[358] ^ v[353]) let part103 = ((v[331] ^ v[128])) let part104 = ((v[331] | v[128])) input[111] = ((v[353] ^ part104) ^ (part103 & v[346])) input[120] = ((v[192] ^ v[128]) ^ ((~v[331] & v[346]) & v[128])) let part105 = ((v[331] | v[128])) input[89] = ((part105 & ~v[192]) ^ (v[346] & ~v[341])) v[363] = input[70] let part106 = ((v[354] ^ v[355])) v[364] = (v[268] & ~part106) let part107 = ((v[51] | v[360])) let part108 = ((v[233] ^ part107)) v[365] = ((((v[51] & v[59]) ^ v[73]) ^ v[235]) ^ (part108 & v[115])) input[175] = v[364] let part109 = ((v[357] ^ v[356])) v[366] = (part109 & ~input[122]) v[367] = (input[125] ^ v[363]) let part110 = ((v[357] ^ v[356])) v[368] = (input[119] & part110) v[369] = input[21] let part111 = ((v[357] ^ v[356])) v[370] = (part111 & input[157]) input[41] = (v[354] ^ v[355]) v[371] = input[57] input[21] = ((v[367] ^ v[369]) ^ v[370]) let part112 = ((v[237] ^ v[238])) let part113 = ((v[357] ^ v[356])) v[372] = ((input[35] ^ v[365]) ^ (part113 & ~part112)) v[373] = ((input[92] ^ v[371]) ^ v[366]) v[374] = (v[368] ^ input[96]) v[375] = (v[334] ^ input[21]) v[376] = input[21] let part114 = ((v[357] ^ v[356])) let part115 = ((v[237] ^ v[238])) input[49] ^= (v[365] ^ (part115 & ~part114)) v[377] = ~v[291] v[378] = (v[334] & ~v[376]) v[379] = (v[334] & v[376]) v[380] = (v[376] & ~v[334]) v[381] = v[291] v[382] = (v[334] | v[291]) v[383] = (v[373] ^ (v[374] & v[212])) v[384] = (v[268] ^ v[361]) v[385] = (v[268] | v[361]) v[386] = (input[49] | v[268]) v[387] = (v[268] & v[361]) v[388] = (input[21] | v[291]) v[389] = (v[372] | v[195]) input[99] = (v[372] | v[110]) v[390] = v[375] v[391] = (~v[291] & v[376]) v[392] = ~v[195] v[393] = (v[267] & v[361]) v[394] = ((~v[291] & v[334]) ^ v[390]) v[395] = (v[334] & ~v[379]) v[396] = (v[378] ^ v[391]) v[397] = (~v[372] & v[322]) v[398] = (input[49] | v[361]) v[399] = input[49] v[400] = ((v[268] ^ v[361]) ^ v[386]) v[401] = (~v[399] & v[364]) v[402] = (v[394] & v[338]) let part116 = ((v[334] | input[21])) v[403] = (v[377] & part116) v[404] = (input[49] | (v[268] & v[361])) v[405] = ((v[334] & ~v[379]) | v[381]) v[406] = (input[21] ^ (v[390] & v[377])) v[407] = ((v[380] & v[377]) ^ v[379]) let part117 = ((v[380] ^ v[388])) v[408] = (v[338] & ~part117) v[409] = (v[388] ^ v[334]) let part118 = (((input[49] | v[268]) | v[361])) let part119 = ((v[268] | v[361])) v[410] = (part119 ^ part118) v[411] = (~v[399] & v[268]) v[412] = (~v[399] & v[393]) v[413] = ((v[399] ^ v[361]) | v[328]) let part120 = ((v[268] | v[361])) v[414] = (((~v[399] & part120) ^ v[268]) ^ v[361]) let part121 = ((v[268] & v[361])) v[415] = ((v[268] & ~part121) | input[49]) v[416] = ((~v[328] & v[268]) ^ v[364]) v[417] = (v[402] ^ (v[379] & ~v[377])) let part122 = ((v[372] | v[195])) v[418] = (input[99] ^ part122) v[419] = (v[395] ^ v[403]) v[420] = ((v[396] & v[338]) ^ v[379]) v[421] = (v[379] ^ v[382]) v[422] = (v[405] ^ v[380]) v[423] = (v[403] ^ v[380]) let part123 = ((v[390] ^ v[382])) v[424] = (v[407] ^ (v[338] & ~part123)) v[425] = (v[372] & ~v[110]) input[184] = (v[372] & v[110]) v[426] = (v[338] & v[382]) v[427] = (v[408] ^ v[409]) v[428] = (v[412] ^ v[387]) v[429] = (v[415] ^ v[387]) v[430] = (v[387] ^ v[411]) v[431] = (v[411] ^ v[361]) v[432] = (v[416] & v[383]) v[433] = (v[417] | v[187]) v[434] = (v[419] ^ (v[338] & ~v[390])) v[435] = (v[420] & v[194]) v[436] = (v[422] ^ (v[338] & ~v[406])) v[437] = (v[397] & ~v[292]) v[438] = (v[424] & v[194]) v[439] = (v[423] ^ (v[338] & ~v[421])) v[440] = (v[427] & v[194]) v[441] = (v[409] ^ v[426]) let part124 = ((input[49] | v[384])) v[442] = (part124 ^ v[393]) v[443] = (v[404] ^ v[393]) v[444] = (v[361] ^ input[36]) v[445] = ((v[404] ^ v[364]) | v[328]) v[446] = input[14] v[447] = (v[362] & input[155]) let part125 = ((v[398] ^ v[361])) v[448] = ((v[410] ^ ((v[364] & v[383]) & v[328])) ^ (part125 & v[328])) v[449] = ((v[401] & ~v[328]) ^ v[398]) v[450] = (v[442] | v[328]) v[451] = (v[328] & ~v[431]) v[452] = (v[400] ^ input[0]) v[453] = (v[428] & v[328]) v[454] = (v[429] & ~v[328]) v[455] = (v[443] ^ input[18]) v[456] = ((v[328] & ~v[443]) ^ v[400]) v[457] = (v[425] & v[328]) input[115] = (v[425] & ~v[195]) v[458] = ((v[418] & ~v[328]) ^ input[115]) let part126 = ((((v[372] ^ v[110]) ^ (~v[195] & v[110])) | v[328])) v[459] = (part126 ^ input[115]) let part127 = ((v[400] | v[328])) let part128 = ((part127 ^ v[385])) v[460] = (part128 & v[383]) input[183] = (input[49] ^ v[364]) v[461] = (v[414] ^ v[446]) v[462] = (v[449] ^ v[432]) let part129 = ((v[372] ^ v[110])) v[463] = (part129 & ~v[195]) let part130 = ((input[184] | v[195])) v[464] = ((part130 ^ v[372]) ^ v[110]) v[465] = (input[99] | v[195]) let part131 = ((v[414] | v[328])) v[466] = (part131 ^ (v[383] & ~v[413])) v[467] = (input[99] & ~v[110]) v[468] = (v[465] ^ (v[425] & v[328])) v[469] = (v[362] & ~input[167]) v[470] = (input[184] & v[392]) v[471] = input[47] v[472] = (v[434] ^ v[433]) input[39] = (~v[372] & v[110]) input[70] = ((~v[372] & v[110]) ^ v[463]) v[473] = (v[436] ^ v[435]) v[474] = (v[439] ^ v[440]) v[475] = (v[441] ^ v[438]) v[476] = input[165] v[477] = (v[471] ^ input[105]) let part132 = ((v[372] | v[322])) input[181] = (v[437] ^ part132) v[478] = (v[476] ^ v[447]) let part133 = ((v[372] | v[322])) let part134 = ((part133 ^ v[336])) v[479] = ((input[181] ^ (v[122] & ~part134)) | v[338]) v[480] = (v[299] & ~v[448]) v[481] = (v[451] ^ v[452]) v[482] = (input[49] ^ v[384]) input[121] = (v[401] ^ v[384]) v[483] = (v[362] & input[176]) v[484] = (v[444] ^ (v[482] & ~v[328])) input[179] = (v[372] & v[322]) v[485] = (v[450] ^ v[482]) v[486] = v[464] v[487] = (v[466] ^ v[410]) v[488] = ((v[470] ^ input[99]) ^ (v[418] & v[328])) input[112] = (v[464] ^ ((v[372] & v[392]) & v[328])) v[489] = (v[455] ^ v[454]) v[490] = (((v[445] ^ v[401]) ^ v[384]) ^ v[460]) v[491] = ((v[430] & ~v[328]) ^ input[183]) v[492] = (v[461] ^ (v[328] & ~v[401])) v[493] = ((v[372] & v[392]) ^ v[110]) v[494] = (v[462] & v[299]) v[495] = (v[467] ^ v[470]) let part135 = ((v[372] | v[322])) input[106] = (part135 & ~v[372]) v[496] = (v[457] ^ input[70]) let part136 = ((v[392] ^ v[110])) v[497] = (v[457] ^ (part136 & v[372])) v[498] = (v[472] ^ input[52]) v[499] = (v[473] | v[122]) v[500] = (v[475] ^ input[48]) v[501] = (v[475] ^ input[34]) v[502] = (v[473] & v[122]) v[503] = (v[472] ^ input[62]) v[504] = (v[477] ^ v[469]) v[505] = (v[478] | input[34]) v[506] = (v[372] & ~input[179]) v[507] = (v[483] ^ input[95]) v[508] = ((v[458] & ~v[383]) ^ v[488]) v[509] = (input[99] & v[392]) input[122] = (input[39] & v[392]) input[67] = ((v[459] & ~v[383]) ^ input[112]) v[510] = (v[484] ^ v[480]) v[511] = (v[383] & ~v[485]) v[512] = (v[489] ^ (v[456] & v[383])) v[513] = (v[492] ^ v[494]) let part137 = (((v[110] & ~input[184]) ^ v[389])) v[514] = (part137 & v[328]) v[515] = (input[67] ^ input[38]) v[516] = (((input[115] & v[328]) ^ input[122]) ^ input[99]) v[517] = (input[106] | v[292]) input[52] = (v[498] ^ v[499]) input[62] = (v[503] ^ v[502]) input[48] = ((v[474] & ~v[122]) ^ v[500]) input[160] = ((v[122] & ~v[474]) ^ v[501]) input[35] = v[372] input[47] = (v[504] ^ v[505]) input[176] = (v[507] & v[212]) input[57] = v[383] input[0] = (((v[487] & v[299]) ^ v[481]) ^ (v[383] & ~v[453])) input[14] = (v[513] ^ (v[383] & ~v[491])) input[36] = (v[510] ^ v[511]) input[18] = ((v[299] & ~v[490]) ^ v[512]) input[64] = (v[372] & ~v[292]) let part138 = ((v[372] | v[322])) input[75] = (~v[292] & part138) input[95] = (v[328] & ~v[418]) let part139 = ((((v[397] & v[122]) ^ v[322]) ^ v[479])) input[110] = (part139 & v[263]) input[150] = (((v[437] & v[122]) ^ v[336]) | v[338]) let part140 = ((v[322] ^ v[292])) input[137] = ((~v[122] & part140) ^ v[437]) let part141 = (((v[506] ^ v[339]) | v[338])) let part142 = ((v[372] | v[322])) let part143 = ((v[322] ^ v[292])) input[169] = (((v[372] ^ (v[122] & ~part143)) ^ (~v[292] & part142)) ^ part141) let part144 = ((v[397] ^ v[292])) input[125] = (part144 & v[122]) input[119] = (v[372] | v[322]) let part145 = ((v[397] ^ v[292])) input[163] = (v[122] & ~part145) input[92] = (((v[509] ^ v[372]) ^ (~v[383] & v[468])) ^ (v[328] & ~v[495])) input[167] = v[486] input[148] = (v[110] ^ v[468]) input[38] = (v[515] ^ (v[508] & ~v[322])) let part146 = ((v[372] | v[322])) input[108] = (v[517] ^ part146) input[105] = (v[516] | v[383]) let part147 = ((v[418] | v[328])) let part148 = ((part147 ^ v[418])) input[157] = (((((v[372] & v[392]) ^ v[372]) ^ (v[493] & v[328])) ^ (part148 & ~v[383])) | v[322]) input[34] = (v[514] ^ v[493]) let part149 = ((v[322] | v[292])) let part150 = ((v[372] | v[322])) let part151 = ((part150 ^ part149)) input[146] = (part151 & v[122]) let part152 = ((v[292] | v[506])) let part153 = ((part152 ^ v[397])) input[155] = (v[122] & ~part153) let part154 = ((v[372] | v[322])) let part155 = ((v[292] | v[506])) input[96] = (part155 ^ part154) let part156 = ((v[506] ^ v[292])) let part157 = ((v[372] | v[322])) input[165] = (((~v[292] & part157) ^ v[397]) ^ (part156 & v[122])) let part158 = ((v[372] | v[322])) let part159 = ((v[372] | v[322])) input[103] = (v[122] | ((~v[292] & part158) ^ part159)) input[142] = ((v[497] ^ (v[496] & ~v[383])) | v[322]) input[168] = (v[389] ^ v[372]) } }
mit
1af27b14118e227934de4a52311e1dc4
39.252081
106
0.39395
2.415757
false
false
false
false
BobElDevil/ScriptWorker
swiftscript/SwiftScript.swift
1
5076
// // SwiftScript.swift // ScriptWorker // // Created by Stephen Marquis on 4/5/17. // Copyright © 2017 Stephen Marquis. All rights reserved. // import Foundation // Simple container class so we can compile this into a unit test bundle class SwiftScript { private enum LineType { case script(URL) case framework(URL) case blank case other init(_ rawLine: String, againstBase base: URL) { let parse = { (line: String, prefix: String) -> URL? in let trimmedLine = line.trimmingCharacters(in: .whitespaces) guard let range = trimmedLine.range(of: prefix, options: .anchored, range: nil, locale: nil) else { return nil } var path = trimmedLine.substring(from: range.upperBound).trimmingCharacters(in: .whitespaces) path = (path as NSString).expandingTildeInPath let url: URL if (path as NSString).isAbsolutePath { url = URL(fileURLWithPath: path) } else { url = base.appendingPathComponent(path) } return url } let line = rawLine.trimmingCharacters(in: .whitespaces) if let val = parse(line, "//!swiftscript") { self = .script(val) } else if let val = parse(line, "//!swiftsearch") { self = .framework(val) } else { self = line.trimmingCharacters(in: .whitespaces).isEmpty ? .blank : .other } } } class func readLines(from fileURL: URL) -> [String] { let fileHandle = try! FileHandle(forReadingFrom: fileURL) let data = fileHandle.readDataToEndOfFile() guard let string = String(data: data, encoding: String.Encoding.utf8) else { print("Failed to read content of \(fileURL)") exit(1) } return string.components(separatedBy: .newlines) } class func filesAndFrameworks(for lines: [String], withDir dir: URL) -> ([URL], [URL]) { guard !lines.isEmpty else { return ([], []) } var lines = lines if lines[0].hasPrefix("#!") { lines.removeFirst() } var filesToRead: [URL] = [] var frameworkSearchPaths: [URL] = [] var stop: Bool = false while !lines.isEmpty && !stop { let line = lines.removeFirst() switch LineType(line, againstBase: dir) { case let .script(file): filesToRead.append(file) case let .framework(path): frameworkSearchPaths.append(path) case .blank: continue case .other: stop = true } } return (filesToRead, frameworkSearchPaths) } class func swiftArguments(for file: URL, additionalFiles: [URL], searchPaths: [URL]) -> [String] { var args: [String] = [] args += searchPaths.filter { FileManager.default.fileExists(atPath: $0.path) }.flatMap { ["-F", $0.path] } args.append(file.path) args += additionalFiles.map { $0.path } let systemVersion = ProcessInfo().operatingSystemVersion let targetString = "x86_64-apple-macosx\(systemVersion.majorVersion).\(systemVersion.minorVersion)" args += ["-target", targetString] return args } class func swiftURLs(for additionalFiles: [URL]) -> [URL] { let fileManager = FileManager.default let swiftURLs = additionalFiles .flatMap { fileOrDirectory -> [URL] in var isDirectory = ObjCBool(booleanLiteral: false) guard fileManager.fileExists(atPath: fileOrDirectory.path, isDirectory: &isDirectory) else { print("Could not find additional file \(fileOrDirectory.path) to compile") exit(1) } if isDirectory.boolValue { return try! fileManager.contentsOfDirectory(at: fileOrDirectory, includingPropertiesForKeys: nil, options: .skipsHiddenFiles) .filter { $0.pathExtension == "swift" } } else { return [fileOrDirectory] } } return swiftURLs } // Returns the destination urls of the script and additional swift files class func setup(workingDirectory: URL, for script: URL, with swiftURLs: [URL]) -> (URL, [URL]) { let fileManager = FileManager.default let destinations = swiftURLs.map { workingDirectory.appendingPathComponent($0.lastPathComponent) } let scriptDestination = workingDirectory.appendingPathComponent("main.swift") zip(swiftURLs, destinations).forEach { source, destination in try! fileManager.copyItem(at: source, to: destination) } try! fileManager.copyItem(at: script, to: scriptDestination) return (scriptDestination, destinations) } }
mit
0024c3a9f2176b2ee27cd2028a00636a
35.775362
145
0.574384
4.833333
false
false
false
false
413738916/ZhiBoTest
ZhiBoSwift/Pods/Kingfisher/Sources/Filter.swift
27
5298
// // Filter.swift // Kingfisher // // Created by Wei Wang on 2016/08/31. // // Copyright (c) 2017 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import CoreImage import Accelerate // Reuse the same CI Context for all CI drawing. private let ciContext = CIContext(options: nil) /// Transformer method which will be used in to provide a `Filter`. public typealias Transformer = (CIImage) -> CIImage? /// Supply a filter to create an `ImageProcessor`. public protocol CIImageProcessor: ImageProcessor { var filter: Filter { get } } extension CIImageProcessor { public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.apply(filter) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Wrapper for a `Transformer` of CIImage filters. public struct Filter { let transform: Transformer public init(tranform: @escaping Transformer) { self.transform = tranform } /// Tint filter which will apply a tint color to images. public static var tint: (Color) -> Filter = { color in Filter { input in let colorFilter = CIFilter(name: "CIConstantColorGenerator")! colorFilter.setValue(CIColor(color: color), forKey: kCIInputColorKey) let colorImage = colorFilter.outputImage let filter = CIFilter(name: "CISourceOverCompositing")! filter.setValue(colorImage, forKey: kCIInputImageKey) filter.setValue(input, forKey: kCIInputBackgroundImageKey) #if swift(>=4.0) return filter.outputImage?.cropped(to: input.extent) #else return filter.outputImage?.cropping(to: input.extent) #endif } } public typealias ColorElement = (CGFloat, CGFloat, CGFloat, CGFloat) /// Color control filter which will apply color control change to images. public static var colorControl: (ColorElement) -> Filter = { arg -> Filter in let (brightness, contrast, saturation, inputEV) = arg return Filter { input in let paramsColor = [kCIInputBrightnessKey: brightness, kCIInputContrastKey: contrast, kCIInputSaturationKey: saturation] let paramsExposure = [kCIInputEVKey: inputEV] #if swift(>=4.0) let blackAndWhite = input.applyingFilter("CIColorControls", parameters: paramsColor) return blackAndWhite.applyingFilter("CIExposureAdjust", parameters: paramsExposure) #else let blackAndWhite = input.applyingFilter("CIColorControls", withInputParameters: paramsColor) return blackAndWhite.applyingFilter("CIExposureAdjust", withInputParameters: paramsExposure) #endif } } } extension Kingfisher where Base: Image { /// Apply a `Filter` containing `CIImage` transformer to `self`. /// /// - parameter filter: The filter used to transform `self`. /// /// - returns: A transformed image by input `Filter`. /// /// - Note: Only CG-based images are supported. If any error happens during transforming, `self` will be returned. public func apply(_ filter: Filter) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Tint image only works for CG-based image.") return base } let inputImage = CIImage(cgImage: cgImage) guard let outputImage = filter.transform(inputImage) else { return base } guard let result = ciContext.createCGImage(outputImage, from: outputImage.extent) else { assertionFailure("[Kingfisher] Can not make an tint image within context.") return base } #if os(macOS) return fixedForRetinaPixel(cgImage: result, to: size) #else return Image(cgImage: result, scale: base.scale, orientation: base.imageOrientation) #endif } }
mit
63afd7c1c1695470ea972af318986da3
37.671533
118
0.655342
4.865014
false
false
false
false
PekanMmd/Pokemon-XD-Code
Objects/managers/swift-png/sources/png/common.swift
1
7351
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // enum General // A namespace for general functionality. // # [Integer storage](general-storage-types) // # [See also](top-level-namespaces) // ## (1:top-level-namespaces) public enum General { } extension General { // struct General.Storage<I> // where I:Swift.FixedWidthInteger & Swift.BinaryInteger // @propertyWrapper // A property wrapper providing an immutable [`Swift.Int`] interface backed // by a different integer type. // # [See also](general-storage-types) // ## (general-storage-types) @propertyWrapper struct Storage<I>:Equatable where I:FixedWidthInteger & BinaryInteger { private var storage:I // init General.Storage.init(wrappedValue:) // Creates an instance of this property wrapper, with the given value // truncated to the width of the storage type [`I`]. // - wrappedValue : Swift.Int // The value to wrap. init(wrappedValue:Int) { self.storage = .init(truncatingIfNeeded: wrappedValue) } // var General.Storage.wrappedValue : Swift.Int { get } // The value wrapped by this property wrapper, expanded to an [`Swift.Int`]. var wrappedValue:Int { .init(self.storage) } } } extension General.Storage:Sendable where I:Sendable { } extension General { struct Heap<Key, Value> where Key:Comparable { private var storage:[(Key, Value)] // support 1-based indexing private subscript(index:Int) -> (key:Key, value:Value) { get { self.storage[index - 1] } set(item) { self.storage[index - 1] = item } } var count:Int { self.storage.count } var first:(key:Key, value:Value)? { self.storage.first } var isEmpty:Bool { self.storage.isEmpty } private var startIndex:Int { 1 } private var endIndex:Int { 1 + self.count } } } extension General.Heap { @inline(__always) private static func left(index:Int) -> Int { return index << 1 } @inline(__always) private static func right(index:Int) -> Int { return index << 1 + 1 } @inline(__always) private static func parent(index:Int) -> Int { return index >> 1 } private func highest(above child:Int) -> Int? { let p:Int = Self.parent(index: child) // make sure it’s not the root guard p >= self.startIndex else { return nil } // and the element is higher than the parent return self[child].key < self[p].key ? p : nil } private func lowest(below parent:Int) -> Int? { let r:Int = Self.right(index: parent), l:Int = Self.left (index: parent) guard l < self.endIndex else { return nil } guard r < self.endIndex else { return self[l].key < self[parent].key ? l : nil } let c:Int = self[r].key < self[l].key ? r : l return self[c].key < self[parent].key ? c : nil } @inline(__always) private mutating func swapAt(_ i:Int, _ j:Int) { self.storage.swapAt(i - 1, j - 1) } private mutating func siftUp(index:Int) { guard let parent:Int = self.highest(above: index) else { return } self.swapAt(index, parent) self.siftUp(index: parent) } private mutating func siftDown(index:Int) { guard let child:Int = self.lowest(below: index) else { return } self.swapAt (index, child) self.siftDown(index: child) } mutating func enqueue(key:Key, value:Value) { self.storage.append((key, value)) self.siftUp(index: self.endIndex - 1) } mutating func dequeue() -> (key:Key, value:Value)? { switch self.count { case 0: return nil case 1: return self.storage.removeLast() default: self.swapAt(self.startIndex, self.endIndex - 1) defer { self.siftDown(index: self.startIndex) } return self.storage.removeLast() } } init<S>(_ sequence:S) where S:Sequence, S.Element == (Key, Value) { self.storage = .init(sequence) // heapify let halfway:Int = Self.parent(index: self.endIndex - 1) + 1 for i:Int in (self.startIndex ..< halfway).reversed() { self.siftDown(index: i) } } } extension General.Heap:ExpressibleByArrayLiteral { init(arrayLiteral:(key:Key, value:Value)...) { self.init(arrayLiteral) } } extension Array where Element == UInt8 { func load<T, U>(bigEndian:T.Type, as type:U.Type, at byte:Int) -> U where T:FixedWidthInteger, U:BinaryInteger { return self[byte ..< byte + MemoryLayout<T>.size].load(bigEndian: T.self, as: U.self) } } extension UnsafeMutableBufferPointer where Element == UInt8 { func store<U, T>(_ value:U, asBigEndian type:T.Type, at byte:Int = 0) where U:BinaryInteger, T:FixedWidthInteger { let cast:T = .init(truncatingIfNeeded: value) Swift.withUnsafeBytes(of: cast.bigEndian) { guard let source:UnsafeRawPointer = $0.baseAddress, let destination:UnsafeMutableRawPointer = self.baseAddress.map(UnsafeMutableRawPointer.init(_:)) else { return } (destination + byte).copyMemory(from: source, byteCount: MemoryLayout<T>.size) } } } extension ArraySlice where Element == UInt8 { func load<T, U>(bigEndian:T.Type, as type:U.Type) -> U where T:FixedWidthInteger, U:BinaryInteger { return self.withUnsafeBufferPointer { (buffer:UnsafeBufferPointer<UInt8>) in assert(buffer.count >= MemoryLayout<T>.size, "attempt to load \(T.self) from slice of size \(buffer.count)") var storage:T = .init() let value:T = withUnsafeMutablePointer(to: &storage) { $0.deinitialize(count: 1) let source:UnsafeRawPointer = .init(buffer.baseAddress!), raw:UnsafeMutableRawPointer = .init($0) raw.copyMemory(from: source, byteCount: MemoryLayout<T>.size) return raw.load(as: T.self) } return U(T(bigEndian: value)) } } }
gpl-2.0
283165415456b15842327a133a26a15e
24.606272
93
0.527283
4.230858
false
false
false
false
testpress/ios-app
ios-app/UI/Dashboard/SectionControllers/BannerSectionController.swift
1
1598
// // BannerSectionController.swift // ios-app // // Created by Karthik on 30/04/21. // Copyright © 2021 Testpress. All rights reserved. // import IGListKit class BannerSectionController: ListSectionController { var dashboardData: DashboardResponse? var currentSection: DashboardSection? var contentId: Int? override init() { super.init() self.inset = UIEdgeInsets(top: 0, left: 10, bottom: 10, right: 10) } override func sizeForItem(at index: Int) -> CGSize { var width = (collectionContext?.containerSize.width ?? 0) * (3/4) if (UIDevice.current.userInterfaceIdiom == .pad) { width = 306 } return CGSize(width: width, height: 180) } override func cellForItem(at index: Int) -> UICollectionViewCell { let cell: BannerAdViewCell = collectionContext?.dequeueReusableCell(withNibName: "BannerAdViewCell", bundle: nil, for: self, at: index) as! BannerAdViewCell cell.dashboardData = dashboardData cell.initCell(bannerId: contentId!) return cell } override func didUpdate(to object: Any) { contentId = object as? Int } override func didSelectItem(at index: Int) { let bannerAd = dashboardData?.getBanner(id: contentId!) if (bannerAd != nil && bannerAd?.url != nil && bannerAd?.url != "") { let webViewController = WebViewController() webViewController.url = bannerAd!.url! viewController?.present(webViewController, animated: true, completion: nil) } } }
mit
3e4992f7e5c97c014dc6e6eefa59558f
30.94
164
0.638698
4.498592
false
false
false
false
hsoi/RxSwift
RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift
7
2829
// // RxTableViewReactiveArrayDataSource.swift // RxCocoa // // Created by Krunoslav Zaher on 6/26/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation import UIKit #if !RX_NO_MODULE import RxSwift #endif // objc monkey business class _RxTableViewReactiveArrayDataSource: NSObject, UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func _tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return _tableView(tableView, numberOfRowsInSection: section) } func _tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { rxAbstractMethod() } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return _tableView(tableView, cellForRowAtIndexPath: indexPath) } } class RxTableViewReactiveArrayDataSourceSequenceWrapper<S: SequenceType> : RxTableViewReactiveArrayDataSource<S.Generator.Element> , RxTableViewDataSourceType { typealias Element = S override init(cellFactory: CellFactory) { super.init(cellFactory: cellFactory) } func tableView(tableView: UITableView, observedEvent: Event<S>) { switch observedEvent { case .Next(let value): super.tableView(tableView, observedElements: Array(value)) case .Error(let error): bindingErrorToInterface(error) case .Completed: break } } } // Please take a look at `DelegateProxyType.swift` class RxTableViewReactiveArrayDataSource<Element> : _RxTableViewReactiveArrayDataSource { typealias CellFactory = (UITableView, Int, Element) -> UITableViewCell var itemModels: [Element]? = nil func modelAtIndex(index: Int) -> Element? { return itemModels?[index] } let cellFactory: CellFactory init(cellFactory: CellFactory) { self.cellFactory = cellFactory } override func _tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return itemModels?.count ?? 0 } override func _tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return cellFactory(tableView, indexPath.item, itemModels![indexPath.row]) } // reactive func tableView(tableView: UITableView, observedElements: [Element]) { self.itemModels = observedElements tableView.reloadData() } } #endif
mit
461551e0f6d813cbb2ac0dcf84707167
28.768421
130
0.67256
5.512671
false
false
false
false
wireapp/wire-ios-sync-engine
Tests/Source/Integration/ConnectionTests+Swift.swift
1
4753
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation class ConnectionTests_Swift: IntegrationTest { var tokens = [Any]() var listObserver: ChangeObserver! override func setUp() { super.setUp() setCurrentAPIVersion(.v0) } override func tearDown() { setCurrentAPIVersion(nil) listObserver = nil tokens = .init() super.tearDown() } func testThatConnectionRequestsToTwoUsersAreAddedToPending() { // given two remote users let userName1 = "Hans Von Üser" let userName2 = "Hannelore Isstgern" var mockUser1: MockUser! var mockUser2: MockUser! mockTransportSession.performRemoteChanges { session in mockUser1 = session.insertUser(withName: userName1) mockUser1.handle = "hans" XCTAssertNotNil(mockUser1.identifier) mockUser1.email = "" mockUser1.phone = "" mockUser2 = session.insertUser(withName: userName2) mockUser2.handle = "hannelore" XCTAssertNotNil(mockUser2.identifier) mockUser2.email = "" mockUser2.phone = "" } XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) XCTAssertTrue(login()) let active = ZMConversationList.conversations(inUserSession: userSession!) let count = active.count listObserver = ConversationListChangeObserver(conversationList: active) var conv1: ZMConversation! var conv2: ZMConversation! // when we search and send connection requests to users userSession?.perform { self.searchAndConnectToUser(withName: userName1, searchQuery: "Hans") self.searchAndConnectToUser(withName: userName2, searchQuery: "Hannelore") } XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // we should see two new active conversations let realUser1 = user(for: mockUser1) XCTAssertNotNil(realUser1) XCTAssertEqual(realUser1?.connection?.status, .sent) let realUser2 = user(for: mockUser2) XCTAssertNotNil(realUser2) XCTAssertEqual(realUser2?.connection?.status, .sent) conv1 = realUser1?.oneToOneConversation XCTAssertNotNil(conv1) conv2 = realUser2?.oneToOneConversation XCTAssertNotNil(conv2) XCTAssertEqual(active.count, count + 2) let observer = ConversationChangeObserver() tokens.append(ConversationChangeInfo.add(observer: observer, for: conv1)) tokens.append(ConversationChangeInfo.add(observer: observer, for: conv2)) // when the remote user accepts the connection requests mockTransportSession.performRemoteChanges { session in session.remotelyAcceptConnection(to: mockUser1) session.remotelyAcceptConnection(to: mockUser2) } XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // we should receive notifications about the changed status and participants let notifications = observer.notifications XCTAssertNotNil(notifications) var conv1StateChanged = false var conv2StateChanged = false var conv1ParticipantsChanged = false var conv2ParticipantsChanged = false (notifications as? [ConversationChangeInfo])?.forEach { note in let conv = note.conversation if note.participantsChanged { conv1ParticipantsChanged = conv1ParticipantsChanged ? true : (conv == conv1) conv2ParticipantsChanged = conv2ParticipantsChanged ? true : (conv == conv2) } if note.connectionStateChanged { conv1StateChanged = conv1StateChanged ? true : (conv == conv1) conv2StateChanged = conv2StateChanged ? true : (conv == conv2) } } XCTAssertTrue(conv1StateChanged) XCTAssertTrue(conv2StateChanged) XCTAssertTrue(conv1ParticipantsChanged) XCTAssertTrue(conv2ParticipantsChanged) } }
gpl-3.0
ee6b50f3c37cfdd982920c1b8111622c
34.462687
92
0.669192
4.95
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothGATT/GATTCrossTrainerData.swift
1
34386
// // GATTCrossTrainerData.swift // Bluetooth // // Created by Jorge Loc Rubio on 6/27/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /** Cross Trainer Data The Cross Trainer Data characteristic is used to send training-related data to the Client from a cross trainer (Server). - SeeAlso: [Cross Trainer Data](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.cross_trainer_data.xml) */ @frozen public struct GATTCrossTrainerData { internal static let minimumLength = MemoryLayout<UInt24>.size public static var uuid: BluetoothUUID { return .crossTrainerData } internal var flags: BitMaskOptionSet<Flag> { var flags = BitMaskOptionSet<Flag>() if instantaneousSpeed != nil { flags.insert(.moreData) } if averageSpeed != nil { flags.insert(.averageSpeed) } if totalDistance != nil { flags.insert(.totalDistance) } if stepPerMinute != nil && averageStepRate != nil { flags.insert(.stepCount) } if strideCount != nil { flags.insert(.strideCount) } if positiveElevationGain != nil && negativeElevationGain != nil { flags.insert(.elevationGain) } if inclination != nil && rampAngleSetting != nil { flags.insert(.inclinationAndRampAngleSetting) } if resistanceLevel != nil { flags.insert(.resistanceLevel) } if instantaneousPower != nil { flags.insert(.instantaneousPower) } if averagePower != nil { flags.insert(.averagePower) } if totalEnergy != nil && energyPerHour != nil && energyPerMinute != nil { flags.insert(.expendedEnergy) } if heartRate != nil { flags.insert(.heartRate) } if metabolicEquivalent != nil { flags.insert(.metabolicEquivalent) } if elapsedTime != nil { flags.insert(.elapsedTime) } if remainingTime != nil { flags.insert(.remainingTime) } return flags } public var instantaneousSpeed: KilometerPerHour? public var averageSpeed: KilometerPerHour? public var totalDistance: Metre.Bit24? public var stepPerMinute: StepPerMinute? public var averageStepRate: StepPerMinute? public var strideCount: Unitless.Unsigned? public var positiveElevationGain: Metre.Bits16? public var negativeElevationGain: Metre.Bits16? public var inclination: Percentage? public var rampAngleSetting: PlainAngleDegree? public var resistanceLevel: Unitless.Signed? public var instantaneousPower: Power? public var averagePower: Power? public var totalEnergy: GATTKilogramCalorie.Bits16? public var energyPerHour: GATTKilogramCalorie.Bits16? public var energyPerMinute: GATTKilogramCalorie.Byte? public var heartRate: GATTBeatsPerMinute.Byte? public var metabolicEquivalent: MetabolicEquivalent? public var elapsedTime: Time? public var remainingTime: Time? public init(instantaneousSpeed: KilometerPerHour? = nil, averageSpeed: KilometerPerHour? = nil, totalDistance: Metre.Bit24? = nil, stepPerMinute: StepPerMinute? = nil, averageStepRate: StepPerMinute? = nil, strideCount: Unitless.Unsigned? = nil, positiveElevationGain: Metre.Bits16? = nil, negativeElevationGain: Metre.Bits16? = nil, inclination: Percentage? = nil, rampAngleSetting: PlainAngleDegree? = nil, resistanceLevel: Unitless.Signed? = nil, instantaneousPower: Power? = nil, averagePower: Power? = nil, totalEnergy: GATTKilogramCalorie.Bits16? = nil, energyPerHour: GATTKilogramCalorie.Bits16? = nil, energyPerMinute: GATTKilogramCalorie.Byte? = nil, heartRate: GATTBeatsPerMinute.Byte? = nil, metabolicEquivalent: MetabolicEquivalent? = nil, elapsedTime: Time? = nil, remainingTime: Time? = nil) { self.instantaneousSpeed = instantaneousSpeed self.averageSpeed = averageSpeed self.totalDistance = totalDistance self.stepPerMinute = stepPerMinute self.averageStepRate = averageStepRate self.strideCount = strideCount self.positiveElevationGain = positiveElevationGain self.negativeElevationGain = negativeElevationGain self.inclination = inclination self.rampAngleSetting = rampAngleSetting self.resistanceLevel = resistanceLevel self.instantaneousPower = instantaneousPower self.averagePower = averagePower self.totalEnergy = totalEnergy self.energyPerHour = energyPerHour self.energyPerMinute = energyPerMinute self.heartRate = heartRate self.metabolicEquivalent = metabolicEquivalent self.elapsedTime = elapsedTime self.remainingTime = remainingTime } // swiftlint:disable:next cyclomatic_complexity public init?(data: Data) { guard data.count >= type(of: self).minimumLength else { return nil } let flags = BitMaskOptionSet<Flag>(rawValue: UInt32(littleEndian: UInt32(bytes: (data[0], data[1], data[2], 0)))) var index = 2 // flags size if flags.contains(.moreData) { guard index + KilometerPerHour.length < data.count else { return nil } self.instantaneousSpeed = KilometerPerHour(rawValue: UInt16(littleEndian: UInt16(bytes: (data[index + 1], data[index + 2])))) index += KilometerPerHour.length } else { self.instantaneousSpeed = nil } if flags.contains(.averageSpeed) { guard index + KilometerPerHour.length < data.count else { return nil } self.averageSpeed = KilometerPerHour(rawValue: UInt16(littleEndian: UInt16(bytes: (data[index + 1], data[index + 2])))) index += KilometerPerHour.length } else { self.averageSpeed = nil } if flags.contains(.totalDistance) { guard index + MemoryLayout<UInt16>.size + MemoryLayout<UInt8>.size < data.count else { return nil } self.totalDistance = Metre.Bit24(rawValue: UInt24(littleEndian: UInt24(bytes: (data[index + 1], data[index + 2], data[index + 3])))) index += MemoryLayout<UInt16>.size + MemoryLayout<UInt8>.size } else { self.totalDistance = nil } if flags.contains(.stepCount) { guard index + StepPerMinute.length + StepPerMinute.length < data.count else { return nil } self.stepPerMinute = StepPerMinute(rawValue: UInt16(littleEndian: UInt16(bytes: (data[index + 1], data[index + 2])))) self.averageStepRate = StepPerMinute(rawValue: UInt16(littleEndian: UInt16(bytes: (data[index + 3], data[index + 4])))) index += StepPerMinute.length * 2 } else { self.stepPerMinute = nil self.averageStepRate = nil } if flags.contains(.strideCount) { guard index + Unitless.Unsigned.length < data.count else { return nil } self.strideCount = Unitless.Unsigned(rawValue: UInt16(littleEndian: UInt16(bytes: (data[index + 1], data[index + 2])))) index += Unitless.Unsigned.length } else { self.strideCount = nil } if flags.contains(.elevationGain) { guard index + Metre.Bits16.length + Metre.Bits16.length < data.count else { return nil } self.positiveElevationGain = Metre.Bits16(rawValue: UInt16(littleEndian: UInt16(bytes: (data[index + 1], data[index + 2])))) self.negativeElevationGain = Metre.Bits16(rawValue: UInt16(littleEndian: UInt16(bytes: (data[index + 3], data[index + 4])))) index += Metre.Bits16.length * 2 } else { self.positiveElevationGain = nil self.negativeElevationGain = nil } if flags.contains(.inclinationAndRampAngleSetting) { guard index + Percentage.length + PlainAngleDegree.length < data.count else { return nil } self.inclination = Percentage(rawValue: Int16(bitPattern: UInt16(littleEndian: UInt16(bytes: (data[index + 1], data[index + 2]))))) self.rampAngleSetting = PlainAngleDegree(rawValue: Int16(bitPattern: UInt16(littleEndian: UInt16(bytes: (data[index + 3], data[index + 4]))))) index += Percentage.length + PlainAngleDegree.length } else { self.inclination = nil self.rampAngleSetting = nil } if flags.contains(.resistanceLevel) { guard index + Unitless.Signed.length < data.count else { return nil } self.resistanceLevel = Unitless.Signed(rawValue: Int16(bitPattern: UInt16(littleEndian: UInt16(bytes: (data[index + 1], data[index + 2]))))) index += Unitless.Signed.length } else { self.resistanceLevel = nil } if flags.contains(.instantaneousPower) { guard index + Power.length < data.count else { return nil } self.instantaneousPower = Power(rawValue: Int16(bitPattern: UInt16(littleEndian: UInt16(bytes: (data[index + 1], data[index + 2]))))) index += Power.length } else { self.instantaneousPower = nil } if flags.contains(.averagePower) { guard index + Power.length < data.count else { return nil } self.averagePower = Power(rawValue: Int16(bitPattern: UInt16(littleEndian: UInt16(bytes: (data[index + 1], data[index + 2]))))) index += Power.length } else { self.averagePower = nil } if flags.contains(.expendedEnergy) { guard index + GATTKilogramCalorie.Bits16.length * 2 + GATTKilogramCalorie.Byte.length < data.count else { return nil } self.totalEnergy = GATTKilogramCalorie.Bits16(rawValue: UInt16(littleEndian: UInt16(bytes: (data[index + 1], data[index + 2])))) self.energyPerHour = GATTKilogramCalorie.Bits16(rawValue: UInt16(littleEndian: UInt16(bytes: (data[index + 3], data[index + 4])))) self.energyPerMinute = GATTKilogramCalorie.Byte(rawValue: data[index + 5]) index += GATTKilogramCalorie.Bits16.length * 2 + GATTKilogramCalorie.Byte.length } else { self.averageSpeed = nil self.energyPerHour = nil self.energyPerMinute = nil } if flags.contains(.heartRate) { guard index + GATTBeatsPerMinute.Byte.length < data.count else { return nil } self.heartRate = GATTBeatsPerMinute.Byte(rawValue: data[index + 1]) index += GATTBeatsPerMinute.Byte.length } else { self.heartRate = nil } if flags.contains(.metabolicEquivalent) { guard index + MetabolicEquivalent.length < data.count else { return nil } self.metabolicEquivalent = MetabolicEquivalent(rawValue: data[index + 1]) index += MetabolicEquivalent.length } else { self.metabolicEquivalent = nil } if flags.contains(.elapsedTime) { guard index + Time.length < data.count else { return nil } self.elapsedTime = Time(rawValue: UInt16(littleEndian: UInt16(bytes: (data[index + 1], data[index + 2])))) index += Time.length } else { self.elapsedTime = nil } if flags.contains(.remainingTime) { guard index + Time.length < data.count else { return nil } self.remainingTime = Time(rawValue: UInt16(littleEndian: UInt16(bytes: (data[index + 1], data[index + 2])))) index += Time.length } else { self.remainingTime = nil } } public var data: Data { let flags = self.flags var totalBytes = MemoryLayout<UInt24>.size //flag size if flags.contains(.moreData) { totalBytes += KilometerPerHour.length } if flags.contains(.averageSpeed) { totalBytes += KilometerPerHour.length } if flags.contains(.totalDistance) { totalBytes += MemoryLayout<UInt24>.size } if flags.contains(.stepCount) { totalBytes += StepPerMinute.length * 2 } if flags.contains(.strideCount) { totalBytes += Unitless.Unsigned.length } if flags.contains(.elevationGain) { totalBytes += Metre.Bits16.length * 2 } if flags.contains(.inclinationAndRampAngleSetting) { totalBytes += Percentage.length + PlainAngleDegree.length } if flags.contains(.resistanceLevel) { totalBytes += Unitless.Signed.length } if flags.contains(.instantaneousPower) { totalBytes += Power.length } if flags.contains(.averagePower) { totalBytes += Power.length } if flags.contains(.expendedEnergy) { totalBytes += GATTKilogramCalorie.Byte.length } if flags.contains(.heartRate) { totalBytes += GATTBeatsPerMinute.Byte.length } if flags.contains(.metabolicEquivalent) { totalBytes += MetabolicEquivalent.length } if flags.contains(.elapsedTime) { totalBytes += Time.length } if flags.contains(.remainingTime) { totalBytes += Time.length } let flagBytes = flags.rawValue.littleEndian.bytes var data = Data([ flagBytes.0, flagBytes.1, flagBytes.2 ]) data.reserveCapacity(totalBytes) if let instantaneousSpeed = self.instantaneousSpeed { let bytes = instantaneousSpeed.rawValue.littleEndian.bytes data += [bytes.0, bytes.1] } if let averageSpeed = self.averageSpeed { let bytes = averageSpeed.rawValue.littleEndian.bytes data += [bytes.0, bytes.1] } if let totalDistance = self.totalDistance { let bytes = totalDistance.rawValue.littleEndian.bytes //24bits data += [bytes.0, bytes.1, bytes.2] } if let stepPerMinute = self.stepPerMinute { let bytes = stepPerMinute.rawValue.littleEndian.bytes data += [bytes.0, bytes.1] } if let averageStepRate = self.averageStepRate { let bytes = averageStepRate.rawValue.littleEndian.bytes data += [bytes.0, bytes.1] } if let strideCount = self.strideCount { let bytes = strideCount.rawValue.littleEndian.bytes data += [bytes.0, bytes.1] } if let positiveElevationGain = self.positiveElevationGain { let bytes = positiveElevationGain.rawValue.littleEndian.bytes data += [bytes.0, bytes.1] } if let negativeElevationGain = self.negativeElevationGain { let bytes = negativeElevationGain.rawValue.littleEndian.bytes data += [bytes.0, bytes.1] } if let inclination = self.inclination { let bytes = UInt16(bitPattern: inclination.rawValue).littleEndian.bytes data += [bytes.0, bytes.1] } if let rampAngleSetting = self.rampAngleSetting { let bytes = UInt16(bitPattern: rampAngleSetting.rawValue).littleEndian.bytes data += [bytes.0, bytes.1] } if let resistanceLevel = self.resistanceLevel { let bytes = UInt16(bitPattern: resistanceLevel.rawValue).littleEndian.bytes data += [bytes.0, bytes.1] } if let instantaneousPower = self.instantaneousPower { let bytes = UInt16(bitPattern: instantaneousPower.rawValue).littleEndian.bytes data += [bytes.0, bytes.1] } if let averagePower = self.averagePower { let bytes = UInt16(bitPattern: averagePower.rawValue).littleEndian.bytes data += [bytes.0, bytes.1] } if let totalEnergy = self.totalEnergy { let bytes = totalEnergy.rawValue.littleEndian.bytes data += [bytes.0, bytes.1] } if let energyPerHour = self.energyPerHour { let bytes = energyPerHour.rawValue.littleEndian.bytes data += [bytes.0, bytes.1] } if let energyPerMinute = self.energyPerMinute { data += [energyPerMinute.rawValue] } if let hearRate = self.heartRate { data += [hearRate.rawValue] } if let metabolicEquivalent = self.metabolicEquivalent { data += [metabolicEquivalent.rawValue] } if let elapsedTime = self.elapsedTime { let bytes = elapsedTime.rawValue.littleEndian.bytes data += [bytes.0, bytes.1] } if let remainingTime = self.remainingTime { let bytes = remainingTime.rawValue.littleEndian.bytes data += [bytes.0, bytes.1] } return data } /// These flags define which data fields are present in the Characteristic value. internal enum Flag: UInt32, BitMaskOption { /// More Data case moreData = 0b01 /// Average Speed present case averageSpeed = 0b10 /// Total Distance Present case totalDistance = 0b100 /// Step Count present case stepCount = 0b1000 /// Stride Count present case strideCount = 0b10000 /// Elevation Gain present case elevationGain = 0b100000 /// Inclination and Ramp Angle Setting present case inclinationAndRampAngleSetting = 0b1000000 /// Resistance Level Present case resistanceLevel = 0b10000000 /// Instantaneous Power present case instantaneousPower = 0b100000000 /// Average Power present case averagePower = 0b1000000000 /// Expended Energy present case expendedEnergy = 0b10000000000 /// Heart Rate present case heartRate = 0b100000000000 /// Metabolic Equivalent present case metabolicEquivalent = 0b1000000000000 // Elapsed Time present case elapsedTime = 0b10000000000000 // Remaining Time present case remainingTime = 0b100000000000000 // Movement Direction case movementDirection = 0b1000000000000000 public static let allCases: [Flag] = [ .moreData, .averageSpeed, .totalDistance, .stepCount, .strideCount, .elevationGain, .inclinationAndRampAngleSetting, .resistanceLevel, .instantaneousPower, .averagePower, .expendedEnergy, .heartRate, .metabolicEquivalent, .elapsedTime, .remainingTime, .movementDirection ] } } extension GATTCrossTrainerData { public struct KilometerPerHour: BluetoothUnit { internal static let length = MemoryLayout<UInt16>.size public static var unitType: UnitIdentifier { return .kilometrePerHour } public var rawValue: UInt16 public init(rawValue: UInt16) { self.rawValue = rawValue } } public enum Metre { public struct Bit24: BluetoothUnit { internal static let length = MemoryLayout<UInt24>.size public static var unitType: UnitIdentifier { return .metre } public var rawValue: UInt24 public init(rawValue: UInt24) { self.rawValue = rawValue } } public struct Bits16: BluetoothUnit { internal static let length = MemoryLayout<UInt16>.size public static var unitType: UnitIdentifier { return .metre } public var rawValue: UInt16 public init(rawValue: UInt16) { self.rawValue = rawValue } } } public struct StepPerMinute: BluetoothUnit { internal static let length = MemoryLayout<UInt16>.size public static var unitType: UnitIdentifier { return .step } public var rawValue: UInt16 public init(rawValue: UInt16) { self.rawValue = rawValue } } public enum Unitless { public struct Unsigned: BluetoothUnit { internal static let length = MemoryLayout<UInt16>.size public static var unitType: UnitIdentifier { return .unitless } public var rawValue: UInt16 public init(rawValue: UInt16) { self.rawValue = rawValue } } public struct Signed: BluetoothUnit { internal static let length = MemoryLayout<Int16>.size public static var unitType: UnitIdentifier { return .unitless } public var rawValue: Int16 public init(rawValue: Int16) { self.rawValue = rawValue } } } public struct Percentage: BluetoothUnit { internal static let length = MemoryLayout<Int16>.size public static var unitType: UnitIdentifier { return .percentage } public var rawValue: Int16 public init(rawValue: Int16) { self.rawValue = rawValue } } public struct PlainAngleDegree: BluetoothUnit { internal static let length = MemoryLayout<Int16>.size public static var unitType: UnitIdentifier { return .degree } public var rawValue: Int16 public init(rawValue: Int16) { self.rawValue = rawValue } } public struct Power: BluetoothUnit { internal static let length = MemoryLayout<Int16>.size public static var unitType: UnitIdentifier { return .power } public var rawValue: Int16 public init(rawValue: Int16) { self.rawValue = rawValue } } public struct MetabolicEquivalent: BluetoothUnit { internal static let length = MemoryLayout<UInt8>.size public static var unitType: UnitIdentifier { return .metabolicEquivalent } public var rawValue: UInt8 public init(rawValue: UInt8) { self.rawValue = rawValue } } public struct Time: BluetoothUnit { internal static let length = MemoryLayout<UInt16>.size public static var unitType: UnitIdentifier { return .second } public var rawValue: UInt16 public init(rawValue: UInt16) { self.rawValue = rawValue } } } extension GATTCrossTrainerData: Equatable { public static func == (lhs: GATTCrossTrainerData, rhs: GATTCrossTrainerData) -> Bool { return lhs.instantaneousSpeed == rhs.instantaneousSpeed && lhs.averageSpeed == rhs.averageSpeed && lhs.totalDistance == rhs.totalDistance && lhs.stepPerMinute == rhs.stepPerMinute && lhs.averageStepRate == rhs.averageStepRate && lhs.strideCount == rhs.strideCount && lhs.positiveElevationGain == rhs.positiveElevationGain && lhs.negativeElevationGain == rhs.negativeElevationGain && lhs.inclination == rhs.inclination && lhs.rampAngleSetting == rhs.rampAngleSetting && lhs.resistanceLevel == rhs.resistanceLevel && lhs.instantaneousPower == rhs.instantaneousPower && lhs.averagePower == rhs.averagePower && lhs.totalEnergy == rhs.totalEnergy && lhs.energyPerHour == rhs.energyPerHour && lhs.energyPerMinute == rhs.energyPerMinute && lhs.heartRate == rhs.heartRate && lhs.metabolicEquivalent == rhs.metabolicEquivalent && lhs.elapsedTime == rhs.elapsedTime && lhs.remainingTime == rhs.remainingTime } } extension GATTCrossTrainerData.KilometerPerHour: Equatable { public static func == (lhs: GATTCrossTrainerData.KilometerPerHour, rhs: GATTCrossTrainerData.KilometerPerHour) -> Bool { return lhs.rawValue == rhs.rawValue } } extension GATTCrossTrainerData.KilometerPerHour: CustomStringConvertible { public var description: String { return rawValue.description } } extension GATTCrossTrainerData.KilometerPerHour: ExpressibleByIntegerLiteral { public init(integerLiteral value: UInt16) { self.init(rawValue: value) } } extension GATTCrossTrainerData.Metre.Bit24: Equatable { public static func == (lhs: GATTCrossTrainerData.Metre.Bit24, rhs: GATTCrossTrainerData.Metre.Bit24) -> Bool { return lhs.rawValue == rhs.rawValue } } extension GATTCrossTrainerData.Metre.Bit24: CustomStringConvertible { public var description: String { return rawValue.description } } extension GATTCrossTrainerData.Metre.Bits16: Equatable { public static func == (lhs: GATTCrossTrainerData.Metre.Bits16, rhs: GATTCrossTrainerData.Metre.Bits16) -> Bool { return lhs.rawValue == rhs.rawValue } } extension GATTCrossTrainerData.Metre.Bits16: CustomStringConvertible { public var description: String { return rawValue.description } } extension GATTCrossTrainerData.Metre.Bits16: ExpressibleByIntegerLiteral { public init(integerLiteral value: UInt16) { self.init(rawValue: value) } } extension GATTCrossTrainerData.StepPerMinute: Equatable { public static func == (lhs: GATTCrossTrainerData.StepPerMinute, rhs: GATTCrossTrainerData.StepPerMinute) -> Bool { return lhs.rawValue == rhs.rawValue } } extension GATTCrossTrainerData.StepPerMinute: CustomStringConvertible { public var description: String { return rawValue.description } } extension GATTCrossTrainerData.StepPerMinute: ExpressibleByIntegerLiteral { public init(integerLiteral value: UInt16) { self.init(rawValue: value) } } extension GATTCrossTrainerData.Unitless.Unsigned: Equatable { public static func == (lhs: GATTCrossTrainerData.Unitless.Unsigned, rhs: GATTCrossTrainerData.Unitless.Unsigned) -> Bool { return lhs.rawValue == rhs.rawValue } } extension GATTCrossTrainerData.Unitless.Unsigned: CustomStringConvertible { public var description: String { return rawValue.description } } extension GATTCrossTrainerData.Unitless.Unsigned: ExpressibleByIntegerLiteral { public init(integerLiteral value: UInt16) { self.init(rawValue: value) } } extension GATTCrossTrainerData.Unitless.Signed: Equatable { public static func == (lhs: GATTCrossTrainerData.Unitless.Signed, rhs: GATTCrossTrainerData.Unitless.Signed) -> Bool { return lhs.rawValue == rhs.rawValue } } extension GATTCrossTrainerData.Unitless.Signed: CustomStringConvertible { public var description: String { return rawValue.description } } extension GATTCrossTrainerData.Unitless.Signed: ExpressibleByIntegerLiteral { public init(integerLiteral value: Int16) { self.init(rawValue: value) } } extension GATTCrossTrainerData.Percentage: Equatable { public static func == (lhs: GATTCrossTrainerData.Percentage, rhs: GATTCrossTrainerData.Percentage) -> Bool { return lhs.rawValue == rhs.rawValue } } extension GATTCrossTrainerData.Percentage: CustomStringConvertible { public var description: String { return rawValue.description } } extension GATTCrossTrainerData.Percentage: ExpressibleByIntegerLiteral { public init(integerLiteral value: Int16) { self.init(rawValue: value) } } extension GATTCrossTrainerData.PlainAngleDegree: Equatable { public static func == (lhs: GATTCrossTrainerData.PlainAngleDegree, rhs: GATTCrossTrainerData.PlainAngleDegree) -> Bool { return lhs.rawValue == rhs.rawValue } } extension GATTCrossTrainerData.PlainAngleDegree: CustomStringConvertible { public var description: String { return rawValue.description } } extension GATTCrossTrainerData.PlainAngleDegree: ExpressibleByIntegerLiteral { public init(integerLiteral value: Int16) { self.init(rawValue: value) } } extension GATTCrossTrainerData.Power: Equatable { public static func == (lhs: GATTCrossTrainerData.Power, rhs: GATTCrossTrainerData.Power) -> Bool { return lhs.rawValue == rhs.rawValue } } extension GATTCrossTrainerData.Power: CustomStringConvertible { public var description: String { return rawValue.description } } extension GATTCrossTrainerData.Power: ExpressibleByIntegerLiteral { public init(integerLiteral value: Int16) { self.init(rawValue: value) } } extension GATTCrossTrainerData.MetabolicEquivalent: Equatable { public static func == (lhs: GATTCrossTrainerData.MetabolicEquivalent, rhs: GATTCrossTrainerData.MetabolicEquivalent) -> Bool { return lhs.rawValue == rhs.rawValue } } extension GATTCrossTrainerData.MetabolicEquivalent: CustomStringConvertible { public var description: String { return rawValue.description } } extension GATTCrossTrainerData.MetabolicEquivalent: ExpressibleByIntegerLiteral { public init(integerLiteral value: UInt8) { self.init(rawValue: value) } } extension GATTCrossTrainerData.Time: Equatable { public static func == (lhs: GATTCrossTrainerData.Time, rhs: GATTCrossTrainerData.Time) -> Bool { return lhs.rawValue == rhs.rawValue } } extension GATTCrossTrainerData.Time: CustomStringConvertible { public var description: String { return rawValue.description } } extension GATTCrossTrainerData.Time: ExpressibleByIntegerLiteral { public init(integerLiteral value: UInt16) { self.init(rawValue: value) } }
mit
ff33cab7be9a336c03b1d73d7b2fe4ab
28.414029
155
0.557307
5.217754
false
false
false
false
4faramita/TweeBox
TweeBox/DataExtension.swift
1
660
// // DataExtension.swift // TweeBox // // Created by 4faramita on 2017/8/31. // Copyright © 2017年 4faramita. All rights reserved. // import Foundation public extension Data { var MIMEType: String { var values = [UInt8](repeating:0, count:1) self.copyBytes(to: &values, count: 1) let ext: String switch (values[0]) { case 0xFF: ext = "image/jpeg" case 0x89: ext = "image/png" case 0x47: ext = "image/gif" case 0x49, 0x4D : ext = "image/tiff" default: ext = "image/png" } return ext } }
mit
c2cd9b551886db8e686f6b34b21cfa96
20.193548
53
0.509893
3.47619
false
false
false
false
borglab/SwiftFusion
Tests/BeeTrackingTests/TrackingFactorGraphTests.swift
1
2792
import XCTest import BeeTracking import PythonKit import PenguinStructures import BeeDataset import BeeTracking import SwiftFusion import TensorFlow class TrackingFactorGraphTests: XCTestCase { let datasetDirectory = URL.sourceFileDirectory().appendingPathComponent("../BeeDatasetTests/fakeDataset") func testGetTrainingBatches() { let dataset = OISTBeeVideo(directory: datasetDirectory, length: 2)! let (fg, bg, _) = getTrainingBatches( dataset: dataset, boundingBoxSize: (40, 70), fgBatchSize: 10, bgBatchSize: 11, fgRandomFrameCount: 1, bgRandomFrameCount: 1 ) XCTAssertEqual(fg.shape, TensorShape([10, 40, 70, 1])) XCTAssertEqual(bg.shape, TensorShape([11, 40, 70, 1])) } func testTrainRPTracker() { let trainingData = OISTBeeVideo(directory: datasetDirectory, length: 1)! let testData = OISTBeeVideo(directory: datasetDirectory, length: 2)! // Test regular training var tracker : TrackingConfiguration<Tuple1<Pose2>> = trainRPTracker( trainingData: trainingData, frames: testData.frames, boundingBoxSize: (40, 70), withFeatureSize: 100, fgRandomFrameCount: 1, bgRandomFrameCount: 1 ) XCTAssertEqual(tracker.frameVariableIDs.count, 2) // Test training with Monte Carlo EM tracker = trainRPTracker( trainingData: trainingData, frames: testData.frames, boundingBoxSize: (40, 70), withFeatureSize: 100, fgRandomFrameCount: 1, bgRandomFrameCount: 1, usingEM: true ) XCTAssertEqual(tracker.frameVariableIDs.count, 2) } func testCreateSingleRPTrack() { let trainingData = OISTBeeVideo(directory: datasetDirectory, length: 2)! let testData = OISTBeeVideo(directory: datasetDirectory, length: 2)! var tracker = trainRPTracker( trainingData: trainingData, frames: testData.frames, boundingBoxSize: (40, 70), withFeatureSize: 100, fgRandomFrameCount: 2, bgRandomFrameCount: 2 ) var (track, groundTruth) = createSingleTrack( onTrack: 0, withTracker: &tracker, andTestData: testData ) XCTAssertEqual(track.count, 2) XCTAssertEqual(groundTruth.count, 2) // Now try with sampling (track, groundTruth) = createSingleTrack( onTrack: 0, withTracker: &tracker, andTestData: testData, withSampling: true ) XCTAssertEqual(track.count, 2) XCTAssertEqual(groundTruth.count, 2) } // func testRunRPTracker() { // let fig: PythonObject = runRPTracker(onTrack: 15) // XCTAssertEqual(fig.axes.count, 2) // } } extension URL { /// Creates a URL for the directory containing the caller's source file. fileprivate static func sourceFileDirectory(file: String = #filePath) -> URL { return URL(fileURLWithPath: file).deletingLastPathComponent() } }
apache-2.0
46e5be53b7599e1f0f85573cc6775838
32.238095
107
0.713825
4.160954
false
true
false
false
cuappdev/tcat-ios
TCAT/Model/Waypoint.swift
1
3858
// // Waypoint.swift // TCAT // // Created by Annie Cheng on 2/24/17. // Copyright © 2017 cuappdev. All rights reserved. // import CoreLocation import UIKit enum WaypointType: String, Codable { case bus case bussing /// The endLocation destination point of the trip case destination /// The startLocation origin point of the trip case origin case none /// Used for bus stops case stop case walk case walking } class Waypoint: NSObject { let smallDiameter: CGFloat = 12 let largeDiameter: CGFloat = 24 var busNumber: Int = 0 var iconView: UIView = UIView() var latitude: CLLocationDegrees = 0 var longitude: CLLocationDegrees = 0 var wpType: WaypointType = .origin init(lat: CLLocationDegrees, long: CLLocationDegrees, wpType: WaypointType, busNumber: Int = 0, isStop: Bool = false) { super.init() self.latitude = lat self.longitude = long self.wpType = wpType self.busNumber = busNumber switch wpType { case .origin: self.iconView = Circle(size: .large, style: .solid, color: isStop ? Colors.tcatBlue : Colors.metadataIcon) case .destination: self.iconView = Circle(size: .large, style: .bordered, color: isStop ? Colors.tcatBlue : Colors.metadataIcon) case .bus: self.iconView = Circle(size: .small, style: .solid, color: Colors.tcatBlue) case .walk: self.iconView = Circle(size: .small, style: .solid, color: Colors.metadataIcon) case .none, .stop, .walking, .bussing: self.iconView = UIView() } } var coordinate: CLLocationCoordinate2D { return CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } func drawOriginIcon() -> UIView { return drawCircle(radius: largeDiameter / 2, innerColor: Colors.metadataIcon, borderColor: Colors.white) } func drawDestinationIcon() -> UIView { return drawCircle(radius: largeDiameter / 2, innerColor: Colors.tcatBlue, borderColor: Colors.white) } func drawStopIcon() -> UIView { return drawCircle(radius: smallDiameter / 2, innerColor: Colors.white) } func drawBusPointIcon() -> UIView { return drawCircle(radius: smallDiameter / 2, innerColor: Colors.tcatBlue) } func drawWalkPointIcon() -> UIView { return drawCircle(radius: smallDiameter / 2, innerColor: Colors.metadataIcon) } /// Draw waypoint meant to be placed as an iconView on map func drawCircle(radius: CGFloat, innerColor: UIColor, borderColor: UIColor? = nil) -> UIView { let constant: CGFloat = 1 let dim = (radius * 2) + 4 let base = UIView(frame: CGRect(x: 0, y: 0, width: dim, height: dim)) let circleView = UIView(frame: CGRect(x: 0, y: 0, width: radius * 2, height: radius * 2)) circleView.center = base.center circleView.layer.cornerRadius = circleView.frame.width / 2.0 circleView.layer.masksToBounds = false circleView.layer.shadowColor = Colors.black.cgColor circleView.layer.shadowOffset = CGSize(width: 0, height: constant) circleView.layer.shadowOpacity = 0.25 circleView.layer.shadowRadius = 1 circleView.backgroundColor = innerColor if let borderColor = borderColor { circleView.layer.borderWidth = 4 circleView.layer.borderColor = borderColor.cgColor } base.addSubview(circleView) return base } func setColor(color: UIColor) { switch wpType { case .destination: iconView.layer.borderColor = color.cgColor case .origin, .stop, .bus, .walk, .bussing, .walking: iconView.backgroundColor = color case .none: break } } }
mit
d642b9ddb18949e5f88eefd9ea1a8ebb
29.611111
123
0.639876
4.314318
false
false
false
false
zhugejunwei/LeetCode
349. Intersection of Two Arrays.swift
1
736
// using Array(Set(nums1)) to remove duplicates in an Array, 48 ms func intersection(nums1: [Int], _ nums2: [Int]) -> [Int] { var nums1 = Array(Set(nums1)).sort() var nums2 = Array(Set(nums2)).sort() var res = [Int]() var i = 0, j = 0 while i < nums1.count && j < nums2.count { if nums1[i] > nums2[j] { j += 1 }else if nums1[i] < nums2[j] { i += 1 }else { res.append(nums1[i]) i += 1 j += 1 } } return res } // using filter(), 56 ms func intersection(nums1: [Int], _ nums2: [Int]) -> [Int] { let nums1 = Array(Set(nums1)).sort() let nums2 = Set(nums2) return nums1.filter{ num in nums2.contains(num) } }
mit
653966ed387901483850c6875e312338
27.346154
66
0.508152
3.041322
false
false
false
false
wayfindrltd/wayfindr-demo-ios
Wayfindr Demo/Classes/Controller/Maintainer/BatteryLevelsTableViewController.swift
1
8674
// // BatteryLevelsTableViewController.swift // Wayfindr Demo // // Created by Wayfindr on 09/12/2015. // Copyright (c) 2016 Wayfindr (http://www.wayfindr.net) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is furnished // to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit import SVProgressHUD // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. //https://github.com/wayfindrltd/wayfindr-demo-ios/issues/6 // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } /// Filters for `BatteryLevelsTableViewController` enum BatteryLevelFilters { case battery case date case minor var description: String { switch self { case .battery: return WAYStrings.CommonStrings.Battery case .date: return WAYStrings.CommonStrings.DateWord case .minor: return WAYStrings.CommonStrings.Minor } } static let allValues = [minor, date, battery] } /// Displays all the beacons and their respective battery levels. final class BatteryLevelsTableViewController: UITableViewController { // MARK: - Properties /// Reuse identifier for the table cells. fileprivate let reuseIdentifier = "BeaconCell" /// Interface for interacting with beacons. private var interface: BeaconInterface /// Whether the controller is still fetching beacon information. fileprivate var fetchingData = true { didSet { if fetchingData { SVProgressHUD.show() } else { SVProgressHUD.dismiss() } } } /// Beacon data to display in table. Each beacon is represented by a cell. fileprivate var beacons = [WAYBeacon]() /// Header for the `UITableView`. fileprivate let headerView = BatteryLevelsHeaderView() // MARK: - Intiailizers / Deinitializers /** Initializes a `BatteryLevelsTableViewController`. - parameter interface: `BeaconInterface` for getting current beacon battery levels. */ init(interface: BeaconInterface) { self.interface = interface super.init(style: .plain) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() tableView.register(SubtitledDetailTableViewCell.self, forCellReuseIdentifier: reuseIdentifier) tableView.estimatedRowHeight = WAYConstants.WAYSizes.EstimatedCellHeight tableView.rowHeight = UITableView.automaticDimension tableView.tableHeaderView = headerView headerView.frame.size.height = WAYConstants.WAYSizes.EstimatedCellHeight headerView.segmentControl.addTarget(self, action: #selector(BatteryLevelsTableViewController.segmentedControlValueChanged(_:)), for: .valueChanged) title = WAYStrings.CommonStrings.BatteryLevels } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) fetchingData = true tableView.reloadData() interface.delegate = self SVProgressHUD.show() interface.getBeacons(completionHandler: { success, beacons, error in self.fetchingData = false if let myBeacons = beacons, success { self.beacons = myBeacons let filterMode = BatteryLevelFilters.allValues[self.headerView.segmentControl.selectedSegmentIndex] self.sortBeacons(filterMode) } else { self.displayError(title: "", message: WAYStrings.ErrorMessages.UnableBeacons) print(error ?? WAYStrings.ErrorMessages.UnableBeacons) } self.tableView.reloadData() SVProgressHUD.dismiss() }) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) fetchingData = false } // MARK: - UITableViewDatasource override func numberOfSections(in tableView: UITableView) -> Int { return fetchingData ? 0 : 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return beacons.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) if let myCell = cell as? SubtitledDetailTableViewCell { let beacon = beacons[indexPath.row] myCell.mainTextLabel.text = "\(WAYStrings.CommonStrings.Major): \(beacon.major) \(WAYStrings.CommonStrings.Minor): \(beacon.minor)" let subtitleText: String if let lastUpdated = beacon.lastUpdated { subtitleText = "\(WAYStrings.BatteryLevel.Updated): \(DateFormatter.localizedString(from: lastUpdated as Date, dateStyle: .medium, timeStyle: .short))" } else { subtitleText = "\(WAYStrings.BatteryLevel.Updated): \(WAYStrings.CommonStrings.Unknown)" } myCell.subtitleTextLabel.text = subtitleText let rightText: String if let batteryLevel = beacon.batteryLevel { rightText = batteryLevel + "%" } else { rightText = WAYStrings.CommonStrings.Unknown } myCell.rightValueLabel.text = rightText myCell.rightValueLabel.textColor = WAYConstants.WAYColors.Maintainer myCell.selectionStyle = .none myCell.setNeedsLayout() } return cell } // MARK: - Control Actions /** Action for when the filter `UISegmentedControl` value is changed. Changes sorting of beacons in `UITableView`. - parameter sender: `UISegmentedControl` whose value was changed. */ @objc func segmentedControlValueChanged(_ sender: UISegmentedControl) { let filterMode = BatteryLevelFilters.allValues[sender.selectedSegmentIndex] sortBeacons(filterMode) tableView.reloadData() } // MARK: - Convenience /** Sort the `beacons` array based on `sortMethod`. - parameter sortMethod: Method to use for sorting. */ fileprivate func sortBeacons(_ sortMethod: BatteryLevelFilters) { switch sortMethod { case .battery: beacons.sort {Int($0.batteryLevel ?? "-1")! < Int($1.batteryLevel ?? "-1")!} case .date: beacons.sort {$0.lastUpdated?.timeIntervalSince1970 < $1.lastUpdated?.timeIntervalSince1970} case .minor: beacons.sort {$0.minor < $1.minor} } } } extension BatteryLevelsTableViewController: BeaconInterfaceDelegate { func beaconInterface(_ beaconInterface: BeaconInterface, didChangeBeacons beacons: [WAYBeacon]) { self.fetchingData = false self.beacons = beacons let filterMode = BatteryLevelFilters.allValues[self.headerView.segmentControl.selectedSegmentIndex] self.sortBeacons(filterMode) self.tableView.reloadData() } }
mit
7078efff61b57715e017bc9f99c440bc
32.620155
167
0.645146
5.215875
false
false
false
false
sky15179/swift-learn
data-Base-exercises/data-Base-exercises/Sqlite/SwiftSqliteUse.swift
1
30378
// // SwiftSqliteUse.swift // data-Base-exercises // // Created by 王智刚 on 2017/6/12. // Copyright © 2017年 王智刚. All rights reserved. // import Foundation import SQLite class dbUse { func useDB() { /// 连接数据库 let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let db = try? Connection("\(path)/db.sqlite3") //从程序中读取的db文件可以设置为制度数据库 let path2 = Bundle.main.path(forResource: "db", ofType: "sqlite3")! let db2 = try! Connection(path2, readonly: true) //内存数据库,不设置路径 let db3 = try! Connection() // equivalent to `Connection(.inMemory)` let db4 = try! Connection(.temporary)//要创建一个临时的,磁盘支持的数据库,请传递一个空文件名 //每个连接都配有自己的串行队列,用于语句执行,并可以跨线程安全访问。打开事务和保存点的线程将在事务打开时阻止其他线程执行语句。如果您为单个数据库维护多个连接,请考虑设置超时(以秒为单位)和/或忙碌处理程序,每个连接都是一个单独的线程吗?没有像fmdb的直接异步接口吗? db?.busyTimeout = 5 db?.busyHandler({ tries in if tries >= 3 { return false } return true }) //创建表 let users = Table("users") //temporary:是否可创建临时表 ifNotExists:表存在读取缓存 let id = Expression<Int64>("id") let name = Expression<String>("name") // let name = Expression<String?>("name") //可选类型的支持 let email = Expression<String>("email") let age = Expression<String>("age") //临时属性,temp,是否可以创建临时表:用于在数据库中删除和增加列,可读可写的数据数据库 try! db?.run(users.create(ifNotExists: true) { (table) in table.column(id, primaryKey: true) table.column(name) table.column(email,unique:true) table.column(age) //column Constraints 列限制 //列属性: primaryKey:主键 unique:是否可重复 check:判断条件 defaultValue:默认值 collate:校对,进行定义这一行的比较方式 references:联合 //collate: // BINARY(默认),他通过使用C函数--memcmp(),一个字节一个字节的进行比较 // 这种方式很好的适用于西方的语言,如English // NOCASE,是在英语中通过26个ASCII字符进行比较的 // eg.'JERRY'和'Jerry'被认为是一样的 // REVERSE,更多的用于测试! // t.column(id, primaryKey: true) // // "id" INTEGER PRIMARY KEY NOT NULL // // t.column(id, primaryKey: .autoincrement) // // "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL // t.column(email, unique: true) // // "email" TEXT UNIQUE NOT NULL // t.column(email, check: email.like("%@%")) // // "email" TEXT NOT NULL CHECK ("email" LIKE '%@%') // t.column(name, defaultValue: "Anonymous") // // "name" TEXT DEFAULT 'Anonymous' // t.column(email, collate: .nocase) // // "email" TEXT NOT NULL COLLATE "NOCASE" // // t.column(name, collate: .rtrim) // // "name" TEXT COLLATE "RTRIM" // t.column(user_id, references: users, id) // // "user_id" INTEGER REFERENCES "users" ("id") }) //table Constraints:表限制 //primaryKey:主键 unique:是否可重复 check:判断条件 foreignKey:外键 // primaryKey adds a PRIMARY KEY constraint to the table. Unlike the column constraint, above, it supports all SQLite types, ascending and descending orders, and composite (multiple column) keys. // // t.primaryKey(email.asc, name) // // PRIMARY KEY("email" ASC, "name") // unique adds a UNIQUE constraint to the table. Unlike the column constraint, above, it supports composite (multiple column) constraints. // // t.unique(local, domain) // // UNIQUE("local", "domain") // check adds a CHECK constraint to the table in the form of a boolean expression (Expression<Bool>). Boolean expressions can be easily built using filter operators and functions. (See also the check parameter under Column Constraints.) // // t.check(balance >= 0) // // CHECK ("balance" >= 0.0) // foreignKey adds a FOREIGN KEY constraint to the table. Unlike the references constraint, above, it supports all SQLite types, both ON UPDATE and ON DELETE actions, and composite (multiple column) keys. // // t.foreignKey(user_id, references: users, id, delete: .setNull) // FOREIGN KEY("user_id") REFERENCES "users"("id") ON DELETE SET NULL /// 插入操作,返回rowid let insert = users.insert(name <- "大会上", email <- "[email protected]") let rowid = (try! db?.run(insert))! let insert2 = users.insert(name <- "WTF",email <- "[email protected]") let rowid2 = (try! db?.run(insert2))! //更新 let update = users.filter(id == rowid) try! db?.run(update.update(email <- email.replace("126", with: "qq"))) for user in (try! db?.prepare(users.filter(name == "大会上")))! { print("Update:id: \(user[id]), name: \(user[name]), email: \(user[email])") } //删除 try! db?.run(users.filter(id == rowid2).delete()) for user in (try! db?.prepare(users))! { print("Delete:id: \(user[id]), name: \(user[name]), email: \(user[email])") } //setters //表里的属性和值关联,通过,运算符重写的:<- // try db.run(counter.update(count <- 0)) // UPDATE "counters" SET "count" = 0 WHERE ("id" = 1) //其他重载的运算符 // Operator Types // <- Value -> Value // += Number -> Number // -= Number -> Number // *= Number -> Number // /= Number -> Number // %= Int -> Int // <<= Int -> Int // >>= Int -> Int // &= Int -> Int // ` // ^= Int -> Int // += String -> String // Postfix Setters // // Operator Types // ++ Int -> Int // -- Int -> Int //查询操作 //查询操作是懒惰执行的 for user in (try! db?.prepare(users))!{ print("id: \(user[id]), email: \(user[email]), name: \(user[name])") } //获取第一行 if let user = try! db?.pluck(users) { /* ... */ } // Row // SELECT * FROM "users" LIMIT 1 let all = Array((try! db?.prepare(users))!) // SELECT * FROM "users" //查询语句的复合操作 let query = users.select(email) // SELECT "email" FROM "users" // .filter(name != nil) // WHERE "name" IS NOT NULL //fiter为啥不行,重写了 != ,fiter中左右比较必须是同一类型 .order(email.desc, name) // ORDER BY "email" DESC, "name" .limit(5, offset: 1) // LIMIT 5 OFFSET 1 .filter(name != "") //直接使用元组获取指定的列 for user in (try! db?.prepare(users.select(id, email)))! { print("id: \(user[id]), email: \(user[email])") // id: 1, email: [email protected] } // SELECT "id", "email" FROM "users" //sentence封装直接对每列的处理 // let sentence = name + " is " + cast(age) as Expression<String?> + " years old!" // for user in users.select(sentence) { // print(user[sentence]) // // Optional("Alice is 30 years old!") // } // SELECT ((("name" || ' is ') || CAST ("age" AS TEXT)) || ' years old!') FROM "users" //当单表存在多种类型需要复杂的类型判断逻辑时,可以考虑合理的分表来解决 //join,联合查询,联合查询确实有性能优化吗?? //join的几种方式: /* 1.cross join:SELECT ... FROM t1 CROSS JOIN t2 ...叫笛卡尔积,匹配前一个表与后一个表的每一行和每一列,这样得到的结果集为n*m行(n, m分别为每张表的行数),x+y列(x, y分别为每张表的列数)。可见,该结果集可能会成为一个巨大的表,对内存和后续处理都会造成巨大压力,所以,慎用(真没用过) 2.inner join:类似Cross Join,但内建机制限制了返回的结果数量。返回的结果集不会超过x + y列,行数在0- n*m行之间。有3种方法用来指定Inner Join的判断条件: 第一种是On表达式:SELECT ... FROM t1 JOIN t2 ON conditional_expression ...,例如:SELECT ... FROM employee JOIN resource ON employee.eid = resource.eid ...。 但On这种方式有俩个问题:一是语句比较长,二是存在重复列,如俩个eid。因此,可以使用第二种方式Using表达式:SELECT ... FROM t1 JOIN t2 USING ( col1 ,... ) ...,这种Join返回的结果集中没有重复的字段,只是每个字段必须存在于各个表中。 更简洁的方式是,使用第三种方式Natural Join:SQL自动检测各表中每一列是否匹配,这样,即使表结构发生变化,也不用修改SQL语句,可以自动适应变化。 3.Outer Join:SQLite3只支持left outer join,其结果集由不大于x + y列,n - n*m行构成,至少包含左侧表的每一行,对于Join后不存在的字段值,则赋NULL。这样得到的表与我们之前设计那个全集结果一样,但数据结构更清晰,空间占用更少。 */ // users.join(posts, on: user_id == users[id]) // SELECT * FROM "users" INNER JOIN "posts" ON ("user_id" = "users"."id") // let query = users.join(posts, on: user_id == id) // assertion failure: ambiguous column 'id' //表的临时名字 let managers = users.alias("managers") // let query5 = users.join(managers, on: managers[id] == users[managerId]) // SELECT * FROM "users" // INNER JOIN ("users") AS "managers" ON ("managers"."id" = "users"."manager_id") users.where(id == 1) // SELECT * FROM "users" WHERE ("id" = 1) // If query results can have ambiguous column names, row values should be accessed with namespaced column expressions. In the above case, SELECT * immediately namespaces all columns of the result set. // // let user = try db.pluck(query) // user[id] // fatal error: ambiguous column 'id' // // (please disambiguate: ["users"."id", "managers"."id"]) // // user[users[id]] // returns "users"."id" // user[managers[id]] // returns "managers"."id" //where 代替fiter,筛选操作 users.where(id == 1) //fiter重写的运算符 // == Equatable -> Bool =/IS* // != Equatable -> Bool !=/IS NOT* // > Comparable -> Bool > // >= Comparable -> Bool >= // < Comparable -> Bool < // <= Comparable -> Bool <= // ~= (Interval, Comparable) -> Bool BETWEEN // && Bool -> Bool AND // ` ` // Swift Types SQLite // like String -> Bool LIKE // glob String -> Bool GLOB // match String -> Bool MATCH // contains (Array<T>, T) -> Bool IN //排序:order,asc,desc users.order(email, name) //限制:limit users.limit(5) //聚合操作:Aggregation,一些数量关系上得直接处理 // let count = try db.scalar(users.count) // // SELECT count(*) FROM "users" // let count = try db.scalar(users.count) // // SELECT count(*) FROM "users" // Filtered queries will appropriately filter aggregate values. // // let count = try db.scalar(users.filter(name != nil).count) // // SELECT count(*) FROM "users" WHERE "name" IS NOT NULL // count as a computed property on a query (see examples above) returns the total number of rows matching the query. // // count as a computed property on a column expression returns the total number of rows where that column is not NULL. // // let count = try db.scalar(users.select(name.count)) // -> Int // // SELECT count("name") FROM "users" // max takes a comparable column expression and returns the largest value if any exists. // // let max = try db.scalar(users.select(id.max)) // -> Int64? // // SELECT max("id") FROM "users" // min takes a comparable column expression and returns the smallest value if any exists. // // let min = try db.scalar(users.select(id.min)) // -> Int64? // // SELECT min("id") FROM "users" // average takes a numeric column expression and returns the average row value (as a Double) if any exists. // // let average = try db.scalar(users.select(balance.average)) // -> Double? // // SELECT avg("balance") FROM "users" // sum takes a numeric column expression and returns the sum total of all rows if any exist. // // let sum = try db.scalar(users.select(balance.sum)) // -> Double? // // SELECT sum("balance") FROM "users" // total, like sum, takes a numeric column expression and returns the sum total of all rows, but in this case always returns a Double, and returns 0.0 for an empty query. // // let total = try db.scalar(users.select(balance.total)) // -> Double // SELECT total("balance") FROM "users" //update rows:更新rows // hen an unscoped query calls update, it will update every row in the table. // // try db.run(users.update(email <- "[email protected]")) // // UPDATE "users" SET "email" = '[email protected]' // Be sure to scope UPDATE statements beforehand using the filter function. // // let alice = users.filter(id == 1) // try db.run(alice.update(email <- "[email protected]")) // // UPDATE "users" SET "email" = '[email protected]' WHERE ("id" = 1) // The update function returns an Int representing the number of updated rows. // // do { // if try db.run(alice.update(email <- "[email protected]")) > 0 { // print("updated alice") // } else { // print("alice not found") // } // } catch { // print("update failed: \(error)") // } //delete rows:删除rows // We can delete rows from a table by calling a query’s delete function. // // When an unscoped query calls delete, it will delete every row in the table. // // try db.run(users.delete()) // // DELETE FROM "users" // Be sure to scope DELETE statements beforehand using the filter function. // // let alice = users.filter(id == 1) // try db.run(alice.delete()) // // DELETE FROM "users" WHERE ("id" = 1) // The delete function returns an Int representing the number of deleted rows. // // do { // if try db.run(alice.delete()) > 0 { // print("deleted alice") // } else { // print("alice not found") // } // } catch { // print("delete failed: \(error)") // } //Transactions and Savepoints:事物和保存点 使用事务和savepoint函数,我们可以在事务中运行一系列语句。如果单个语句失败或块抛出错误,则更改将回滚 // try db.transaction { // let rowid = try db.run(users.insert(email <- "[email protected]")) // try db.run(users.insert(email <- "[email protected]", managerId <- rowid)) // } //表重命名 // try db.run(users.rename(Table("users_old")) // ALTER TABLE "users" RENAME TO "users_old" //添加列:支持的列操作属性:check,defaulvalue,collate,reference // try db.run(users.addColumn(suffix)) // ALTER TABLE "users" ADD COLUMN "suffix" TEXT //索引操作------------------------------------------------------------重要 //建立索引: try! db?.run(users.createIndex(email)) // The createIndex function has a couple default parameters we can override. // // unique adds a UNIQUE constraint to the index. Default: false. // // try db.run(users.createIndex(email, unique: true)) // // CREATE UNIQUE INDEX "index_users_on_email" ON "users" ("email") // ifNotExists adds an IF NOT EXISTS clause to the CREATE TABLE statement (which will bail out gracefully if the table already exists). Default: false. // // try db.run(users.createIndex(email, ifNotExists: true)) // // CREATE INDEX IF NOT EXISTS "index_users_on_email" ON "users" ("email" //去除索引 // We can build DROP INDEX statements by calling the dropIndex function on a SchemaType. // try! db?.run(users.dropIndex(email)) // // DROP INDEX "index_users_on_email" // The dropIndex function has one additional parameter, ifExists, which (when true) adds an IF EXISTS clause to the statement. // // try db.run(users.dropIndex(email, ifExists: true)) // DROP INDEX IF EXISTS "index_users_on_email" //删除表 try! db?.run(users.drop()) // DROP TABLE "users" try! db?.run(users.drop(ifExists: true)) // DROP TABLE IF EXISTS "users" //版本管理 //设置版本 // extension Connection { // public var userVersion: Int32 { // get { return Int32(try! scalar("PRAGMA user_version") as! Int64)} // set { try! run("PRAGMA user_version = \(newValue)") } // } // } //使用版本 // if db.userVersion == 0 { // // handle first migration // db.userVersion = 1 // } // if db.userVersion == 1 { // // handle second migration // db.userVersion = 2 // } //自定义数据类型入库,遵守Value,实现方法,不支持下标 // extension Date: Value { // class var declaredDatatype: String { // return String.declaredDatatype // } // class func fromDatatypeValue(stringValue: String) -> Date { // return SQLDateFormatter.dateFromString(stringValue)! // } // var datatypeValue: String { // return SQLDateFormatter.stringFromDate(self) // } // } // // let SQLDateFormatter: DateFormatter = { // let formatter = DateFormatter() // formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS" // formatter.locale = Locale(localeIdentifier: "en_US_POSIX") // formatter.timeZone = TimeZone(forSecondsFromGMT: 0) // return formatter // }() //二进制数据的处理 // extension UIImage: Value { // public class var declaredDatatype: String { // return Blob.declaredDatatype // } // public class func fromDatatypeValue(blobValue: Blob) -> UIImage { // return UIImage(data: Data.fromDatatypeValue(blobValue))! // } // public var datatypeValue: Blob { // return UIImagePNGRepresentation(self)!.datatypeValue // } // // } //通过使用命名空间来代替下标方法 // Namespace expressions. Use the namespace function, instead: // // let avatar = Expression<UIImage?>("avatar") // users[avatar] // fails to compile // users.namespace(avatar) // "users"."avatar" //拓展下标方法 // extension Query { // subscript(column: Expression<UIImage>) -> Expression<UIImage> { // return namespace(column) // } // subscript(column: Expression<UIImage?>) -> Expression<UIImage?> { // return namespace(column) // } // } // // extension Row { // subscript(column: Expression<UIImage>) -> UIImage { // return get(column) // } // subscript(column: Expression<UIImage?>) -> UIImage? { // return get(column) // } // } //自定义sql函数 // Many of SQLite’s core functions have been surfaced in and type-audited for SQLite.swift. // // Note: SQLite.swift aliases the ?? operator to the ifnull function. // // name ?? email // ifnull("name", "email") // Aggregate SQLite Functions // // Most of SQLite’s aggregate functions have been surfaced in and type-audited for SQLite.swift. // // Custom SQL Functions // // We can create custom SQL functions by calling createFunction on a database connection. // // For example, to give queries access to MobileCoreServices.UTTypeConformsTo, we can write the following: // // import MobileCoreServices // // let typeConformsTo: (Expression<String>, Expression<String>) -> Expression<Bool> = ( // try db.createFunction("typeConformsTo", deterministic: true) { UTI, conformsToUTI in // return UTTypeConformsTo(UTI, conformsToUTI) // } // ) // Note: The optional deterministic parameter is an optimization that causes the function to be created with SQLITE_DETERMINISTIC. // Note typeConformsTo’s signature: // // (Expression<String>, Expression<String>) -> Expression<Bool> // Because of this, createFunction expects a block with the following signature: // // (String, String) -> Bool // Once assigned, the closure can be called wherever boolean expressions are accepted. // // let attachments = Table("attachments") // let UTI = Expression<String>("UTI") // // let images = attachments.filter(typeConformsTo(UTI, kUTTypeImage)) // // SELECT * FROM "attachments" WHERE "typeConformsTo"("UTI", 'public.image') // Note: The return type of a function must be a core SQL type or conform to Value. // We can create loosely-typed functions by handling an array of raw arguments, instead. // // db.createFunction("typeConformsTo", deterministic: true) { args in // guard let UTI = args[0] as? String, conformsToUTI = args[1] as? String else { return nil } // return UTTypeConformsTo(UTI, conformsToUTI) // } // Creating a loosely-typed function cannot return a closure and instead must be wrapped manually or executed using raw SQL. // // let stmt = try db.prepare("SELECT * FROM attachments WHERE typeConformsTo(UTI, ?)") // for row in stmt.bind(kUTTypeImage) { /* ... */ } //自定义Collations // We can create custom collating sequences by calling createCollation on a database connection. // // try db.createCollation("NODIACRITIC") { lhs, rhs in // return lhs.compare(rhs, options: .diacriticInsensitiveSearch) // } // We can reference a custom collation using the Custom member of the Collation enumeration. // // restaurants.order(collate(.custom("NODIACRITIC"), name)) // SELECT * FROM "restaurants" ORDER BY "name" COLLATE "NODIACRITIC" //使用sqlite的fst4模块实现全文搜索,和like性能相比极大的提升 // We can create a virtual table using the FTS4 module by calling create on a VirtualTable. // // let emails = VirtualTable("emails") // let subject = Expression<String>("subject") // let body = Expression<String>("body") // // try db.run(emails.create(.FTS4(subject, body))) // // CREATE VIRTUAL TABLE "emails" USING fts4("subject", "body") // We can specify a tokenizer using the tokenize parameter. // // try db.run(emails.create(.FTS4([subject, body], tokenize: .Porter))) // // CREATE VIRTUAL TABLE "emails" USING fts4("subject", "body", tokenize=porter) // We can set the full range of parameters by creating a FTS4Config object. // // let emails = VirtualTable("emails") // let subject = Expression<String>("subject") // let body = Expression<String>("body") // let config = FTS4Config() // .column(subject) // .column(body, [.unindexed]) // .languageId("lid") // .order(.desc) // // try db.run(emails.create(.FTS4(config)) // // CREATE VIRTUAL TABLE "emails" USING fts4("subject", "body", notindexed="body", languageid="lid", order="desc") // Once we insert a few rows, we can search using the match function, which takes a table or column as its first argument and a query string as its second. // // try db.run(emails.insert( // subject <- "Just Checking In", // body <- "Hey, I was just wondering...did you get my last email?" // )) // // let wonderfulEmails: QueryType = emails.match("wonder*") // // SELECT * FROM "emails" WHERE "emails" MATCH 'wonder*' // // let replies = emails.filter(subject.match("Re:*")) // // SELECT * FROM "emails" WHERE "subject" MATCH 'Re:*' //FST5 // When linking against a version of SQLite with FTS5 enabled we can create the virtual table in a similar fashion. // // let emails = VirtualTable("emails") // let subject = Expression<String>("subject") // let body = Expression<String>("body") // let config = FTS5Config() // .column(subject) // .column(body, [.unindexed]) // // try db.run(emails.create(.FTS5(config)) // // CREATE VIRTUAL TABLE "emails" USING fts5("subject", "body" UNINDEXED) // // // Note that FTS5 uses a different syntax to select columns, so we need to rewrite // // the last FTS4 query above as: // let replies = emails.filter(emails.match("subject:\"Re:\"*)) // // SELECT * FROM "emails" WHERE "emails" MATCH 'subject:"Re:"*' // // https://www.sqlite.org/fts5.html#_changes_to_select_statements_ //原始sql的执行 // Executing Arbitrary SQL // // Though we recommend you stick with SQLite.swift’s type-safe system whenever possible, it is possible to simply and safely prepare and execute raw SQL statements via a Database connection using the following functions. // // execute runs an arbitrary number of SQL statements as a convenience. // // try db.execute( // "BEGIN TRANSACTION;" + // "CREATE TABLE users (" + // "id INTEGER PRIMARY KEY NOT NULL," + // "email TEXT UNIQUE NOT NULL," + // "name TEXT" + // ");" + // "CREATE TABLE posts (" + // "id INTEGER PRIMARY KEY NOT NULL," + // "title TEXT NOT NULL," + // "body TEXT NOT NULL," + // "published_at DATETIME" + // ");" + // "PRAGMA user_version = 1;" + // "COMMIT TRANSACTION;" // ) // prepare prepares a single Statement object from a SQL string, optionally binds values to it (using the statement’s bind function), and returns the statement for deferred execution. // // let stmt = try db.prepare("INSERT INTO users (email) VALUES (?)") // Once prepared, statements may be executed using run, binding any unbound parameters. // // try stmt.run("[email protected]") // db.changes // -> {Some 1} // Statements with results may be iterated over, using the columnNames if useful. // // let stmt = try db.prepare("SELECT id, email FROM users") // for row in stmt { // for (index, name) in stmt.columnNames.enumerate() { // print ("\(name)=\(row[index]!)") // // id: Optional(1), email: Optional("[email protected]") // } // } // run prepares a single Statement object from a SQL string, optionally binds values to it (using the statement’s bind function), executes, and returns the statement. // // try db.run("INSERT INTO users (email) VALUES (?)", "[email protected]") // scalar prepares a single Statement object from a SQL string, optionally binds values to it (using the statement’s bind function), executes, and returns the first value of the first row. // // let count = try db.scalar("SELECT count(*) FROM users") as! Int64 // Statements also have a scalar function, which can optionally re-bind values at execution. // // let stmt = try db.prepare("SELECT count (*) FROM users") // let count = try stmt.scalar() as! Int64 //sql的打印 #if DEBUG // db?.trace(print) #endif } } //extension Date: Value { // class var declaredDatatype: String { // return String.declaredDatatype // } // class func fromDatatypeValue(stringValue: String) -> Date { // return SQLDateFormatter.dateFromString(stringValue)! // } // var datatypeValue: String { // return SQLDateFormatter.stringFromDate(self) // } //}
apache-2.0
899de780a80491239ed9c5ee13834755
43.092767
243
0.558606
3.836777
false
false
false
false
mono0926/RegexPractice
Carthage/Checkouts/PySwiftyRegex/PySwiftyRegex/PySwiftyRegex.swift
2
21766
// PySwiftyRegex.swift // Copyright (c) 2015 Ce Zheng // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /** * Counterpart of Python's re module, but as a class. */ public class re { // MARK: - re methods /** Compile a regular expression pattern into a RegexObject object, which can be used for matching using its match() and search() methods, described below. See https://docs.python.org/2/library/re.html#re.compile - parameter pattern: regular expression pattern string - parameter flags: NSRegularExpressionOptions value - returns: The created RegexObject object. If the pattern is invalid, RegexObject.isValid is false, and all methods have a default return value. */ public static func compile(pattern: String, flags: RegexObject.Flag = []) -> RegexObject { return RegexObject(pattern: pattern, flags: flags) } /** Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. See https://docs.python.org/2/library/re.html#re.search - parameter pattern: regular expression pattern string - parameter string: string to be searched - parameter flags: NSRegularExpressionOptions value - returns: Corresponding MatchObject instance. Return nil if no position in the string matches the pattern or pattern is invalid; note that this is different from finding a zero-length match at some point in the string. */ public static func search(pattern: String, _ string: String, flags: RegexObject.Flag = []) -> MatchObject? { return re.compile(pattern, flags: flags).search(string) } /** If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding MatchObject instance. See https://docs.python.org/2/library/re.html#re.match - parameter pattern: regular expression pattern string - parameter string: string to be searched - parameter flags: NSRegularExpressionOptions value - returns: Corresponding MatchObject instance. Return nil if the string does not match the pattern or pattern is invalid; note that this is different from a zero-length match. */ public static func match(pattern: String, _ string: String, flags: RegexObject.Flag = []) -> MatchObject? { return re.compile(pattern, flags: flags).match(string) } /** Split string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list. See https://docs.python.org/2/library/re.html#re.split - parameter pattern: regular expression pattern string - parameter string: string to be splitted - parameter maxsplit: maximum number of times to split the string, defaults to 0, meaning no limit is applied - parameter flags: NSRegularExpressionOptions value - returns: Array of splitted strings */ public static func split(pattern: String, _ string: String, _ maxsplit: Int = 0, flags: RegexObject.Flag = []) -> [String?] { return re.compile(pattern, flags: flags).split(string, maxsplit) } /** Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result unless they touch the beginning of another match. See https://docs.python.org/2/library/re.html#re.findall - parameter pattern: regular expression pattern string - parameter string: string to be searched - parameter flags: NSRegularExpressionOptions value - returns: Array of matched substrings */ public static func findall(pattern: String, _ string: String, flags: RegexObject.Flag = []) -> [String] { return re.compile(pattern, flags: flags).findall(string) } /** Return an array of MatchObject instances over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result unless they touch the beginning of another match. See https://docs.python.org/2/library/re.html#re.finditer - parameter pattern: regular expression pattern string - parameter string: string to be searched - parameter flags: NSRegularExpressionOptions value - returns: Array of match results as MatchObject instances */ public static func finditer(pattern: String, _ string: String, flags: RegexObject.Flag = []) -> [MatchObject] { return re.compile(pattern, flags: flags).finditer(string) } /** Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. Different from python, passing a repl as a closure is not supported. See https://docs.python.org/2/library/re.html#re.sub - parameter pattern: regular expression pattern string - parameter repl: replacement string - parameter string: string to be searched and replaced - parameter count: maximum number of times to perform replace operations to the string - parameter flags: NSRegularExpressionOptions value - returns: replaced string */ public static func sub(pattern: String, _ repl: String, _ string: String, _ count: Int = 0, flags: RegexObject.Flag = []) -> String { return re.compile(pattern, flags: flags).sub(repl, string, count) } /** Perform the same operation as sub(), but return a tuple (new_string, number_of_subs_made) as (String, Int) See https://docs.python.org/2/library/re.html#re.subn - parameter pattern: regular expression pattern string - parameter repl: replacement string - parameter string: string to be searched and replaced - parameter count: maximum number of times to perform replace operations to the string - parameter flags: NSRegularExpressionOptions value - returns: a tuple (new_string, number_of_subs_made) as (String, Int) */ public static func subn(pattern: String, _ repl: String, _ string: String, _ count: Int = 0, flags: RegexObject.Flag = []) -> (String, Int) { return re.compile(pattern, flags: flags).subn(repl, string, count) } // MARK: - RegexObject /** * Counterpart of Python's re.RegexObject */ public class RegexObject { /// Typealias for NSRegularExpressionOptions public typealias Flag = NSRegularExpressionOptions /// Whether this object is valid or not public var isValid: Bool { return regex != nil } /// Pattern used to construct this RegexObject public let pattern: String private let regex: NSRegularExpression? /// Underlying NSRegularExpression Object public var nsRegex: NSRegularExpression? { return regex } /// NSRegularExpressionOptions used to contructor this RegexObject public var flags: Flag { return regex?.options ?? [] } /// Number of capturing groups public var groups: Int { return regex?.numberOfCaptureGroups ?? 0 } /** Create A re.RegexObject Instance - parameter pattern: regular expression pattern string - parameter flags: NSRegularExpressionOptions value - returns: The created RegexObject object. If the pattern is invalid, RegexObject.isValid is false, and all methods have a default return value. */ public required init(pattern: String, flags: Flag = []) { self.pattern = pattern do { self.regex = try NSRegularExpression(pattern: pattern, options: flags) } catch let error as NSError { self.regex = nil debugPrint(error) } } /** Scan through string looking for a location where this regular expression produces a match, and return a corresponding MatchObject instance. Return nil if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string. See https://docs.python.org/2/library/re.html#re.RegexObject.search - parameter string: string to be searched - parameter pos: position in string where the search is to start, defaults to 0 - parameter endpos: position in string where the search it to end (non-inclusive), defaults to nil, meaning the end of the string. If endpos is less than pos, no match will be found. - parameter options: NSMatchOptions value - returns: search result as MatchObject instance if a match is found, otherwise return nil */ public func search(string: String, _ pos: Int = 0, _ endpos: Int? = nil, options: NSMatchingOptions = []) -> MatchObject? { guard let regex = regex else { return nil } let start = pos > 0 ?pos :0 let end = endpos ?? string.characters.count let length = max(0, end - start) let range = NSRange(location: start, length: length) if let match = regex.firstMatchInString(string, options: options, range: range) { return MatchObject(string: string, match: match) } return nil } /** If zero or more characters at the beginning of string match this regular expression, return a corresponding MatchObject instance. Return nil if the string does not match the pattern; note that this is different from a zero-length match. See https://docs.python.org/2/library/re.html#re.RegexObject.match - parameter string: string to be matched - parameter pos: position in string where the search is to start, defaults to 0 - parameter endpos: position in string where the search it to end (non-inclusive), defaults to nil, meaning the end of the string. If endpos is less than pos, no match will be found. - returns: match result as MatchObject instance if a match is found, otherwise return nil */ public func match(string: String, _ pos: Int = 0, _ endpos: Int? = nil) -> MatchObject? { return search(string, pos, endpos, options: [.Anchored]) } /** Identical to the re.split() function, using the compiled pattern. See https://docs.python.org/2/library/re.html#re.RegexObject.split - parameter string: string to be splitted - parameter maxsplit: maximum number of times to split the string, defaults to 0, meaning no limit is applied - returns: Array of splitted strings */ public func split(string: String, _ maxsplit: Int = 0) -> [String?] { guard let regex = regex else { return [] } var splitsLeft = maxsplit == 0 ? Int.max : (maxsplit < 0 ? 0 : maxsplit) let range = NSRange(location: 0, length: string.characters.count) var results = [String?]() var start = string.startIndex var end = string.startIndex regex.enumerateMatchesInString(string, options: [], range: range) { result, _, stop in if splitsLeft <= 0 { stop.memory = true return } guard let result = result where result.range.length > 0 else { return } end = string.startIndex.advancedBy(result.range.location) results.append(string[start..<end]) if regex.numberOfCaptureGroups > 0 { results += MatchObject(string: string, match: result).groups() } splitsLeft-- start = end.advancedBy(result.range.length) } if start <= string.endIndex { results.append(string[start..<string.endIndex]) } return results } /** Similar to the re.findall() function, using the compiled pattern, but also accepts optional pos and endpos parameters that limit the search region like for match(). See https://docs.python.org/2/library/re.html#re.RegexObject.findall - parameter string: string to be matched - parameter pos: position in string where the search is to start, defaults to 0 - parameter endpos: position in string where the search it to end (non-inclusive), defaults to nil, meaning the end of the string. If endpos is less than pos, no match will be found. - returns: Array of matched substrings */ public func findall(string: String, _ pos: Int = 0, _ endpos: Int? = nil) -> [String] { return finditer(string, pos, endpos).map { $0.group()! } } /** Similar to the re.finditer() function, using the compiled pattern, but also accepts optional pos and endpos parameters that limit the search region like for match(). https://docs.python.org/2/library/re.html#re.RegexObject.finditer - parameter string: string to be matched - parameter pos: position in string where the search is to start, defaults to 0 - parameter endpos: position in string where the search it to end (non-inclusive), defaults to nil, meaning the end of the string. If endpos is less than pos, no match will be found. - returns: Array of match results as MatchObject instances */ public func finditer(string: String, _ pos: Int = 0, _ endpos: Int? = nil) -> [MatchObject] { guard let regex = regex else { return [] } let start = pos > 0 ?pos :0 let end = endpos ?? string.characters.count let length = max(0, end - start) let range = NSRange(location: start, length: length) return regex.matchesInString(string, options: [], range: range).map { MatchObject(string: string, match: $0) } } /** Identical to the re.sub() function, using the compiled pattern. See https://docs.python.org/2/library/re.html#re.RegexObject.sub - parameter repl: replacement string - parameter string: string to be searched and replaced - parameter count: maximum number of times to perform replace operations to the string - returns: replaced string */ public func sub(repl: String, _ string: String, _ count: Int = 0) -> String { return subn(repl, string, count).0 } /** Identical to the re.subn() function, using the compiled pattern. See https://docs.python.org/2/library/re.html#re.RegexObject.subn - parameter repl: replacement string - parameter string: string to be searched and replaced - parameter count: maximum number of times to perform replace operations to the string - returns: a tuple (new_string, number_of_subs_made) as (String, Int) */ public func subn(repl: String, _ string: String, _ count: Int = 0) -> (String, Int) { guard let regex = regex else { return (string, 0) } let range = NSRange(location: 0, length: string.characters.count) let mutable = NSMutableString(string: string) let maxCount = count == 0 ? Int.max : (count > 0 ? count : 0) var n = 0 var offset = 0 regex.enumerateMatchesInString(string, options: [], range: range) { result, _, stop in if maxCount <= n { stop.memory = true return } if let result = result { n++ let resultRange = NSRange(location: result.range.location + offset, length: result.range.length) let lengthBeforeReplace = mutable.length regex.replaceMatchesInString(mutable, options: [], range: resultRange, withTemplate: repl) offset += mutable.length - lengthBeforeReplace } } return (mutable as String, n) } } // MARK: - MatchObject /** * Counterpart of Python's re.MatchObject */ public final class MatchObject { /// String matched public let string: String /// Underlying NSTextCheckingResult public let match: NSTextCheckingResult init(string: String, match: NSTextCheckingResult) { self.string = string self.match = match } /** Return the string obtained by doing backslash substitution on the template string template, as done by the sub() method. Note that named backreferences in python is not supported here since NSRegularExpression does not have this feature. See https://docs.python.org/2/library/re.html#re.MatchObject.expand - parameter template: regular expression template decribing the expanded format - returns: expanded string */ public func expand(template: String) -> String { guard let regex = match.regularExpression else { return "" } return regex.replacementStringForResult(match, inString: string, offset: 0, template: template) } /** Returns one subgroup of the match. If the group number is negative or larger than the number of groups defined in the pattern, nil returned. If a group is contained in a part of the pattern that did not match, the corresponding result is nil. If a group is contained in a part of the pattern that matched multiple times, the last match is returned. Note that different from python's group function this function does not accept multiple arguments due to ambiguous syntax. If you would like to use multiple arguments pass in an array instead. See https://docs.python.org/2/library/re.html#re.MatchObject.group - parameter index: group index, defaults to 0, meaning the entire matching string - returns: string of the matching group */ public func group(index: Int = 0) -> String? { guard let range = span(index) where range.startIndex < string.endIndex else { return nil } return string[range] } /** Returns one or more subgroups of the match. If a group number is negative or larger than the number of groups defined in the pattern, nil is inserted at the relevant index of the returned array. If a group is contained in a part of the pattern that did not match, the corresponding result is None. If a group is contained in a part of the pattern that matched multiple times, the last match is returned. See https://docs.python.org/2/library/re.html#re.MatchObject.group - parameter indexes: array of group indexes to get - returns: array of strings of the matching groups */ public func group(indexes: [Int]) -> [String?] { return indexes.map { group($0) } } /** Return an array containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The default argument is used for groups that did not participate in the match. Note that python version of this function returns a tuple while this one returns an array due to the fact that swift cannot specify a variadic tuple as return value. See https://docs.python.org/2/library/re.html#re.MatchObject.groups - parameter defaultValue: default value string - returns: array of all matching subgroups as String */ public func groups(defaultValue: String) -> [String] { return (1..<match.numberOfRanges).map { group($0) ?? defaultValue } } /** Return an array containing all the subgroups of the match, from 1 up to however many groups are in the pattern. For groups that did not participate in the match, nil is inserted at the relevant index of the return array. Note that python version of this function returns a tuple while this one returns an array due to the fact that swift cannot specify a variadic tuple as return value. See https://docs.python.org/2/library/re.html#re.MatchObject.groups - returns: array of all matching subgroups as String? (nil when relevant optional capture group is not matched) */ public func groups() -> [String?] { return (1..<match.numberOfRanges).map { group($0) } } /** Return the range of substring matched by group; group defaults to zero (meaning the whole matched substring). Return nil if paremeter is invalid or group exists but did not contribute to the match. See https://docs.python.org/2/library/re.html#re.MatchObject.span - parameter index: group index - returns: range of matching group substring */ public func span(index: Int = 0) -> Range<String.Index>? { if index >= match.numberOfRanges { return nil } let nsrange = match.rangeAtIndex(index) if nsrange.location == NSNotFound { return string.endIndex..<string.endIndex } let startIndex = string.startIndex.advancedBy(nsrange.location) let endIndex = startIndex.advancedBy(nsrange.length) return startIndex..<endIndex } } }
mit
ea2f405281eced670815f14068a4d681
43.146045
407
0.691739
4.469912
false
false
false
false
daaavid/TIY-Assignments
07--Jackpot/jackpot/jackpot/Ticket.swift
1
2219
// // Ticket.swift // jackpot // // Created by david on 10/13/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import Foundation class Ticket { var ticketString = "" var ticketArray = Array<Int>() var winningTicket = Array<Int>() init() { ticketArray = makeTicket() ticketString = formatTicket(ticketArray) } init(arrayFromPicker: Array<Int>) { winningTicket = arrayFromPicker } func makeTicket() -> Array<Int> { var willLoop = true while willLoop == true { ticketArray = [] while ticketArray.count < 6 { let number = Int(1 + arc4random() % 52) ticketArray.append(number) } if checkDuplicateNumbers(ticketArray) == true { willLoop = false return ticketArray } } } func checkDuplicateNumbers(arrayToTest: Array<Int>) -> Bool { let arrayFromSet = Set<Int>(arrayToTest) if arrayToTest.count == arrayFromSet.count { return true } else { return false } } func formatTicket(ticketArray: Array<Int>) -> String { var ticketAsString = "" for number in ticketArray { ticketAsString = ticketAsString + "\(number)" + " " } return ticketAsString } func checkWinningTicket(winningTicketNum: Array<Int>) -> String { var matchingNumbers = 0 var prizeAmount = 0 for x in winningTicketNum { if ticketArray.contains(x) { matchingNumbers += 1 } } if matchingNumbers == 3 { prizeAmount = 1 } if matchingNumbers == 4 { prizeAmount = 5 } if matchingNumbers == 5 { prizeAmount = 20 } if matchingNumbers == 6 { prizeAmount = 100 } return "$ " + String(prizeAmount) } }
cc0-1.0
1d7a0fecba7d89bd2399dff385b9479f
19.728972
67
0.474752
4.790497
false
false
false
false
apple/swift
validation-test/compiler_crashers_fixed/00530-swift-metatypetype-get.swift
65
591
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck class C<D> { init <A: A where A.B == D>(e: A.B) { } static func c<g>() -> (g, g -> g) -> g { d b d.f = { } { g) { i } } i c { } class d: c{ class func f {} struct d<c : f,f where g.i == c.i>
apache-2.0
ea776ad0916d87010dec680b6e21ad67
24.695652
79
0.651438
2.91133
false
false
false
false
taktem/TAKSwiftSupport
TAKSwiftSupport/CoreLocation/LocationManager.swift
1
3400
// // LocationManager.swift // TAKSwiftSupport // // Created by 西村 拓 on 2015/12/13. // Copyright © 2015年 TakuNishimura. All rights reserved. // import UIKit import CoreLocation import RxSwift /// CoreLocation public class LocationManager: NSObject, CLLocationManagerDelegate { /// Singleton Object public static let sharedInstance: LocationManager = LocationManager() /// Rx private let disposeBag = DisposeBag() /// CoreLocation Instance let manager = CLLocationManager() /// Location private let stockLocation: Variable<CLLocation?> = Variable(nil) public let currentLocation: Variable<CLLocation?> = Variable(nil) /// 要求精度 public var verticalAccuracy = 100.0 public var horizontalAccuracy = 100.0 /// Cycle public override init() { super.init() // 初期設定 defaultSetting() } //MARK: - Util private func defaultSetting() { // Delegate manager.delegate = self manager.distanceFilter = kCLDistanceFilterNone manager.desiredAccuracy = kCLLocationAccuracyBest // パーミッション要求 manager.requestWhenInUseAuthorization() } //MARK: - Controller /** ロケーション取得開始 */ public func startUpdatingLocation() { stockLocation.asObservable() .filter({ location -> Bool in return location != nil }) .subscribeNext { [weak self] location -> Void in self?.currentLocation.value = location } .addDisposableTo(disposeBag) manager.startUpdatingLocation() } public func startUpdatingLocationOnce() { stockLocation.asObservable() .filter({ location -> Bool in return location != nil }) .take(1) .subscribeNext { [weak self] location -> Void in self?.currentLocation.value = location self?.stopUpdatingLocation() } .addDisposableTo(disposeBag) manager.startUpdatingLocation() } /** ロケーション取得停止 */ public func stopUpdatingLocation() { manager.stopUpdatingLocation() manager.delegate = nil } //MARK: - Delegate public func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.first else { return } // 精度フィルタ if location.verticalAccuracy > verticalAccuracy || location.horizontalAccuracy > horizontalAccuracy { return } stockLocation.value = location } public func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { } public func locationManager(manager: CLLocationManager, didFinishDeferredUpdatesWithError error: NSError?) { } public func locationManagerDidPauseLocationUpdates(manager: CLLocationManager) { } public func locationManagerDidResumeLocationUpdates(manager: CLLocationManager) { } }
mit
0547be550445967621cea196c85fb537
24.229008
112
0.584569
5.944245
false
false
false
false
kevintavog/WatchThis
Source/WatchThis/ShowListController.swift
1
10532
// // import AppKit import Foundation import RangicCore import Async class ShowListController : NSWindowController, NSWindowDelegate, SlideshowListProviderDelegate { // In Swift 4, 'NSPasteboard.PasteboardType.fileURL' is available, but seems to be OSX 10.13 only - use this as a workaround static let FilenamesPboardType = NSPasteboard.PasteboardType("NSFilenamesPboardType") var slideshowListProvider = SlideshowListProvider() var slideshowControllers = [SlideshowWindowController]() @IBOutlet weak var tabView: NSTabView! @IBOutlet weak var editFilesTabItem: NSTabViewItem! @IBOutlet weak var editFolderTableView: NSTableView! @IBOutlet weak var savedTabItem: NSTabViewItem! @IBOutlet weak var savedTableView: NSTableView! @IBOutlet weak var slideDurationStepper: NSStepper! @IBOutlet weak var slideDurationText: NSTextField! // MARK: initialization override func awakeFromNib() { super.awakeFromNib() slideshowListProvider.delegate = self window!.registerForDraggedTypes([ShowListController.FilenamesPboardType]) updateEditData() Notifications.addObserver(self, selector: #selector(ShowListController.slideshowEnumerationCompleted(_:)), name: Notifications.SlideshowListProvider.EnumerationCompleted, object: nil) Async.background { self.slideshowListProvider.findSavedSlideshows() } } func addKeyboardShorcutToMenu() { if let windowMenu = NSApp.windowsMenu { if let listItem = windowMenu.item(withTitle: "Watch This") { listItem.keyEquivalent = "0" listItem.keyEquivalentModifierMask = NSEvent.ModifierFlags(rawValue: UInt(Int(NSEvent.ModifierFlags.command.rawValue))) } var shortcut = 1 for item in windowMenu.items { if shortcut < 10 { if item.title.range(of: "Slideshow") != nil { item.keyEquivalent = String(shortcut) item.keyEquivalentModifierMask = NSEvent.ModifierFlags(rawValue: UInt(Int(NSEvent.ModifierFlags.command.rawValue))) shortcut += 1 } } } } } // MARK: notifications @objc func slideshowEnumerationCompleted(_ notification: Notification) { Async.main { self.savedTableView.reloadData() } } // MARK: menu handling @IBAction func saveEditFields(_ sender: AnyObject) { let _ = saveSlideshow(slideshowListProvider.editedSlideshow) } @IBAction func clearEditFields(_ sender: AnyObject) { slideshowListProvider.editedSlideshow.reset() updateEditData() } @IBAction func deleteSavedSlideshow(_ sender: AnyObject) { } @IBAction func run(_ sender: AnyObject) { if let selectedSlideshow = getActiveSlideshow() { if selectedSlideshow.folderList.count < 1 && selectedSlideshow.searchQuery == nil { let alert = NSAlert() alert.messageText = "There are no images to show because there are no folders and no search terms in this slideshow." alert.alertStyle = NSAlert.Style.warning alert.addButton(withTitle: "Close") alert.runModal() return } let slideshowController = SlideshowWindowController(windowNibName: "SlideshowWindow") slideshowController.window?.makeKeyAndOrderFront(self) slideshowController.setDataModel(selectedSlideshow, mediaList: MediaList(data: selectedSlideshow)) slideshowControllers.append(slideshowController) addKeyboardShorcutToMenu() } else { let alert = NSAlert() alert.messageText = "Select a slideshow to run." alert.alertStyle = NSAlert.Style.warning alert.addButton(withTitle: "Close") alert.runModal() return } } @IBAction func addFolder(_ sender: AnyObject) { let dialog = NSOpenPanel() dialog.canChooseFiles = false dialog.canChooseDirectories = true dialog.allowsMultipleSelection = true if 1 != dialog.runModal().rawValue || dialog.urls.count < 1 { return } for folderUrl in dialog.urls { slideshowListProvider.editedSlideshow.folderList.append(folderUrl.path) } editFolderTableView.reloadData() } @IBAction func removeFolder(_ sender: AnyObject) { if editFolderTableView.selectedRow >= 0 { var itemsToRemove = Set<String>() for (_, index) in editFolderTableView.selectedRowIndexes.enumerated() { itemsToRemove.insert(slideshowListProvider.editedSlideshow.folderList[index]) } let newFolders = slideshowListProvider.editedSlideshow.folderList.filter( { f in !itemsToRemove.contains(f) }) slideshowListProvider.editedSlideshow.folderList = newFolders editFolderTableView.reloadData() } } @IBAction func slideDurationChanged(_ sender: AnyObject) { slideshowListProvider.editedSlideshow.slideSeconds = slideDurationStepper.doubleValue updateEditData() } func updateEditData() { slideDurationText.doubleValue = slideshowListProvider.editedSlideshow.slideSeconds slideDurationStepper.doubleValue = slideshowListProvider.editedSlideshow.slideSeconds } func getActiveSlideshow() -> SlideshowData? { switch tabView.selectedTabViewItem?.identifier as! String { case "Saved": if savedTableView.selectedRow < 0 { return nil } return slideshowListProvider.savedSlideshows[savedTableView.selectedRow] case "EditFiles": return slideshowListProvider.editedSlideshow case "EditSearch": Logger.error("Not implemented yet...: search tab") return nil default: Logger.error("Unexpected tab identifier: \(String(describing: tabView.selectedTabViewItem?.identifier))") return nil } } // MARK: table view data @objc func numberOfRowsInTableView(_ tv: NSTableView) -> Int { switch tv.tag { case 0: return slideshowListProvider.editedSlideshow.folderList.count case 1: return slideshowListProvider.savedSlideshows.count default: Logger.error("Unknown tag: \(tv.tag)") return 0 } } @objc func tableView(_ tv: NSTableView, objectValueForTableColumn: NSTableColumn?, row: Int) -> String { switch tv.tag { case 0: return slideshowListProvider.editedSlideshow.folderList[row] case 1: return slideshowListProvider.savedSlideshows[row].name ?? "" default: return "" } } func canClose() -> Bool { return slideshowListProvider.canClose() } // MARK: NSWindowDelegate func windowShouldClose(_ sender: NSWindow) -> Bool { return canClose() } // MARK: SlideshowListProviderDelegate func saveSlideshow(_ slideshow: SlideshowData) -> Bool { if slideshow.folderList.count < 1 { let alert = NSAlert() alert.messageText = "Add a folder before saving." alert.alertStyle = NSAlert.Style.warning alert.addButton(withTitle: "Close") alert.runModal() return false } let name = getUniqueNameFromUser() if name == nil { return false } // Come up with a reasonable filename (unique name minus file system characters) slideshow.name = name slideshow.filename = SlideshowData.getFilenameForName(name!) do { try slideshow.save() return true } catch let error { let alert = NSAlert() alert.messageText = "There was an error saving the slideshow: \(error)." alert.alertStyle = NSAlert.Style.warning alert.addButton(withTitle: "Close") alert.runModal() } return false } func wantToSaveEditedSlideshow() -> WtButtonId { let alert = NSAlert() alert.messageText = "Do you want to save changes to the Edited slideshow?" alert.alertStyle = NSAlert.Style.warning alert.addButton(withTitle: "Yes") alert.addButton(withTitle: "No") alert.addButton(withTitle: "Cancel") let response = alert.runModal() switch response { case NSApplication.ModalResponse.alertFirstButtonReturn: return WtButtonId.no default: return WtButtonId.cancel } } func getUniqueNameFromUser() -> String? { let question = NSAlert() question.messageText = "Enter a name for this slideshow" question.alertStyle = NSAlert.Style.informational question.addButton(withTitle: "OK") question.addButton(withTitle: "Cancel") let textField = NSTextField(frame: NSRect(x: 0, y: 0, width: 200, height: 24)) question.accessoryView = textField question.window.initialFirstResponder = textField repeat { let response = question.runModal() if response != NSApplication.ModalResponse.alertFirstButtonReturn { return nil } if textField.stringValue.count == 0 { continue } let name = textField.stringValue.trimmingCharacters(in: CharacterSet.whitespaces) // TODO: Case-insensitive search let matchingNames = slideshowListProvider.savedSlideshows.filter( { s in !(s.filename == slideshowListProvider.editedSlideshow.filename) && !(s.name == name) } ) if matchingNames.count > 0 { let alert = NSAlert() alert.messageText = "The name '\(name)' is already used - choose a unique name." alert.alertStyle = NSAlert.Style.warning alert.addButton(withTitle: "Close") alert.runModal() continue } return name } while true } }
mit
cfb995c24d112821cd442b69aecf998d
31.506173
191
0.617072
5.295123
false
false
false
false
troystribling/BlueCap
Examples/BlueCap/BlueCap/Peripheral/PeripheralManagerServicesCharacteristicValuesViewController.swift
1
5791
// // PeripheralManagerServicesCharacteristicValuesViewController.swift // BlueCap // // Created by Troy Stribling on 8/20/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import UIKit import BlueCapKit import CoreBluetooth class PeripheralManagerServicesCharacteristicValuesViewController : UITableViewController { weak var characteristic: MutableCharacteristic? var peripheralManagerViewController: PeripheralManagerViewController? struct MainStoryboard { static let peripheralManagerServiceCharacteristicEditValueSegue = "PeripheralManagerServiceCharacteristicEditValue" static let peripheralManagerServiceCharacteristicEditDiscreteValuesSegue = "PeripheralManagerServiceCharacteristicEditDiscreteValues" static let peripheralManagerServicesCharacteristicValueCell = "PeripheralManagerServicesCharacteristicValueCell" } required init?(coder aDecoder:NSCoder) { super.init(coder:aDecoder) } override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated:Bool) { super.viewWillAppear(animated) self.tableView.reloadData() guard let characteristic = self.characteristic else { _ = navigationController?.popViewController(animated: true) return } self.navigationItem.title = characteristic.name let future = characteristic.startRespondingToWriteRequests(capacity: 10) future.onSuccess { [weak self, weak characteristic] (args) -> Void in guard let strongSelf = self, let characteristic = characteristic else { return } let (request, _) = args if let value = request.value , value.count > 0 { characteristic.value = request.value characteristic.respondToRequest(request, withResult: CBATTError.success) strongSelf.updateWhenActive() } else { characteristic.respondToRequest(request, withResult :CBATTError.invalidAttributeValueLength) } } NotificationCenter.default.addObserver(self, selector: #selector(PeripheralManagerServicesCharacteristicValuesViewController.didEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.navigationItem.title = "" NotificationCenter.default.removeObserver(self) self.characteristic?.stopRespondingToWriteRequests() } override func prepare(for segue: UIStoryboardSegue, sender: Any!) { if segue.identifier == MainStoryboard.peripheralManagerServiceCharacteristicEditValueSegue { let viewController = segue.destination as! PeripheralManagerServiceCharacteristicEditValueViewController viewController.characteristic = self.characteristic let selectedIndex = sender as! IndexPath if let stringValues = self.characteristic?.stringValue { let values = Array(stringValues.keys) viewController.valueName = values[selectedIndex.row] } if let peripheralManagerViewController = self.peripheralManagerViewController { viewController.peripheralManagerViewController = peripheralManagerViewController } } else if segue.identifier == MainStoryboard.peripheralManagerServiceCharacteristicEditDiscreteValuesSegue { let viewController = segue.destination as! PeripheralManagerServiceCharacteristicEditDiscreteValuesViewController viewController.characteristic = self.characteristic if let peripheralManagerViewController = self.peripheralManagerViewController { viewController.peripheralManagerViewController = peripheralManagerViewController } } } @objc func didEnterBackground() { Logger.debug() if let peripheralManagerViewController = self.peripheralManagerViewController { _ = self.navigationController?.popToViewController(peripheralManagerViewController, animated: false) } } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int { if let values = self.characteristic?.stringValue { return values.count } else { return 0 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: MainStoryboard.peripheralManagerServicesCharacteristicValueCell, for: indexPath) as! CharacteristicValueCell if let values = self.characteristic?.stringValue { let characteristicValueNames = Array(values.keys) let characteristicValues = Array(values.values) cell.valueNameLabel.text = characteristicValueNames[indexPath.row] cell.valueLable.text = characteristicValues[indexPath.row] } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let characteristic = characteristic else { return } if characteristic.stringValues.isEmpty { self.performSegue(withIdentifier: MainStoryboard.peripheralManagerServiceCharacteristicEditValueSegue, sender:indexPath) } else { self.performSegue(withIdentifier: MainStoryboard.peripheralManagerServiceCharacteristicEditDiscreteValuesSegue, sender:indexPath) } } }
mit
00f817368de651d6d055d4c37d4a523c
44.598425
218
0.706614
6.274106
false
false
false
false
cwwise/CWWeChat
CWWeChat/ChatModule/CWChatClient/Bussiness/CWTextMessageDispatchOperation.swift
2
941
// // CWTextMessageDispatchOperation.swift // CWWeChat // // Created by chenwei on 2017/3/30. // Copyright © 2017年 cwcoder. All rights reserved. // import UIKit /// 文字消息直接发送 class CWTextMessageDispatchOperation: CWMessageDispatchOperation { override func sendMessage() { let toId = message.targetId let messageId = message.messageId let textBody = message.messageBody as! CWTextMessageBody let content = textBody.text let _ = self.messageTransmitter.sendMessage(content: content, targetId: toId, messageId: messageId, chatType: message.chatType.rawValue, type: message.messageType.rawValue) } }
mit
15c5f4197952a6f3ccbc2a0d3edabd5d
31.928571
97
0.509761
5.656442
false
false
false
false
nangege/SkinManager
SkinManager/UIColorExtension.swift
1
5295
// // UIColorExtension.swift // HEXColor // // Created by R0CKSTAR on 6/13/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import UIKit /** MissingHashMarkAsPrefix: "Invalid RGB string, missing '#' as prefix" UnableToScanHexValue: "Scan hex error" MismatchedHexStringLength: "Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8" */ public enum UIColorInputError : Error { case missingHashMarkAsPrefix, unableToScanHexValue, mismatchedHexStringLength } extension UIColor { /** The shorthand three-digit hexadecimal representation of color. #RGB defines to the color #RRGGBB. - parameter hex3: Three-digit hexadecimal value. - parameter alpha: 0.0 - 1.0. The default is 1.0. */ public convenience init(hex3: UInt16, alpha: CGFloat = 1) { let divisor = CGFloat(15) let red = CGFloat((hex3 & 0xF00) >> 8) / divisor let green = CGFloat((hex3 & 0x0F0) >> 4) / divisor let blue = CGFloat( hex3 & 0x00F ) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** The shorthand four-digit hexadecimal representation of color with alpha. #RGBA defines to the color #RRGGBBAA. - parameter hex4: Four-digit hexadecimal value. */ public convenience init(hex4: UInt16) { let divisor = CGFloat(15) let red = CGFloat((hex4 & 0xF000) >> 12) / divisor let green = CGFloat((hex4 & 0x0F00) >> 8) / divisor let blue = CGFloat((hex4 & 0x00F0) >> 4) / divisor let alpha = CGFloat( hex4 & 0x000F ) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** The six-digit hexadecimal representation of color of the form #RRGGBB. - parameter hex6: Six-digit hexadecimal value. */ public convenience init(hex6: UInt32, alpha: CGFloat = 1) { let divisor = CGFloat(255) let red = CGFloat((hex6 & 0xFF0000) >> 16) / divisor let green = CGFloat((hex6 & 0x00FF00) >> 8) / divisor let blue = CGFloat( hex6 & 0x0000FF ) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** The six-digit hexadecimal representation of color with alpha of the form #RRGGBBAA. - parameter hex8: Eight-digit hexadecimal value. */ public convenience init(hex8: UInt32) { let divisor = CGFloat(255) let red = CGFloat((hex8 & 0xFF000000) >> 24) / divisor let green = CGFloat((hex8 & 0x00FF0000) >> 16) / divisor let blue = CGFloat((hex8 & 0x0000FF00) >> 8) / divisor let alpha = CGFloat( hex8 & 0x000000FF ) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** The rgba string representation of color with alpha of the form #RRGGBBAA/#RRGGBB, throws error. - parameter rgba: String value. */ public convenience init(rgba_throws rgba: String) throws { guard rgba.hasPrefix("#") else { throw UIColorInputError.missingHashMarkAsPrefix } let hexString: String = String(rgba[rgba.index(rgba.startIndex, offsetBy: 1)...]) var hexValue: UInt32 = 0 guard Scanner(string: hexString).scanHexInt32(&hexValue) else { throw UIColorInputError.unableToScanHexValue } switch (hexString.count) { case 3: self.init(hex3: UInt16(hexValue)) case 4: self.init(hex4: UInt16(hexValue)) case 6: self.init(hex6: hexValue) case 8: self.init(hex8: hexValue) default: throw UIColorInputError.mismatchedHexStringLength } } /** The rgba string representation of color with alpha of the form #RRGGBBAA/#RRGGBB, fails to default color. - parameter rgba: String value. */ public convenience init(_ rgba: String, defaultColor: UIColor = UIColor.clear) { guard let color = try? UIColor(rgba_throws: rgba) else { self.init(cgColor: defaultColor.cgColor) return } self.init(cgColor: color.cgColor) } /** Hex string of a UIColor instance. - parameter includeAlpha: Whether the alpha should be included. */ public func hexString(_ includeAlpha: Bool = true) -> String { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 self.getRed(&r, green: &g, blue: &b, alpha: &a) if (includeAlpha) { return String(format: "#%02X%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255), Int(a * 255)) } else { return String(format: "#%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255)) } } } extension String { /** Convert argb string to rgba string. */ public var argb2rgba: String? { guard self.hasPrefix("#") else { return nil } let hexString: String = String(self[self.index(self.startIndex, offsetBy: 1)...]) switch hexString.count { case 4: return "#\(String(hexString[self.index(self.startIndex, offsetBy: 1)...]))\(String(hexString[..<self.index(self.startIndex, offsetBy: 1)]))" case 8: return "#\(String(hexString[self.index(self.startIndex, offsetBy: 2)...]))\(String(hexString[..<self.index(self.startIndex, offsetBy: 2)]))" default: return nil } } }
mit
a0b517eedd5e2fd1f139261466c0d2f8
31.484663
146
0.626251
3.739407
false
false
false
false
per-dalsgaard/20-apps-in-20-weeks
App 16 - Devslopes Social/Devslopes Social/FeedViewController.swift
1
4804
// // FeedViewController.swift // Devslopes Social // // Created by Per Kristensen on 25/04/2017. // Copyright © 2017 Per Dalsgaard. All rights reserved. // import UIKit import Firebase class FeedViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var postImageButton: RoundButton! @IBOutlet weak var captionTextField: UITextField! var posts = [Post]() var imagePicker: UIImagePickerController! static var imageCache: NSCache<NSString, UIImage> = NSCache() override func viewDidLoad() { super.viewDidLoad() imagePicker = UIImagePickerController() imagePicker.allowsEditing = true imagePicker.delegate = self tableView.dataSource = self tableView.delegate = self DataSerice.ds.REF_POSTS.observe(.value, with: { (snapshot) in self.posts = [] if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] { for snap in snapshot { if let postDataDict = snap.value as? Dictionary<String, AnyObject> { let postId = snap.key let post = Post(postId: postId, postData: postDataDict) self.posts.insert(post, at: 0) } } } self.tableView.reloadData() }) } // MARK: - UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return posts.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "PostTableViewCell", for: indexPath) as? PostTableViewCell { let post = posts[indexPath.row] let image = FeedViewController.imageCache.object(forKey: post.imageUrl as NSString) cell.configureCell(post: posts[indexPath.row], postImage: image) return cell } return PostTableViewCell() } // MARK: - UITableViewDataSource func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("didSelectRowAtIndexPath") } // MARK: - UIImagePickerControllerDelegate func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let image = info[UIImagePickerControllerEditedImage] as? UIImage { postImageButton.setImage(image, for: .normal) } imagePicker.dismiss(animated: true, completion: nil) } // MARK: - IBActions @IBAction func addImageButtonPressed(_ sender: UIButton) { present(imagePicker, animated: true, completion: nil) } @IBAction func postButtonPressed(_ sender: UIButton) { guard let caption = captionTextField.text , caption != "" else { print("Caption must be entered") return } guard let postImage = postImageButton.image(for: .normal) , postImageButton.currentImage != UIImage(named: "add-image") else { print("An image must be selected") return } if let postImageData = UIImageJPEGRepresentation(postImage, 0.2) { let imageUid = NSUUID().uuidString let metadata = FIRStorageMetadata() metadata.contentType = "image/jpeg" DataSerice.ds.REF_POST_IMAGES.child(imageUid).put(postImageData, metadata: metadata, completion: { (metadata, error) in if error != nil { print("Unable to upload image to Firebase storage") } else { print("Successfully uploaded image") let postImageUrl = metadata?.downloadURL()?.absoluteString self.addPostToFirebase(postImageUrl: postImageUrl!) } }) } } // MARK: - Miscellaneous func addPostToFirebase(postImageUrl: String) { let postData: Dictionary<String, AnyObject> = [ "caption": captionTextField.text as AnyObject, "imageUrl": postImageUrl as AnyObject, "likes": 0 as AnyObject ] let firebasePost = DataSerice.ds.REF_POSTS.childByAutoId() firebasePost.setValue(postData) postImageButton.setImage(UIImage(named:"add-image"), for: .normal) captionTextField.text = "" } }
mit
5ab896aaad2998144399e053945a08e9
35.386364
153
0.611285
5.378499
false
false
false
false
wwq0327/iOS9Example
CollectionDemo/CollectionDemo/CustomLayout.swift
1
3966
// // CustomLayout.swift // CollectionDemo // // Created by wyatt on 15/12/27. // Copyright © 2015年 Wanqing Wang. All rights reserved. // import UIKit let screenBounds = UIScreen.mainScreen().bounds // cell 的宽度与高度设置 let itemWidth = screenBounds.width - 120.0 let itemHeith = screenBounds.height - 100.0 class CustomLayout: UICollectionViewFlowLayout { override init() { super.init() // cell item 尺寸 self.itemSize = CGSizeMake(itemWidth, itemHeith) // 水平滚动 self.scrollDirection = .Horizontal // cell 间距 self.minimumLineSpacing = 20.0 } required init?(coder aDecoder: NSCoder) { // fatalError("init(coder:) has not been implemented") super.init(coder: aDecoder) } // 对布局的一些准备工作放在这里 override func prepareLayout() { super.prepareLayout() // 设置边距,让第一张图片和最后一张图片出现在中间位置 let inset = (self.collectionView?.bounds.width ?? 0) * 0.5 - self.itemSize.width * 0.5 self.sectionInset = UIEdgeInsetsMake(0, inset, 0, inset) } // 允许CollectionView Bounds 显示的边界发生变化,重新进行布局,默认是false override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { return true } // 获取CollectionView的所有Item项,进行相应的处理(移动过程中,控制各个Item的缩放比例) // 用来计算rect这个范围内所有的cell的UICollectionViewLayoutAttributes,并返回 override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let array = super.layoutAttributesForElementsInRect(rect) // 可见矩形 var visibleRect = CGRect() visibleRect.origin = self.collectionView!.contentOffset visibleRect.size = self.collectionView!.frame.size // 获得collectionVIew中央的X值(即显示在屏幕中央的X) let collectionViewCenterX = self.collectionView!.contentOffset.x + self.collectionView!.frame.size.width / 2 for attrs in array! { //如果不在屏幕上,直接跳过 if !CGRectIntersectsRect(visibleRect, attrs.frame) { continue } let scale = 1 + 0.05 * ( 1 - abs(attrs.center.x - collectionViewCenterX) / (self.collectionView!.frame.size.width * 0.5)) attrs.transform = CGAffineTransformMakeScale(scale, scale) } return array } /* 当UICollectionView停止那一刻ContentOffset的值(控制UICollectionView停止时,有一个Item一定居中显示) proposedContentOffset默认的值是CotentOffset - parameter proposedContentOffset: 原本collectionView停止滚动那一刻的位置 - parameter velocity: 滚动速度 - returns: 最终停留的位置 */ override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { let lastRect = CGRectMake(proposedContentOffset.x, proposedContentOffset.y, self.collectionView!.frame.width, self.collectionView!.frame.height) //获得collectionVIew中央的X值(即显示在屏幕中央的X) let centerX = proposedContentOffset.x + self.collectionView!.frame.width * 0.5; //这个范围内所有的属性 let array = self.layoutAttributesForElementsInRect(lastRect) //需要移动的距离 var adjustOffsetX = CGFloat(MAXFLOAT); for attri in array! { if abs(attri.center.x - centerX) < abs(adjustOffsetX) { adjustOffsetX = attri.center.x - centerX; } } return CGPointMake(proposedContentOffset.x + adjustOffsetX, proposedContentOffset.y) } }
apache-2.0
5e0c63468ca5d449dcc03d655e0a3c35
35.260417
152
0.661591
4.445722
false
false
false
false
maxep/DiscogsAPI
Example-swift/DGSearchViewController.swift
2
5732
// DGSearchViewController.swift // // Copyright (c) 2017 Maxime Epain // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import DiscogsAPI class DGSearchViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate { var searchController : UISearchController! fileprivate var response: DGSearchResponse! { didSet { tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() navigationController!.navigationBar.barStyle = UIBarStyle.black searchController = UISearchController(searchResultsController: nil) searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false definesPresentationContext = true tableView.tableHeaderView = searchController.searchBar searchController.searchBar.scopeButtonTitles = ["All", "Release", "Master", "Artist", "Label"] searchController.searchBar.delegate = self let callback = URL(string: "discogs-swift://success")! Discogs.api.authentication.authenticate(withCallback: callback, success: { (identity) in print("Authenticated user: \(identity)") }) { (error) in print(error) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let indexPath = tableView.indexPathForSelectedRow, let destination = segue.destination as? DGViewController { destination.objectID = response.results[indexPath.row].id } } // MARK: UISearchResultsUpdating func updateSearchResults(for searchController: UISearchController) { if let query = searchController.searchBar.text as String?, !query.isEmpty { let type = ["", "release", "master", "artist", "label"][searchController.searchBar.selectedScopeButtonIndex] // Search on Discogs let request = DGSearchRequest() request.query = query request.type = type request.pagination.perPage = 25 Discogs.api.database.search(request, success: { (response) in self.response = response }) { (error) in print(error) } } } // MARK: UISearchBarDelegate func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { updateSearchResults(for: searchController) } // MARK: UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return response?.results.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let result = response.results[indexPath.row] let cell = dequeueReusableCellWithResult(result) cell.textLabel?.text = result.title cell.detailTextLabel?.text = result.type // Get a Discogs image if let thumb = result.thumb { Discogs.api.resource.get(image: thumb, success: { (image) in cell.imageView?.image = image }) } // Load the next response page if result === response.results.last { response.loadNextPage(success: { self.tableView.reloadData() }) } return cell } func dequeueReusableCellWithResult(_ result : DGSearchResult) -> UITableViewCell { guard let type = result.type else { return UITableViewCell() } let cell : UITableViewCell switch type { case "artist": cell = tableView.dequeueReusableCell(withIdentifier: "ArtistCell")! cell.imageView?.image = UIImage(named: "default-artist") case "label": cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell")! cell.imageView?.image = UIImage(named: "default-label") case "master": cell = tableView.dequeueReusableCell(withIdentifier: "MasterCell")! cell.imageView?.image = UIImage(named: "default-release") default: cell = tableView.dequeueReusableCell(withIdentifier: "ReleaseCell")! cell.imageView?.image = UIImage(named: "default-release") } return cell } }
mit
12514879ba0c25f9184ea25082696ffa
36.464052
120
0.64672
5.464252
false
false
false
false
dclelland/AudioKit
AudioKit/Common/Nodes/Effects/Envelopes/Tremolo/AKTremolo.swift
1
3917
// // AKTremolo.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// Table-lookup tremolo with linear interpolation /// /// - parameter input: Input node to process /// - parameter frequency: Frequency (Hz) /// public class AKTremolo: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKTremoloAudioUnit? internal var token: AUParameterObserverToken? private var waveform: AKTable? private var frequencyParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// Frequency (Hz) public var frequency: Double = 10 { willSet { if frequency != newValue { if internalAU!.isSetUp() { frequencyParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.frequency = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize this tremolo node /// /// - parameter input: Input node to process /// - parameter frequency: Frequency (Hz) /// - parameter waveform: Shape of the tremolo (default to sine) /// public init( _ input: AKNode, frequency: Double = 10, waveform: AKTable = AKTable(.PositiveSine)) { self.waveform = waveform self.frequency = frequency var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = 0x7472656d /*'trem'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKTremoloAudioUnit.self, asComponentDescription: description, name: "Local AKTremolo", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKTremoloAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) self.internalAU?.setupWaveform(Int32(waveform.size)) for i in 0 ..< waveform.size { self.internalAU?.setWaveformValue(waveform.values[i], atIndex: UInt32(i)) } } guard let tree = internalAU?.parameterTree else { return } frequencyParameter = tree.valueForKey("frequency") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.frequencyParameter!.address { self.frequency = Double(value) } } } internalAU?.frequency = Float(frequency) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
mit
9c63fba04191ea1edc7484534f531bb3
29.84252
89
0.605565
5.188079
false
false
false
false
russelhampton05/MenMew
App Prototypes/Menu_Server_App_Prototype_001/Menu_Server_App_Prototype_001/MessagePopupViewController.swift
1
5212
// // MessagePopupViewController.swift // App_Prototype_Alpha_001 // // Created by Jon Calanio on 11/12/16. // Copyright © 2016 Jon Calanio. All rights reserved. // import UIKit class MessagePopupViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { //IBOutlets @IBOutlet var requestLabel: UILabel! @IBOutlet var messageTableView: UITableView! @IBOutlet var confirmButton: UIButton! @IBOutlet var cancelButton: UIButton! @IBOutlet var popupView: UIView! //Variables var messages: [String] = [] var selectedMessage: String? var didCancel: Bool = false override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.black.withAlphaComponent(0.6) self.showAnimate() loadMessages() messageTableView.delegate = self messageTableView.dataSource = self loadTheme() } @IBAction func confirmButtonPressed(_ sender: Any) { removeAnimate() } @IBAction func cancelButtonPressed(_ sender: Any) { didCancel = true removeAnimate() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messages.count } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MessageCell") as UITableViewCell! cell?.textLabel!.text = messages[indexPath.row] cell?.backgroundColor = currentTheme!.primary! cell?.textLabel!.textColor = currentTheme!.highlight! let bgView = UIView() bgView.backgroundColor = currentTheme!.highlight! cell?.selectedBackgroundView = bgView cell?.textLabel?.highlightedTextColor = currentTheme!.primary! cell?.detailTextLabel?.highlightedTextColor = currentTheme!.primary! return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedMessage = messages[indexPath.row] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Popup view animation func showAnimate() { self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3) self.view.alpha = 0.0 UIView.animate(withDuration: 0.25, animations: { self.view.alpha = 1.0 self.view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) }) } //Popup remove animation func removeAnimate() { UIView.animate(withDuration: 0.25, animations: { self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3) self.view.alpha = 0.0 }, completion:{(finished : Bool) in if (finished) { if !self.didCancel { self.processMessage() } if let parent = self.parent as? TableDetailViewController { parent.tableView.isScrollEnabled = true } self.view.removeFromSuperview() } }) } func processMessage() { if let parent = self.parent as? TableDetailViewController { if selectedMessage != nil { if selectedMessage == "Order Ready" { selectedMessage = "Order placed for ticket \(currentTicket!.desc!) is ready." } else if selectedMessage == "Order Delayed" { selectedMessage = "One or more items for order \(currentTicket!.desc!) is experiencing a delay." } else if selectedMessage == "Item/s Unavailable" { selectedMessage = "We apologize, but one or more items for order \(currentTicket!.desc!) is unavailable." } parent.sendMessage(message: selectedMessage!) } } } func loadMessages() { self.messages.append("Order Ready") self.messages.append("Order Delayed") self.messages.append("Item/s Unavailable") } func loadTheme() { //Background and Tint view.tintColor = currentTheme!.highlight! popupView.backgroundColor = currentTheme!.primary! messageTableView.backgroundColor = currentTheme!.primary! messageTableView.sectionIndexBackgroundColor = currentTheme!.primary! //Labels requestLabel.textColor = currentTheme!.highlight! //Buttons confirmButton.backgroundColor = currentTheme!.highlight! confirmButton.setTitleColor(currentTheme!.primary!, for: .normal) cancelButton.backgroundColor = currentTheme!.highlight! cancelButton.setTitleColor(currentTheme!.primary!, for: .normal) } }
mit
5dff8e8750c81d35b99a6d6b8b8c3db3
31.36646
125
0.596239
5.549521
false
false
false
false
HLoveMe/HSomeFunctions-swift-
HScrollView/HScrollView/HScrollView/view/UIView+Extension.swift
1
3354
// // UIView+Extension.swift // HScrollView // // Created by 朱子豪 on 16/3/8. // Copyright © 2016年 朱子豪. All rights reserved. // import UIKit extension UIView{ /**size*/ var size:CGSize { get{ return self.frame.size } set{ var rect:CGRect = self.frame rect.size = newValue self.frame = rect } } /**width*/ var width:CGFloat { get{ return self.bounds.size.width } set{ self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, newValue, self.frame.size.height) } } /**height*/ var height:CGFloat { get{ return self.bounds.size.height } set{ self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y,self.frame.size.width,newValue) } } /**center*/ var centerH:CGPoint{ get{ return self.center } set{ self.frame = CGRectMake(newValue.x - self.width * 0.5, newValue.y - self.height * 0.5 ,self.width,self.height) } } /**origin*/ var origin:CGPoint{ get{ return self.frame.origin } set{ var rect:CGRect = self.frame rect.origin = newValue self.frame = rect } } /** x */ var x:CGFloat{ get{ return self.origin.x } set{ var rect:CGRect = self.frame rect.origin = CGPointMake(newValue, rect.origin.y) self.frame = rect } } /** y */ var y:CGFloat{ get{ return self.origin.y } set{ var rect:CGRect = self.frame rect.origin = CGPointMake(rect.origin.x,newValue) self.frame = rect } } /**MaxX*/ var MaxX:CGFloat { get{ return CGRectGetMaxX(self.frame) } set{ var rect:CGRect = self.frame rect.origin = CGPointMake(newValue - self.width, rect.origin.y) self.frame = rect } } /**MaxY*/ var MaxY:CGFloat{ get{ return CGRectGetMaxY(self.frame) } set{ var rect:CGRect = self.frame rect.origin = CGPointMake(rect.origin.x,newValue - self.height) self.frame = rect } } /**下标*/ subscript(des:String) ->CGFloat{ get{ let str = des.lowercaseString switch str{ case "x": return self.x case "y": return self.y case "w","wid","width","宽": return self.width case "h","hei","height","高": return self.height default: return 0 } } set{ let str = des.lowercaseString switch str{ case "x": self.x = newValue case "y": self.y = newValue case "w","wid","width","宽": self.width = newValue case "h","hei","height","高": self.height = newValue default: break } } } }
apache-2.0
3e7405748da90f4f785e10c0ff9a5841
22.429577
122
0.450255
4.27635
false
false
false
false
ATFinke-Productions/Steppy-2
Extensions/StepCount/STPYStepTableViewController.swift
1
4033
// // STPYStepTableViewController.swift // StepCount // // Created by Andrew Finke on 12/25/14. // Copyright (c) 2014 Andrew Finke. All rights reserved. // import UIKit import NotificationCenter class STPYStepTableViewController: UITableViewController, NCWidgetProviding { let today = NSLocalizedString("Leaderboards Today Text", comment: "") let week = NSLocalizedString("Leaderboards Week Text", comment: "") let total = NSLocalizedString("Leaderboards Total Text", comment: "") var data = [String:Int]() let motionHelper = STPYCMHelper() //MARK: Loading override func viewDidLoad() { super.viewDidLoad() preferredContentSize = CGSizeMake(0, 132.0) tableView.backgroundColor = UIColor.clearColor() let defaults = NSUserDefaults(suiteName: "group.com.atfinkeproductions.SwiftSteppy") let todaySteps = defaults?.integerForKey("T-Steps") let weekSteps = defaults?.integerForKey("W-Steps") let totalSteps = defaults?.integerForKey("A-Steps") data[self.today] = todaySteps data[self.week] = weekSteps data[self.total] = totalSteps tableView.reloadData() motionHelper.pedometerDataForToday { (steps, distance, date) -> Void in let maxSteps = max(steps, todaySteps!) self.data[self.today] = maxSteps self.tableView.reloadData() } motionHelper.pedometerDataForThisWeek { (steps, distance) -> Void in let maxSteps = max(steps, weekSteps!) self.data[self.week] = maxSteps self.tableView.reloadData() } motionHelper.pedometerDataForAllTime { (steps, distance) -> Void in let maxSteps = max(steps, totalSteps!) self.data[self.total] = maxSteps self.tableView.reloadData() } // Do any additional setup after loading the view from its nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: Table View override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell switch indexPath.row { case 0: cell.textLabel?.text = today cell.detailTextLabel?.text = STPYFormatter.sharedInstance.stringForSteps(data[today]! as NSNumber) case 1: cell.textLabel?.text = week cell.detailTextLabel?.text = STPYFormatter.sharedInstance.stringForSteps(data[week]! as NSNumber) default: cell.textLabel?.text = total cell.detailTextLabel?.text = STPYFormatter.sharedInstance.stringForSteps(data[total]! as NSNumber) } return cell } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { extensionContext?.openURL(NSURL(string: "Steppy2://")!, completionHandler: nil) } //MARK: Widget Functions func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) { completionHandler(.NewData) } func widgetMarginInsetsForProposedMarginInsets(defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets { return UIEdgeInsets(top: 0, left: 28, bottom: 39, right: 0) } override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { extensionContext?.openURL(NSURL(string: "Steppy2://")!, completionHandler: nil) super.touchesEnded(touches as Set<NSObject>, withEvent: event) } }
mit
3e37f47a1a49a8481a91c3570aeaf759
36.342593
118
0.657823
5.079345
false
false
false
false
asp2insp/CodePathFinalProject
Pretto/Invitation.swift
1
9848
// // Invitation.swift // Pretto // // Created by Josiah Gaskin on 6/14/15. // Copyright (c) 2015 Pretto. All rights reserved. // import Foundation import Photos private let kClassName = "Invitation" class Invitation : PFObject, PFSubclassing { var isUpdating : Bool = false override class func initialize() { struct Static { static var onceToken : dispatch_once_t = 0; } dispatch_once(&Static.onceToken) { self.registerSubclass() } } static func parseClassName() -> String { return kClassName } @NSManaged var event : Event @NSManaged var from : PFUser @NSManaged var to : PFUser var paused: Bool { get { return self["paused"] as! Bool } set { self["paused"] = newValue self.lastUpdated = NSDate() } } var accepted: Bool { get { return self["accepted"] as! Bool } set { self["accepted"] = newValue } } @NSManaged var lastUpdated : NSDate? var shouldUploadPhotos : Bool { return accepted && !paused } // Get all photos from the camera roll past self.lastUpdated and add them to the event func updateFromCameraRoll() { if self.isUpdating { return } if !self.accepted || self.paused { lastUpdated = NSDate() return } self.isUpdating = true let fetchOptions = PHFetchOptions() fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] let startDate = self.lastUpdated ?? event.startDate lastUpdated = NSDate() fetchOptions.predicate = NSPredicate(format: "creationDate > %@ AND creationDate < %@", startDate, event.endDate) PHPhotoLibrary.requestAuthorization(nil) let allResult = PHAsset.fetchAssetsWithMediaType(.Image, options: fetchOptions) let requestOptions = PHImageRequestOptions() requestOptions.deliveryMode = PHImageRequestOptionsDeliveryMode.HighQualityFormat requestOptions.resizeMode = PHImageRequestOptionsResizeMode.Fast requestOptions.version = PHImageRequestOptionsVersion.Current requestOptions.synchronous = true let requestManager = PHImageManager.defaultManager() println("Adding \(allResult.count) photos to \(event.title)") dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { for var i = 0; i < allResult.count; i++ { let currentAsset = allResult[i] as! PHAsset var targetScaleRatio = CGFloat(Double(1248.0 / Double(currentAsset.pixelWidth))) println("Scale: \(targetScaleRatio)") var targetWidth = CGFloat(currentAsset.pixelWidth) * targetScaleRatio var targetHeight = CGFloat(currentAsset.pixelHeight) * targetScaleRatio let targetSize = CGSize(width: targetWidth, height: targetHeight) println("Width from \(currentAsset.pixelWidth) to \(targetWidth)") println("Height from \(currentAsset.pixelHeight) to \(targetHeight)") let targetRect = CGRect(origin: CGPoint(x: 0, y: 0), size: targetSize) requestManager.requestImageForAsset(currentAsset, targetSize: targetSize, contentMode: PHImageContentMode.AspectFit, options: requestOptions, resultHandler: { (assetResult, info) -> Void in UIGraphicsBeginImageContext(targetRect.size) assetResult.drawInRect(targetRect) let finalImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let data = UIImageJPEGRepresentation(finalImage, 0.0) println("Image Size = \(data.length)") if data == nil { return } let thumbFile = PFFile(data: data) thumbFile.saveInBackground() let image = Photo() image.thumbnailFile = thumbFile image.owner = PFUser.currentUser()! image.localPath = currentAsset.localIdentifier image.saveInBackgroundWithBlock({ (success, err) -> Void in NSNotificationCenter.defaultCenter().postNotificationName(kNewPhotoForEventNotification, object: self.event) self.event.addImageToEvent(image) self.event.saveInBackgroundWithBlock({ (success:Bool, erro:NSError?) -> Void in let push = PFPush() push.setChannel(self.event.channel!) let myString = "New content available!" let data = ["alert" : myString, "badge" : "Increment", "sound" : "" ] push.setData(data) push.sendPushInBackground() self.saveInBackground() }) }) }) } self.saveInBackground() self.isUpdating = false } } // Query for all live events in the background and call the given block with the result // Only returns live events where you have accepted the invitation class func getAllLiveEvents(block: ([Invitation] -> Void) ) { let query = PFQuery(className: "Invitation", predicate: nil) query.includeKey("event") let innerQuery = PFQuery(className: "Event", predicate: nil) innerQuery.whereKey(kEventStartDateKey, lessThanOrEqualTo: NSDate()) innerQuery.whereKey(kEventEndDateKey, greaterThan: NSDate()) query.whereKey("event", matchesQuery: innerQuery) query.whereKey("to", equalTo: PFUser.currentUser()!) query.whereKey("accepted", equalTo: true) query.includeKey("event") query.orderByDescending("createdAt") query.findObjectsInBackgroundWithBlock { (items, error) -> Void in if error == nil { var invites : [Invitation] = [] for obj in items ?? [] { if let invitation = obj as? Invitation { invites.append(invitation) } } block(invites) } } } // Query for all past events in the background and call the given block with the result class func getAllPastEvents(block: ([Invitation] -> Void) ) { let query = PFQuery(className: "Invitation", predicate: nil) query.includeKey("event") let innerQuery = PFQuery(className: "Event", predicate: nil) innerQuery.whereKey(kEventEndDateKey, lessThan: NSDate()) query.whereKey("event", matchesQuery: innerQuery) query.whereKey("to", equalTo: PFUser.currentUser()!) query.includeKey("event") query.whereKey("accepted", equalTo: true) query.orderByDescending("createdAt") query.findObjectsInBackgroundWithBlock { (items, error) -> Void in if error == nil { var invites : [Invitation] = [] for obj in items ?? [] { if let invitation = obj as? Invitation { invites.append(invitation) } } block(invites) } } } // Query for all future events (ongoing, and yet to come, that aren't accepted) // in the background and call the given block with the result class func getAllLiveAndFutureNonAcceptedEvents(block: ([Invitation] -> Void) ) { let query = PFQuery(className: "Invitation", predicate: nil) query.includeKey("event") let innerQuery = PFQuery(className: "Event", predicate: nil) innerQuery.whereKey(kEventEndDateKey, greaterThanOrEqualTo: NSDate()) query.whereKey("event", matchesQuery: innerQuery) query.whereKey("to", equalTo: PFUser.currentUser()!) query.whereKey("accepted", equalTo: false) query.includeKey("event") query.orderByDescending("createdAt") query.findObjectsInBackgroundWithBlock { (items, error) -> Void in if error == nil { var invites : [Invitation] = [] for obj in items ?? [] { if let invitation = obj as? Invitation { invites.append(invitation) } } block(invites) } } } // Query for all future events (only Accepted) // in the background and call the given block with the result class func getAllFutureEvents(block: ([Invitation] -> Void) ) { let query = PFQuery(className: "Invitation", predicate: nil) query.includeKey("event") let innerQuery = PFQuery(className: "Event", predicate: nil) innerQuery.whereKey(kEventStartDateKey, greaterThan: NSDate()) query.whereKey("event", matchesQuery: innerQuery) query.whereKey("to", equalTo: PFUser.currentUser()!) query.whereKey("accepted", equalTo: true) query.includeKey("event") query.orderByDescending("createdAt") query.findObjectsInBackgroundWithBlock { (items, error) -> Void in if error == nil { var invites : [Invitation] = [] for obj in items ?? [] { if let invitation = obj as? Invitation { invites.append(invitation) } } block(invites) } } } }
mit
6138487030e980c292039be4fc3e17fd
40.910638
205
0.574533
5.416942
false
false
false
false
matrix-org/matrix-ios-sdk
MatrixSDKTests/Crypto/Verification/Transactions/SAS/Sas+Stub.swift
1
1647
// // Copyright 2022 The Matrix.org Foundation C.I.C // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation #if DEBUG import MatrixSDKCrypto extension Sas { static func stub( otherUserId: String = "Bob", otherDeviceId: String = "Device2", flowId: String = "123", roomId: String = "ABC", weStarted: Bool = true, hasBeenAccepted: Bool = false, canBePresented: Bool = false, supportsEmoji: Bool = true, haveWeConfirmed: Bool = false, isDone: Bool = false, isCancelled: Bool = false, cancelInfo: CancelInfo? = nil ) -> Sas { return .init( otherUserId: otherUserId, otherDeviceId: otherDeviceId, flowId: flowId, roomId: roomId, weStarted: weStarted, hasBeenAccepted: hasBeenAccepted, canBePresented: canBePresented, supportsEmoji: supportsEmoji, haveWeConfirmed: haveWeConfirmed, isDone: isDone, isCancelled: isCancelled, cancelInfo: cancelInfo ) } } #endif
apache-2.0
b8a480c67f225963dc3441c5d6d8c59a
28.945455
75
0.633273
4.451351
false
false
false
false
amraboelela/swift
stdlib/public/core/StringGuts.swift
1
8825
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims // // StringGuts is a parameterization over String's representations. It provides // functionality and guidance for efficiently working with Strings. // @_fixed_layout public // SPI(corelibs-foundation) struct _StringGuts { @usableFromInline internal var _object: _StringObject @inlinable @inline(__always) internal init(_ object: _StringObject) { self._object = object _invariantCheck() } // Empty string @inlinable @inline(__always) init() { self.init(_StringObject(empty: ())) } } // Raw extension _StringGuts { @inlinable internal var rawBits: _StringObject.RawBitPattern { @inline(__always) get { return _object.rawBits } } } // Creation extension _StringGuts { @inlinable @inline(__always) internal init(_ smol: _SmallString) { self.init(_StringObject(smol)) } @inlinable @inline(__always) internal init(_ bufPtr: UnsafeBufferPointer<UInt8>, isASCII: Bool) { self.init(_StringObject(immortal: bufPtr, isASCII: isASCII)) } @inline(__always) internal init(_ storage: __StringStorage) { self.init(_StringObject(storage)) } internal init(_ storage: __SharedStringStorage) { self.init(_StringObject(storage)) } internal init( cocoa: AnyObject, providesFastUTF8: Bool, isASCII: Bool, length: Int ) { self.init(_StringObject( cocoa: cocoa, providesFastUTF8: providesFastUTF8, isASCII: isASCII, length: length)) } } // Queries extension _StringGuts { // The number of code units @inlinable internal var count: Int { @inline(__always) get { return _object.count } } @inlinable internal var isEmpty: Bool { @inline(__always) get { return count == 0 } } @inlinable internal var isSmall: Bool { @inline(__always) get { return _object.isSmall } } internal var isSmallASCII: Bool { @inline(__always) get { return _object.isSmall && _object.smallIsASCII } } @inlinable internal var asSmall: _SmallString { @inline(__always) get { return _SmallString(_object) } } @inlinable internal var isASCII: Bool { @inline(__always) get { return _object.isASCII } } @inlinable internal var isFastASCII: Bool { @inline(__always) get { return isFastUTF8 && _object.isASCII } } @inline(__always) internal var isNFC: Bool { return _object.isNFC } @inline(__always) internal var isNFCFastUTF8: Bool { // TODO(String micro-performance): Consider a dedicated bit for this return _object.isNFC && isFastUTF8 } internal var hasNativeStorage: Bool { return _object.hasNativeStorage } internal var hasSharedStorage: Bool { return _object.hasSharedStorage } internal var hasBreadcrumbs: Bool { return hasNativeStorage || hasSharedStorage } } // extension _StringGuts { // Whether we can provide fast access to contiguous UTF-8 code units @_transparent @inlinable internal var isFastUTF8: Bool { return _fastPath(_object.providesFastUTF8) } // A String which does not provide fast access to contiguous UTF-8 code units @inlinable internal var isForeign: Bool { @inline(__always) get { return _slowPath(_object.isForeign) } } @inlinable @inline(__always) internal func withFastUTF8<R>( _ f: (UnsafeBufferPointer<UInt8>) throws -> R ) rethrows -> R { _internalInvariant(isFastUTF8) if self.isSmall { return try _SmallString(_object).withUTF8(f) } defer { _fixLifetime(self) } return try f(_object.fastUTF8) } @inlinable @inline(__always) internal func withFastUTF8<R>( range: Range<Int>, _ f: (UnsafeBufferPointer<UInt8>) throws -> R ) rethrows -> R { return try self.withFastUTF8 { wholeUTF8 in return try f(UnsafeBufferPointer(rebasing: wholeUTF8[range])) } } @inlinable @inline(__always) internal func withFastCChar<R>( _ f: (UnsafeBufferPointer<CChar>) throws -> R ) rethrows -> R { return try self.withFastUTF8 { utf8 in let ptr = utf8.baseAddress._unsafelyUnwrappedUnchecked._asCChar return try f(UnsafeBufferPointer(start: ptr, count: utf8.count)) } } } // Internal invariants extension _StringGuts { #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { #if arch(i386) || arch(arm) _internalInvariant(MemoryLayout<String>.size == 12, """ the runtime is depending on this, update Reflection.mm and \ this if you change it """) #else _internalInvariant(MemoryLayout<String>.size == 16, """ the runtime is depending on this, update Reflection.mm and \ this if you change it """) #endif } #endif // INTERNAL_CHECKS_ENABLED internal func _dump() { _object._dump() } } // C String interop extension _StringGuts { @inlinable @inline(__always) // fast-path: already C-string compatible internal func withCString<Result>( _ body: (UnsafePointer<Int8>) throws -> Result ) rethrows -> Result { if _slowPath(!_object.isFastZeroTerminated) { return try _slowWithCString(body) } return try self.withFastCChar { return try body($0.baseAddress._unsafelyUnwrappedUnchecked) } } @inline(never) // slow-path @usableFromInline internal func _slowWithCString<Result>( _ body: (UnsafePointer<Int8>) throws -> Result ) rethrows -> Result { _internalInvariant(!_object.isFastZeroTerminated) return try String(self).utf8CString.withUnsafeBufferPointer { let ptr = $0.baseAddress._unsafelyUnwrappedUnchecked return try body(ptr) } } } extension _StringGuts { // Copy UTF-8 contents. Returns number written or nil if not enough space. // Contents of the buffer are unspecified if nil is returned. @inlinable internal func copyUTF8(into mbp: UnsafeMutableBufferPointer<UInt8>) -> Int? { let ptr = mbp.baseAddress._unsafelyUnwrappedUnchecked if _fastPath(self.isFastUTF8) { return self.withFastUTF8 { utf8 in guard utf8.count <= mbp.count else { return nil } let utf8Start = utf8.baseAddress._unsafelyUnwrappedUnchecked ptr.initialize(from: utf8Start, count: utf8.count) return utf8.count } } return _foreignCopyUTF8(into: mbp) } @_effects(releasenone) @usableFromInline @inline(never) // slow-path internal func _foreignCopyUTF8( into mbp: UnsafeMutableBufferPointer<UInt8> ) -> Int? { var ptr = mbp.baseAddress._unsafelyUnwrappedUnchecked var numWritten = 0 for cu in String(self).utf8 { guard numWritten < mbp.count else { return nil } ptr.initialize(to: cu) ptr += 1 numWritten += 1 } return numWritten } internal var utf8Count: Int { @inline(__always) get { if _fastPath(self.isFastUTF8) { return count } return String(self).utf8.count } } } // Index extension _StringGuts { @usableFromInline internal typealias Index = String.Index @inlinable internal var startIndex: String.Index { @inline(__always) get { return Index(encodedOffset: 0) } } @inlinable internal var endIndex: String.Index { @inline(__always) get { return Index(encodedOffset: self.count) } } } // Old SPI(corelibs-foundation) extension _StringGuts { @available(*, deprecated) public // SPI(corelibs-foundation) var _isContiguousASCII: Bool { return !isSmall && isFastUTF8 && isASCII } @available(*, deprecated) public // SPI(corelibs-foundation) var _isContiguousUTF16: Bool { return false } // FIXME: Remove. Still used by swift-corelibs-foundation @available(*, deprecated) public var startASCII: UnsafeMutablePointer<UInt8> { return UnsafeMutablePointer(mutating: _object.fastUTF8.baseAddress!) } // FIXME: Remove. Still used by swift-corelibs-foundation @available(*, deprecated) public var startUTF16: UnsafeMutablePointer<UTF16.CodeUnit> { fatalError("Not contiguous UTF-16") } } @available(*, deprecated) public // SPI(corelibs-foundation) func _persistCString(_ p: UnsafePointer<CChar>?) -> [CChar]? { guard let s = p else { return nil } let count = Int(_swift_stdlib_strlen(s)) var result = [CChar](repeating: 0, count: count + 1) for i in 0..<count { result[i] = s[i] } return result }
apache-2.0
c5b3b59d9da78a36b0cbe9ad5f6274da
26.321981
80
0.672181
4.135426
false
false
false
false
jfrowies/coolblue
coolblue/ViewModels/ArticlesFeedViewModel.swift
1
2261
// // ArticlesFeedViewModel.swift // coolblue // // Created by Fer Rowies on 3/25/16. // Copyright © 2016 Fernando Rowies. All rights reserved. // import Foundation protocol ArticlesFeedViewModelDelegate: class { func articlesFeedViewModelDelegateDidLoadedArticles(sender sender: ArticlesFeedViewModel) } class ArticlesFeedViewModel { //MARK: - Internal properties weak var delegate : ArticlesFeedViewModelDelegate? var articles : [ArticleViewModel] = [ArticleViewModel]() //MARK: - Private properties private let articlesFeedService : ArticlesService private let imageDownloader : ImageDownloader private var fetchingData : Bool = false private var endOfData : Bool = false private var pageNumber : Int = 0 private var pageSize : Int = 30 //MARK: - initializers init(articlesFeedService: ArticlesService, imageDownloader: ImageDownloader) { self.articlesFeedService = articlesFeedService self.imageDownloader = imageDownloader } //MARK: - Functions func loadMoreArticles() { if self.endOfData || self.fetchingData { return } self.fetchingData = true articlesFeedService.getArticles(pageNumber: self.pageNumber+1, pageSize: self.pageSize) { [weak self] (result) -> Void in switch result { case .Success: if let articlesServiceResult = result.value { guard let strongSelf = self else { break } let newArticles = articlesServiceResult.articles.map { ArticleViewModel(article: $0, imageDownloader: strongSelf.imageDownloader) } strongSelf.articles.appendContentsOf(newArticles) strongSelf.pageNumber = articlesServiceResult.page if articlesServiceResult.articles.count < self?.pageSize { strongSelf.endOfData = true } } case .Failure: break } self?.delegate?.articlesFeedViewModelDelegateDidLoadedArticles(sender: self!) self?.fetchingData = false } } }
mit
f5968217bd56504387e35f499b608b9e
30.84507
151
0.620354
5.525672
false
false
false
false
azadibogolubov/InterestDestroyer
iOS Version/Interest Destroyer/Charts/Classes/Components/ChartXAxis.swift
16
5024
// // ChartXAxis.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit public class ChartXAxis: ChartAxisBase { @objc public enum XAxisLabelPosition: Int { case Top case Bottom case BothSided case TopInside case BottomInside } public var values = [String?]() public var labelWidth = CGFloat(1.0) public var labelHeight = CGFloat(1.0) /// the space that should be left out (in characters) between the x-axis labels /// This only applies if the number of labels that will be skipped in between drawn axis labels is not custom set. /// /// **default**: 4 public var spaceBetweenLabels = Int(4) /// the modulus that indicates if a value at a specified index in an array(list) for the x-axis-labels is drawn or not. Draw when `(index % modulus) == 0`. public var axisLabelModulus = Int(1) /// Is axisLabelModulus a custom value or auto calculated? If false, then it's auto, if true, then custom. /// /// **default**: false (automatic modulus) private var _isAxisModulusCustom = false /// the modulus that indicates if a value at a specified index in an array(list) for the y-axis-labels is drawn or not. Draw when `(index % modulus) == 0`. /// Used only for Horizontal BarChart public var yAxisLabelModulus = Int(1) /// if set to true, the chart will avoid that the first and last label entry in the chart "clip" off the edge of the chart public var avoidFirstLastClippingEnabled = false /// Custom formatter for adjusting x-value strings private var _xAxisValueFormatter: ChartXAxisValueFormatter = ChartDefaultXAxisValueFormatter() /// Custom XValueFormatter for the data object that allows custom-formatting of all x-values before rendering them. /// Provide null to reset back to the default formatting. public var valueFormatter: ChartXAxisValueFormatter? { get { return _xAxisValueFormatter } set { _xAxisValueFormatter = newValue ?? ChartDefaultXAxisValueFormatter() } } /// the position of the x-labels relative to the chart public var labelPosition = XAxisLabelPosition.Top /// if set to true, word wrapping the labels will be enabled. /// word wrapping is done using `(value width * labelWidth)` /// /// *Note: currently supports all charts except pie/radar/horizontal-bar* public var wordWrapEnabled = false /// - returns: true if word wrapping the labels is enabled public var isWordWrapEnabled: Bool { return wordWrapEnabled } /// the width for wrapping the labels, as percentage out of one value width. /// used only when isWordWrapEnabled = true. /// /// **default**: 1.0 public var wordWrapWidthPercent: CGFloat = 1.0 public override init() { super.init() } public override func getLongestLabel() -> String { var longest = "" for (var i = 0; i < values.count; i++) { let text = values[i] if (text != nil && longest.characters.count < (text!).characters.count) { longest = text! } } return longest } public var isAvoidFirstLastClippingEnabled: Bool { return avoidFirstLastClippingEnabled } /// Sets the number of labels that should be skipped on the axis before the next label is drawn. /// This will disable the feature that automatically calculates an adequate space between the axis labels and set the number of labels to be skipped to the fixed number provided by this method. /// Call `resetLabelsToSkip(...)` to re-enable automatic calculation. public func setLabelsToSkip(count: Int) { _isAxisModulusCustom = true if (count < 0) { axisLabelModulus = 1 } else { axisLabelModulus = count + 1 } } /// Calling this will disable a custom number of labels to be skipped (set by `setLabelsToSkip(...)`) while drawing the x-axis. Instead, the number of values to skip will again be calculated automatically. public func resetLabelsToSkip() { _isAxisModulusCustom = false } /// - returns: true if a custom axis-modulus has been set that determines the number of labels to skip when drawing. public var isAxisModulusCustom: Bool { return _isAxisModulusCustom } public var valuesObjc: [NSObject] { get { return ChartUtils.bridgedObjCGetStringArray(swift: values); } set { self.values = ChartUtils.bridgedObjCGetStringArray(objc: newValue); } } }
apache-2.0
6539186d81bf711d977b2f9e04291fc8
32.271523
209
0.642715
4.730697
false
false
false
false
HassanEskandari/Eureka
Source/Core/Row.swift
1
6516
// Row.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation open class RowOf<T>: BaseRow where T: Equatable{ private var _value: T? { didSet { guard _value != oldValue else { return } guard let form = section?.form else { return } if let delegate = form.delegate { delegate.valueHasBeenChanged(for: self, oldValue: oldValue, newValue: value) callbackOnChange?() } guard let t = tag else { return } form.tagToValues[t] = (value != nil ? value! : NSNull()) if let rowObservers = form.rowObservers[t]?[.hidden] { for rowObserver in rowObservers { (rowObserver as? Hidable)?.evaluateHidden() } } if let rowObservers = form.rowObservers[t]?[.disabled] { for rowObserver in rowObservers { (rowObserver as? Disableable)?.evaluateDisabled() } } } } /// The typed value of this row. open var value: T? { set (newValue) { _value = newValue guard let _ = section?.form else { return } wasChanged = true if validationOptions.contains(.validatesOnChange) || (wasBlurred && validationOptions.contains(.validatesOnChangeAfterBlurred)) || (!isValid && validationOptions != .validatesOnDemand) { validate() } } get { return _value } } /// The untyped value of this row. public override var baseValue: Any? { get { return value } set { value = newValue as? T } } /// Block variable used to get the String that should be displayed for the value of this row. open var displayValueFor: ((T?) -> String?)? = { return $0.map { String(describing: $0) } } public required init(tag: String?) { super.init(tag: tag) } internal var rules: [ValidationRuleHelper<T>] = [] @discardableResult public override func validate() -> [ValidationError] { validationErrors = rules.flatMap { $0.validateFn(value) } return validationErrors } /// Add a Validation rule for the Row /// - Parameter rule: RuleType object to add public func add<Rule: RuleType>(rule: Rule) where T == Rule.RowValueType { let validFn: ((T?) -> ValidationError?) = { (val: T?) in return rule.isValid(value: val) } rules.append(ValidationRuleHelper(validateFn: validFn, rule: rule)) } /// Add a Validation rule set for the Row /// - Parameter ruleSet: RuleSet<T> set of rules to add public func add(ruleSet: RuleSet<T>) { rules.append(contentsOf: ruleSet.rules) } public func remove(ruleWithIdentifier identifier: String) { if let index = rules.index(where: { (validationRuleHelper) -> Bool in return validationRuleHelper.rule.id == identifier }) { rules.remove(at: index) } } public func removeAllRules() { validationErrors.removeAll() rules.removeAll() } public func setValue(values: [String: Any?]) { if let tag = self.tag { if values.keys.contains(tag) { self.value = values[tag] as? T } } } } /// Generic class that represents an Eureka row. open class Row<Cell: CellType>: RowOf<Cell.Value>, TypedRowType where Cell: BaseCell { /// Responsible for creating the cell for this row. public var cellProvider = CellProvider<Cell>() /// The type of the cell associated to this row. public let cellType: Cell.Type! = Cell.self private var _cell: Cell! { didSet { RowDefaults.cellSetup["\(type(of: self))"]?(_cell, self) (callbackCellSetup as? ((Cell) -> Void))?(_cell) } } /// The cell associated to this row. public var cell: Cell! { return _cell ?? { let result = cellProvider.makeCell(style: self.cellStyle) result.row = self result.setup() _cell = result return _cell }() } /// The untyped cell associated to this row public override var baseCell: BaseCell { return cell } public required init(tag: String?) { super.init(tag: tag) } /** Method that reloads the cell */ override open func updateCell() { super.updateCell() cell.update() customUpdateCell() RowDefaults.cellUpdate["\(type(of: self))"]?(cell, self) callbackCellUpdate?() } /** Method called when the cell belonging to this row was selected. Must call the corresponding method in its cell. */ open override func didSelect() { super.didSelect() if !isDisabled { cell?.didSelect() } customDidSelect() callbackCellOnSelection?() } /** Will be called inside `didSelect` method of the row. Can be used to customize row selection from the definition of the row. */ open func customDidSelect() {} /** Will be called inside `updateCell` method of the row. Can be used to customize reloading a row from its definition. */ open func customUpdateCell() {} }
mit
c123e6572147b0326b8766b7554019c5
32.415385
199
0.607888
4.637722
false
false
false
false
sunshineclt/NKU-Helper
NKU Helper/StoreClass/VersionInfoAgent.swift
1
1375
// // VersionInfoAgent.swift // NKU Helper // // Created by 陈乐天 on 16/8/2. // Copyright © 2016年 陈乐天. All rights reserved. // import Foundation private let sharedStoreAgent = VersionInfoAgent() /** 访问用户详细数据的类 * * * * * last modified: - date: 2016.9.30 - author: 陈乐天 - since: Swift3.0 - version: 1.0 */ class VersionInfoAgent: UserDefaultsBaseStoreAgent { class var sharedInstance: VersionInfoAgent { return sharedStoreAgent } typealias dataForm = (Version: String, Build: String)? let key = "buildCode" /// 访问存储中的Version号和Build号 /// /// - returns: Version号和Build号组成的元组 func getData() -> dataForm { guard let data = userDefaults.dictionary(forKey: key) as? [String: String] else { return nil } return (Version: data["version"]!, Build: data["build"]!) } /// 存储当前Version号和Build号 func saveData() { let version = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String let build = Bundle.main.infoDictionary!["CFBundleVersion"] as! String let data = ["version": version, "build": build] userDefaults.removeObject(forKey: key) userDefaults.set(data, forKey: key) userDefaults.synchronize() } }
gpl-3.0
e15cf7f93bd0f52ba28f75b05ecf5e92
22.814815
90
0.62986
3.932722
false
false
false
false
gearedupcoding/RadioPal
RadioPal/New Group/StreamModel.swift
1
592
// // StreamModel.swift // RadioPal // // Created by Jami, Dheeraj on 9/20/17. // Copyright © 2017 Jami, Dheeraj. All rights reserved. // import UIKit import SwiftyJSON class StreamModel: NSObject { var contentType: String? var status: Int? var listeners: Int? var stream: String? var bitrate: Int? init(json: JSON) { self.contentType = json["content_type"].string self.stream = json["stream"].string self.bitrate = json["bitrate"].int self.status = json["status"].int self.listeners = json["listeners"].int } }
mit
73a32e2026ebfb69f1ff6afbf25332fb
21.730769
56
0.624365
3.648148
false
false
false
false
mlgoogle/wp
wp/Scenes/Login/ResetLoginPasswordVC.swift
1
5105
// // ResetLoginPasswordVC.swift // wp // // Created by mu on 2017/4/26. // Copyright © 2017年 com.yundian. All rights reserved. // import UIKit import SVProgressHUD import DKNightVersion class ResetLoginPasswordVC: BaseTableViewController { @IBOutlet weak var phoneView: UIView! @IBOutlet weak var phoneText: UITextField! @IBOutlet weak var codeText: UITextField! @IBOutlet weak var codeBtn: UIButton! @IBOutlet weak var nextBtn: UIButton! @IBOutlet weak var pwdText: UITextField! private var timer: Timer? private var codeTime = 60 //MARK: --LIFECYCLE override func viewDidLoad() { super.viewDidLoad() initUI() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) hideTabBarWithAnimationDuration() translucent(clear: false) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) SVProgressHUD.dismiss() } //获取验证码 @IBAction func changeCodePicture(_ sender: UIButton) { if checkoutText(){ let type = 1 SVProgressHUD.showProgressMessage(ProgressMessage: "请稍候...") AppAPIHelper.commen().verifycode(verifyType: Int64(type), phone: phoneText.text!, complete: { [weak self](result) -> ()? in SVProgressHUD.dismiss() if let strongSelf = self{ if let resultDic: [String: AnyObject] = result as? [String : AnyObject]{ if let token = resultDic[SocketConst.Key.vToken]{ UserModel.share().codeToken = token as! String } if let timestamp = resultDic[SocketConst.Key.timeStamp]{ UserModel.share().timestamp = timestamp as! Int } } strongSelf.codeBtn.isEnabled = false strongSelf.timer = Timer.scheduledTimer(timeInterval: 1, target: strongSelf, selector: #selector(strongSelf.updatecodeBtnTitle), userInfo: nil, repeats: true) } return nil }, error: errorBlockFunc()) } } func updatecodeBtnTitle() { if codeTime == 0 { codeBtn.isEnabled = true codeBtn.setTitle("重新发送", for: .normal) codeTime = 60 timer?.invalidate() codeBtn.dk_backgroundColorPicker = DKColorTable.shared().picker(withKey: AppConst.Color.main) return } codeBtn.isEnabled = false codeTime = codeTime - 1 let title: String = "\(codeTime)秒后重新发送" codeBtn.setTitle(title, for: .normal) codeBtn.backgroundColor = UIColor.init(rgbHex: 0xCCCCCC) } //注册 @IBAction func nextBtnTapped(_ sender: UIButton) { if checkoutText(){ if checkTextFieldEmpty([phoneText,pwdText,codeText]){ UserModel.share().code = codeText.text UserModel.share().phone = phoneText.text resetpwd() } } } func resetpwd() { let password = ((pwdText.text! + AppConst.sha256Key).sha256()+UserModel.share().phone!).sha256() let param = ResetPwdParam() param.phone = phoneText.text! param.pwd = password param.vCode = UserModel.share().code! param.vToken = UserModel.share().codeToken param.timestamp = UserModel.share().timestamp SVProgressHUD.showProgressMessage(ProgressMessage: "重置中...") AppAPIHelper.login().repwd(param: param, complete: { [weak self](result) -> ()?in SVProgressHUD.dismiss() if let status: Int = result?["status"] as? Int{ if status == 0{ SVProgressHUD.showSuccessMessage(SuccessMessage: "重置成功", ForDuration: 2, completion: nil) _ = self?.navigationController?.popToRootViewController(animated: true) }else{ SVProgressHUD.showErrorMessage(ErrorMessage: "重置失败", ForDuration: 2, completion: nil) } } return nil }, error: errorBlockFunc()) } func checkoutText() -> Bool { if checkTextFieldEmpty([phoneText]) { if isTelNumber(num: phoneText.text!) == false{ SVProgressHUD.showErrorMessage(ErrorMessage: "手机号格式错误", ForDuration: 1, completion: nil) return false } return true } return false } //MARK: --UI func initUI() { phoneView.layer.borderWidth = 0.5 pwdText.placeholder = "请输入登录密码" phoneView.layer.borderColor = UIColor.init(rgbHex: 0xcccccc).cgColor codeBtn.dk_backgroundColorPicker = DKColorTable.shared().picker(withKey: AppConst.Color.main) nextBtn.dk_backgroundColorPicker = DKColorTable.shared().picker(withKey: AppConst.Color.main) } }
apache-2.0
920518ca7287524a417fb1259be61133
36.684211
178
0.58739
4.823869
false
false
false
false
SASAbus/SASAbus-ios
SASAbus/Controller/Route/MainRouteViewController.swift
1
2264
import UIKit import Pulley import LocationPickerViewController class MainRouteViewController: MasterViewController { @IBOutlet var searchContainer: UIView! @IBOutlet var resultsContainer: UIView! let searchViewController: RouteFeedViewController? = nil let resultsViewController: RouteResultsViewController? = nil private var shadowImageView: UIImageView? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } required init() { super.init(nibName: "MainRouteViewController", title: "Route") } override func viewDidLoad() { super.viewDidLoad() let searchNib = UINib(nibName: "RouteFeedViewController", bundle: nil) let searchViewController = searchNib.instantiate(withOwner: self)[0] as! RouteFeedViewController searchViewController.parentVC = self let resultsViewController = RouteResultsViewController.getViewController() resultsViewController.parentVC = self addChildController(searchViewController, container: searchContainer) addChildController(resultsViewController, container: resultsContainer) resultsContainer.isHidden = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if shadowImageView == nil { shadowImageView = findShadowImage(under: navigationController!.navigationBar) } shadowImageView?.isHidden = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) shadowImageView?.isHidden = false } private func findShadowImage(under view: UIView) -> UIImageView? { if view is UIImageView && view.bounds.size.height <= 1 { return (view as! UIImageView) } for subview in view.subviews { if let imageView = findShadowImage(under: subview) { return imageView } } return nil } func showRouteResults(origin: LocationItem, destination: LocationItem) { searchContainer.isHidden = true resultsContainer.isHidden = false resultsViewController?.showRouteResults(origin: origin, destination: destination) } }
gpl-3.0
03093336d2f6b40c3f59d9eec754be7f
27.3
104
0.687721
5.455422
false
false
false
false