repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
lijianwei-jj/OOSegmentViewController
OOSegmentViewController/OOSegmentNavigationBar.swift
1
8401
// // OOSegmentNavigationBar.swift // OOSegmentViewController // // Created by lee on 16/6/27. // Copyright © 2016年 clearlove. All rights reserved. // import UIKit open class OOSegmentNavigationBar : UIScrollView { public var isTitleItem = true public var titles = [String]() { didSet { isTitleItem = true configItems() } } public var images = [UIImage]() { didSet { isTitleItem = false configItems() } } fileprivate var datas: [AnyHashable] { return isTitleItem ? titles : images } open var itemHeight : CGFloat! open var titleColor : UIColor! open var titleSelectedColor : UIColor! open var fontSize : CGFloat! open var cursorBottomMargin : CGFloat? open var cursorHeight : CGFloat! open var itemMargin : CGFloat = 0 open var itemOffset : CGFloat = 0 var segmentViewController : OOSegmentViewController? fileprivate var titleItemMap = [AnyHashable:UIButton]() fileprivate var selectedItem : UIButton! var moveEffect : CursorMoveEffect! fileprivate var contentView = UIView(frame: CGRect.zero) // private var lastContentOffset = CGFloat(0) open var cursor = UIView(frame: CGRect(x: 0,y: 0,width: 0,height: 2)) var cursorColor : UIColor! { didSet { cursor.backgroundColor = cursorColor } } public init(){ super.init(frame: CGRect.zero) configUI() } override public init(frame: CGRect) { super.init(frame: frame) configUI() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func layoutSubviews() { super.layoutSubviews() if contentView.frame == CGRect.zero { contentView.frame.size.height = self.frame.size.height let height = self.frame.height if let margin = cursorBottomMargin { cursor.frame = CGRect(x: 0, y: height - cursorHeight - margin, width: 0, height: cursorHeight) } else { cursor.frame = CGRect(x: 0, y: height - cursorHeight - (height-fontSize)/4, width: 0, height: cursorHeight) } layoutItems() } } public func configUI() { self.showsHorizontalScrollIndicator = false addSubview(contentView) cursor.backgroundColor = cursorColor contentView.addSubview(cursor) } public func configItems() { // guard titleItemMap.count == 0 else { // return // } guard let _ = titleColor,let _ = titleSelectedColor,let _ = fontSize else { return } // print("configItems") titleItemMap.values.forEach { $0.removeFromSuperview() } datas.enumerated().forEach { let item = UIButton() item.tag = $0 if isTitleItem { let title = $1 as? String item.setTitle(title, for: .normal) item.setTitleColor(titleColor, for: .normal) item.setTitleColor(titleSelectedColor, for: .selected) item.titleLabel?.font = UIFont.systemFont(ofSize: fontSize) }else{ let image = $1 as? UIImage item.setImage(image, for: .selected) item.setImage(image?.withRenderingMode(.alwaysTemplate), for: .normal) item.tintColor = UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1) } item.addTarget(self, action: #selector(itemClick(_:)), for: .touchUpInside) titleItemMap[$1] = item contentView.addSubview(item) } layoutItems() } open func layoutItems() { guard frame.height > 0 else { return } contentView.frame.origin.x = 0 var contentWidth = itemOffset datas.enumerated().forEach { let itemSize = (datas[$0] as? UIImage)?.size ?? CGSize.zero let item = titleItemMap[$1] let itemWidth = isTitleItem ? ceil(titleWidthAtFont(UIFont.systemFont(ofSize: fontSize), index: $0)) : itemHeight / itemSize.height * itemSize.width let y = isTitleItem ? 0 : (self.frame.height - itemHeight) / 2.0 item?.frame = CGRect(x: contentWidth, y: y, width: itemWidth, height: isTitleItem ? self.frame.height : itemHeight) if $0 == segmentViewController?.pageIndex ?? 0 { cursor.frame.size.width = itemWidth cursor.frame.origin.x = contentWidth item?.isSelected = true selectedItem = item } contentWidth += itemWidth + itemMargin } contentWidth += itemOffset - itemMargin contentSize.width = contentWidth contentView.frame.size.width = contentWidth // contentView.frame.origin.x = contentWidth < CGRectGetWidth(self.frame) ? (CGRectGetWidth(self.frame) - contentWidth) / 2.0 : 0 if contentWidth < self.frame.width { contentView.frame.origin.x = (self.frame.width - contentWidth) / 2.0 } } @objc func itemClick(_ sender:UIButton) { segmentViewController?.moveToControllerAtIndex(index: sender.tag) } func titleWidthAtFont(_ font:UIFont,index:Int) -> CGFloat { return titles[index].boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: font.lineHeight), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil).size.width + 4 } func updateSelectItem(_ newIndex: Int) { // if let pageIndex = segmentViewController?.pendingIndex { selectedItem.isSelected = false selectedItem = titleItemMap[datas[newIndex]] selectedItem.isSelected = true // } } } extension OOSegmentNavigationBar : UIScrollViewDelegate { // XXX: 这还是有点小问题 当用户从最右开始拖动 cursor 会有跳动 public func scrollViewDidScroll(_ scrollView: UIScrollView) { // print(scrollView.contentOffset.x) guard let segmentViewController = segmentViewController else { return } let fullWidth = segmentViewController.view.frame.width // view移动完后系统会重新设置当前view的位置 if scrollView.contentOffset.x == fullWidth { return } guard scrollView.contentOffset.x >= 0 && scrollView.contentOffset.x <= fullWidth * 2 else { return } let oldIndex = segmentViewController.pageIndex var index = segmentViewController.pendingIndex if abs(index - oldIndex) < 2 { index = scrollView.contentOffset.x > fullWidth ? oldIndex + 1 : oldIndex - 1 } guard index >= 0 && index < datas.count else { return } let button = titleItemMap[datas[index]]! , oldButton = titleItemMap[datas[oldIndex]]! if let _ = moveEffect.scroll?(scrollView, navBar: self, cursor: self.cursor, newItem: button, oldItem: oldButton) { return } let xScale = scrollView.contentOffset.x.truncatingRemainder(dividingBy: fullWidth) / fullWidth let indicatorWidth = button.frame.size.width // titleWidthAtFont(titleFont, index: index) let oldWidth = oldButton.frame.size.width // titleWidthAtFont(titleFont, index: oldIndex) let f = CGFloat(button.tag - oldButton.tag) var s = (f > 0 ? 1.0 - (xScale == 0 ? 1.0 : xScale) : xScale) // == 1.0 ? xScale : 0 s = s < 0.01 || s > 0.99 ? round(s) : s let w = round((oldWidth - indicatorWidth) * s + indicatorWidth) let x = round((oldButton.frame.origin.x - button.frame.origin.x) * s) + button.frame.origin.x let cx = round((oldButton.center.x - button.center.x) * s) + button.center.x if let _ = moveEffect.scroll?(scrollView, navBar: self, cursor: self.cursor, fullWidth: fullWidth, xScale: xScale, correctXScale: s,computeWidth:w, leftXOffset: x, centerXOffset: cx, finished: s==0) { return } } }
mit
682eb9a41b175818b141a0c4254f06c4
35.823009
254
0.597092
4.620766
false
false
false
false
peaks-cc/iOS11_samplecode
chapter_12/HomeKitSample/App/Code/Lib/HomeKitUtils/CharacteristicType.swift
1
18931
// // CharacteristicType.swift // // Created by ToKoRo on 2017-08-21. // import HomeKit enum CharacteristicType { case unknown case powerState case hue case saturation case brightness case temperatureUnits case currentTemperature case targetTemperature case currentHeatingCooling case targetHeatingCooling case coolingThreshold case heatingThreshold case currentRelativeHumidity case targetRelativeHumidity case currentDoorState case targetDoorState case obstructionDetected case name case manufacturer case model case serialNumber case identify case rotationDirection case rotationSpeed case outletInUse case version case logs case audioFeedback case adminOnlyAccess case securitySystemAlarmType case motionDetected case currentLockMechanismState case targetLockMechanismState case lockMechanismLastKnownAction case lockManagementControlPoint case lockManagementAutoSecureTimeout case airParticulateDensity case airParticulateSize case airQuality case batteryLevel case carbonDioxideDetected case carbonDioxideLevel case carbonDioxidePeakLevel case carbonMonoxideDetected case carbonMonoxideLevel case carbonMonoxidePeakLevel case chargingState case contactState case currentHorizontalTilt case currentLightLevel case currentPosition case currentSecuritySystemState case currentVerticalTilt case firmwareVersion case hardwareVersion case holdPosition case inputEvent case leakDetected case occupancyDetected case outputState case positionState case smokeDetected case softwareVersion case statusActive case statusFault case statusJammed case statusLowBattery case statusTampered case targetHorizontalTilt case targetSecuritySystemState case targetPosition case targetVerticalTilt case streamingStatus case setupStreamEndpoint case supportedVideoStreamConfiguration case supportedAudioStreamConfiguration case supportedRTPConfiguration case selectedStreamConfiguration case volume case mute case nightVision case opticalZoom case digitalZoom case imageRotation case imageMirroring case labelNamespace case labelIndex case active case currentAirPurifierState case targetAirPurifierState case currentFanState case currentHeaterCoolerState case currentHumidifierDehumidifierState case currentSlatState case waterLevel case filterChangeIndication case filterLifeLevel case filterResetChangeIndication case lockPhysicalControls case swingMode case targetHeaterCoolerState case targetHumidifierDehumidifierState case targetFanState case slatType case currentTilt case targetTilt case ozoneDensity case nitrogenDioxideDensity case sulphurDioxideDensity case pm25Density case pm10Density case volatileOrganicCompoundDensity case dehumidifierThreshold case humidifierThreshold case colorTemperature init(typeString: String) { switch typeString { case HMCharacteristicTypePowerState: self = .powerState case HMCharacteristicTypeHue: self = .hue case HMCharacteristicTypeSaturation: self = .saturation case HMCharacteristicTypeBrightness: self = .brightness case HMCharacteristicTypeTemperatureUnits: self = .temperatureUnits case HMCharacteristicTypeCurrentTemperature: self = .currentTemperature case HMCharacteristicTypeTargetTemperature: self = .targetTemperature case HMCharacteristicTypeCurrentHeatingCooling: self = .currentHeatingCooling case HMCharacteristicTypeTargetHeatingCooling: self = .targetHeatingCooling case HMCharacteristicTypeCoolingThreshold: self = .coolingThreshold case HMCharacteristicTypeHeatingThreshold: self = .heatingThreshold case HMCharacteristicTypeCurrentRelativeHumidity: self = .currentRelativeHumidity case HMCharacteristicTypeTargetRelativeHumidity: self = .targetRelativeHumidity case HMCharacteristicTypeCurrentDoorState: self = .currentDoorState case HMCharacteristicTypeTargetDoorState: self = .targetDoorState case HMCharacteristicTypeObstructionDetected: self = .obstructionDetected case HMCharacteristicTypeName: self = .name case HMCharacteristicTypeManufacturer: self = .manufacturer case HMCharacteristicTypeModel: self = .model case HMCharacteristicTypeSerialNumber: self = .serialNumber case HMCharacteristicTypeIdentify: self = .identify case HMCharacteristicTypeRotationDirection: self = .rotationDirection case HMCharacteristicTypeRotationSpeed: self = .rotationSpeed case HMCharacteristicTypeOutletInUse: self = .outletInUse case HMCharacteristicTypeVersion: self = .version case HMCharacteristicTypeLogs: self = .logs case HMCharacteristicTypeAudioFeedback: self = .audioFeedback case HMCharacteristicTypeAdminOnlyAccess: self = .adminOnlyAccess case HMCharacteristicTypeSecuritySystemAlarmType: self = .securitySystemAlarmType case HMCharacteristicTypeMotionDetected: self = .motionDetected case HMCharacteristicTypeCurrentLockMechanismState: self = .currentLockMechanismState case HMCharacteristicTypeTargetLockMechanismState: self = .targetLockMechanismState case HMCharacteristicTypeLockMechanismLastKnownAction: self = .lockMechanismLastKnownAction case HMCharacteristicTypeLockManagementControlPoint: self = .lockManagementControlPoint case HMCharacteristicTypeLockManagementAutoSecureTimeout: self = .lockManagementAutoSecureTimeout case HMCharacteristicTypeAirParticulateDensity: self = .airParticulateDensity case HMCharacteristicTypeAirParticulateSize: self = .airParticulateSize case HMCharacteristicTypeAirQuality: self = .airQuality case HMCharacteristicTypeBatteryLevel: self = .batteryLevel case HMCharacteristicTypeCarbonDioxideDetected: self = .carbonDioxideDetected case HMCharacteristicTypeCarbonDioxideLevel: self = .carbonDioxideLevel case HMCharacteristicTypeCarbonDioxidePeakLevel: self = .carbonDioxidePeakLevel case HMCharacteristicTypeCarbonMonoxideDetected: self = .carbonMonoxideDetected case HMCharacteristicTypeCarbonMonoxideLevel: self = .carbonMonoxideLevel case HMCharacteristicTypeCarbonMonoxidePeakLevel: self = .carbonMonoxidePeakLevel case HMCharacteristicTypeChargingState: self = .chargingState case HMCharacteristicTypeContactState: self = .contactState case HMCharacteristicTypeCurrentHorizontalTilt: self = .currentHorizontalTilt case HMCharacteristicTypeCurrentLightLevel: self = .currentLightLevel case HMCharacteristicTypeCurrentPosition: self = .currentPosition case HMCharacteristicTypeCurrentSecuritySystemState: self = .currentSecuritySystemState case HMCharacteristicTypeCurrentVerticalTilt: self = .currentVerticalTilt case HMCharacteristicTypeFirmwareVersion: self = .firmwareVersion case HMCharacteristicTypeHardwareVersion: self = .hardwareVersion case HMCharacteristicTypeHoldPosition: self = .holdPosition case HMCharacteristicTypeInputEvent: self = .inputEvent case HMCharacteristicTypeLeakDetected: self = .leakDetected case HMCharacteristicTypeOccupancyDetected: self = .occupancyDetected case HMCharacteristicTypeOutputState: self = .outputState case HMCharacteristicTypePositionState: self = .positionState case HMCharacteristicTypeSmokeDetected: self = .smokeDetected case HMCharacteristicTypeSoftwareVersion: self = .softwareVersion case HMCharacteristicTypeStatusActive: self = .statusActive case HMCharacteristicTypeStatusFault: self = .statusFault case HMCharacteristicTypeStatusJammed: self = .statusJammed case HMCharacteristicTypeStatusLowBattery: self = .statusLowBattery case HMCharacteristicTypeStatusTampered: self = .statusTampered case HMCharacteristicTypeTargetHorizontalTilt: self = .targetHorizontalTilt case HMCharacteristicTypeTargetSecuritySystemState: self = .targetSecuritySystemState case HMCharacteristicTypeTargetPosition: self = .targetPosition case HMCharacteristicTypeTargetVerticalTilt: self = .targetVerticalTilt case HMCharacteristicTypeStreamingStatus: self = .streamingStatus case HMCharacteristicTypeSetupStreamEndpoint: self = .setupStreamEndpoint case HMCharacteristicTypeSupportedVideoStreamConfiguration: self = .supportedVideoStreamConfiguration case HMCharacteristicTypeSupportedAudioStreamConfiguration: self = .supportedAudioStreamConfiguration case HMCharacteristicTypeSupportedRTPConfiguration: self = .supportedRTPConfiguration case HMCharacteristicTypeSelectedStreamConfiguration: self = .selectedStreamConfiguration case HMCharacteristicTypeVolume: self = .volume case HMCharacteristicTypeMute: self = .mute case HMCharacteristicTypeNightVision: self = .nightVision case HMCharacteristicTypeOpticalZoom: self = .opticalZoom case HMCharacteristicTypeDigitalZoom: self = .digitalZoom case HMCharacteristicTypeImageRotation: self = .imageRotation case HMCharacteristicTypeImageMirroring: self = .imageMirroring case HMCharacteristicTypeLabelNamespace: self = .labelNamespace case HMCharacteristicTypeLabelIndex: self = .labelIndex case HMCharacteristicTypeActive: self = .active case HMCharacteristicTypeCurrentAirPurifierState: self = .currentAirPurifierState case HMCharacteristicTypeTargetAirPurifierState: self = .targetAirPurifierState case HMCharacteristicTypeCurrentFanState: self = .currentFanState case HMCharacteristicTypeCurrentHeaterCoolerState: self = .currentHeaterCoolerState case HMCharacteristicTypeCurrentHumidifierDehumidifierState: self = .currentHumidifierDehumidifierState case HMCharacteristicTypeCurrentSlatState: self = .currentSlatState case HMCharacteristicTypeWaterLevel: self = .waterLevel case HMCharacteristicTypeFilterChangeIndication: self = .filterChangeIndication case HMCharacteristicTypeFilterLifeLevel: self = .filterLifeLevel case HMCharacteristicTypeFilterResetChangeIndication: self = .filterResetChangeIndication case HMCharacteristicTypeLockPhysicalControls: self = .lockPhysicalControls case HMCharacteristicTypeSwingMode: self = .swingMode case HMCharacteristicTypeTargetHeaterCoolerState: self = .targetHeaterCoolerState case HMCharacteristicTypeTargetHumidifierDehumidifierState: self = .targetHumidifierDehumidifierState case HMCharacteristicTypeTargetFanState: self = .targetFanState case HMCharacteristicTypeSlatType: self = .slatType case HMCharacteristicTypeCurrentTilt: self = .currentTilt case HMCharacteristicTypeTargetTilt: self = .targetTilt case HMCharacteristicTypeOzoneDensity: self = .ozoneDensity case HMCharacteristicTypeNitrogenDioxideDensity: self = .nitrogenDioxideDensity case HMCharacteristicTypeSulphurDioxideDensity: self = .sulphurDioxideDensity case HMCharacteristicTypePM2_5Density: self = .pm25Density case HMCharacteristicTypePM10Density: self = .pm10Density case HMCharacteristicTypeVolatileOrganicCompoundDensity: self = .volatileOrganicCompoundDensity case HMCharacteristicTypeDehumidifierThreshold: self = .dehumidifierThreshold case HMCharacteristicTypeHumidifierThreshold: self = .humidifierThreshold case HMCharacteristicTypeColorTemperature: self = .colorTemperature default: self = .unknown } } } extension CharacteristicType: CustomStringConvertible { var description: String { switch self { case .unknown: return "UNKNOWN" case .powerState: return "powerState" case .hue: return "hue" case .saturation: return "saturation" case .brightness: return "brightness" case .temperatureUnits: return "temperatureUnits" case .currentTemperature: return "currentTemperature" case .targetTemperature: return "targetTemperature" case .currentHeatingCooling: return "currentHeatingCooling" case .targetHeatingCooling: return "targetHeatingCooling" case .coolingThreshold: return "coolingThreshold" case .heatingThreshold: return "heatingThreshold" case .currentRelativeHumidity: return "currentRelativeHumidity" case .targetRelativeHumidity: return "targetRelativeHumidity" case .currentDoorState: return "currentDoorState" case .targetDoorState: return "targetDoorState" case .obstructionDetected: return "obstructionDetected" case .name: return "name" case .manufacturer: return "manufacturer" case .model: return "model" case .serialNumber: return "serialNumber" case .identify: return "identify" case .rotationDirection: return "rotationDirection" case .rotationSpeed: return "rotationSpeed" case .outletInUse: return "outletInUse" case .version: return "version" case .logs: return "logs" case .audioFeedback: return "audioFeedback" case .adminOnlyAccess: return "adminOnlyAccess" case .securitySystemAlarmType: return "securitySystemAlarmType" case .motionDetected: return "motionDetected" case .currentLockMechanismState: return "currentLockMechanismState" case .targetLockMechanismState: return "targetLockMechanismState" case .lockMechanismLastKnownAction: return "lockMechanismLastKnownAction" case .lockManagementControlPoint: return "lockManagementControlPoint" case .lockManagementAutoSecureTimeout: return "lockManagementAutoSecureTimeout" case .airParticulateDensity: return "airParticulateDensity" case .airParticulateSize: return "airParticulateSize" case .airQuality: return "airQuality" case .batteryLevel: return "batteryLevel" case .carbonDioxideDetected: return "carbonDioxideDetected" case .carbonDioxideLevel: return "carbonDioxideLevel" case .carbonDioxidePeakLevel: return "carbonDioxidePeakLevel" case .carbonMonoxideDetected: return "carbonMonoxideDetected" case .carbonMonoxideLevel: return "carbonMonoxideLevel" case .carbonMonoxidePeakLevel: return "carbonMonoxidePeakLevel" case .chargingState: return "chargingState" case .contactState: return "contactState" case .currentHorizontalTilt: return "currentHorizontalTilt" case .currentLightLevel: return "currentLightLevel" case .currentPosition: return "currentPosition" case .currentSecuritySystemState: return "currentSecuritySystemState" case .currentVerticalTilt: return "currentVerticalTilt" case .firmwareVersion: return "firmwareVersion" case .hardwareVersion: return "hardwareVersion" case .holdPosition: return "holdPosition" case .inputEvent: return "inputEvent" case .leakDetected: return "leakDetected" case .occupancyDetected: return "occupancyDetected" case .outputState: return "outputState" case .positionState: return "positionState" case .smokeDetected: return "smokeDetected" case .softwareVersion: return "softwareVersion" case .statusActive: return "statusActive" case .statusFault: return "statusFault" case .statusJammed: return "statusJammed" case .statusLowBattery: return "statusLowBattery" case .statusTampered: return "statusTampered" case .targetHorizontalTilt: return "targetHorizontalTilt" case .targetSecuritySystemState: return "targetSecuritySystemState" case .targetPosition: return "targetPosition" case .targetVerticalTilt: return "targetVerticalTilt" case .streamingStatus: return "streamingStatus" case .setupStreamEndpoint: return "setupStreamEndpoint" case .supportedVideoStreamConfiguration: return "supportedVideoStreamConfiguration" case .supportedAudioStreamConfiguration: return "supportedAudioStreamConfiguration" case .supportedRTPConfiguration: return "supportedRTPConfiguration" case .selectedStreamConfiguration: return "selectedStreamConfiguration" case .volume: return "volume" case .mute: return "mute" case .nightVision: return "nightVision" case .opticalZoom: return "opticalZoom" case .digitalZoom: return "digitalZoom" case .imageRotation: return "imageRotation" case .imageMirroring: return "imageMirroring" case .labelNamespace: return "labelNamespace" case .labelIndex: return "labelIndex" case .active: return "active" case .currentAirPurifierState: return "currentAirPurifierState" case .targetAirPurifierState: return "targetAirPurifierState" case .currentFanState: return "currentFanState" case .currentHeaterCoolerState: return "currentHeaterCoolerState" case .currentHumidifierDehumidifierState: return "currentHumidifierDehumidifierState" case .currentSlatState: return "currentSlatState" case .waterLevel: return "waterLevel" case .filterChangeIndication: return "filterChangeIndication" case .filterLifeLevel: return "filterLifeLevel" case .filterResetChangeIndication: return "filterResetChangeIndication" case .lockPhysicalControls: return "lockPhysicalControls" case .swingMode: return "swingMode" case .targetHeaterCoolerState: return "targetHeaterCoolerState" case .targetHumidifierDehumidifierState: return "targetHumidifierDehumidifierState" case .targetFanState: return "targetFanState" case .slatType: return "slatType" case .currentTilt: return "currentTilt" case .targetTilt: return "targetTilt" case .ozoneDensity: return "ozoneDensity" case .nitrogenDioxideDensity: return "nitrogenDioxideDensity" case .sulphurDioxideDensity: return "sulphurDioxideDensity" case .pm25Density: return "PM2_5Density" case .pm10Density: return "PM10Density" case .volatileOrganicCompoundDensity: return "volatileOrganicCompoundDensity" case .dehumidifierThreshold: return "dehumidifierThreshold" case .humidifierThreshold: return "humidifierThreshold" case .colorTemperature: return "colorTemperature" } } }
mit
0fc9aef5657eceafb090f97daaf0c676
50.442935
111
0.762506
5.013506
false
true
false
false
peaks-cc/iOS11_samplecode
chapter_14/AirPlay2/AirPlay2Test/SampleBufferAudioPlayer.swift
1
7899
// // AirPlay.swift // AirPlay2Test // // Created by 7gano on 2017/07/28. // Copyright © 2017 ROLLCAKE. All rights reserved. // import UIKit import AVFoundation func createFloat32CMAudioFormatDescription() -> CMAudioFormatDescription { var asbd = AudioStreamBasicDescription() asbd.mFormatID = kAudioFormatLinearPCM asbd.mFormatFlags = kAudioFormatFlagsNativeFloatPacked asbd.mSampleRate = 44100 asbd.mBitsPerChannel = 32 asbd.mFramesPerPacket = 1 asbd.mChannelsPerFrame = 2 asbd.mBytesPerFrame = asbd.mBitsPerChannel / 8 * asbd.mChannelsPerFrame asbd.mBytesPerPacket = asbd.mBytesPerFrame * asbd.mFramesPerPacket var formatDescription:CMAudioFormatDescription? CMAudioFormatDescriptionCreate(nil, &asbd, 0, nil, 0, nil, nil, &formatDescription) return formatDescription! } let processingFrameLength:UInt32 = 4096 class SampleBufferAudioPlayer: NSObject { //audioRendererとrenderSynchronizerをインスタンス変数として用意しておく let audioRenderer = AVSampleBufferAudioRenderer() let renderSynchronizer = AVSampleBufferRenderSynchronizer() //オーディオ・レンダリング処理はサブスレッド内で行う必要があるため、専用のserializationQueueを用意しておく let serializationQueue = DispatchQueue(label: "serialization queue") //AVAudioFileを使ってバッファを読み込む var sourceFile: AVAudioFile! //再生するオーディオのフォーマット情報。たとえばCDクオリティの場合16bit/44.1kHzのような情報を持つ。 var readingFormat: AVAudioFormat! //最終的にAudioRendererに渡すCMSampleBufferのオーディオフォーマット。 let sampleBufferformatDescription = createFloat32CMAudioFormatDescription() //現在オーディオファイルのどの位置を読み込んでいるかを保持 var currentFrame:AVAudioFrameCount = 0 //このファイルを読み込む let sourceFileURL = Bundle.main.url(forResource: "source", withExtension: "caf")! //let sourceFileURL = Bundle.main.url(forResource: "podcast #012", withExtension: "m4a")! var processingAudioBuffer:AudioBuffer = { var audioBuffer = AudioBuffer() audioBuffer.mDataByteSize = UInt32(Int(processingFrameLength * 2) * MemoryLayout<Float32>.stride) audioBuffer.mData = UnsafeMutableRawPointer.allocate(bytes: Int(audioBuffer.mDataByteSize), alignedTo: 1) audioBuffer.mNumberChannels = 2 return audioBuffer } () func convertToInterleaved(audioBufferList:UnsafeMutablePointer<AudioBufferList>, frameLength:UInt32) -> AudioBufferList{ let mutableAudioBufferListPointer = UnsafeMutableAudioBufferListPointer(audioBufferList) let audioBufferL = mutableAudioBufferListPointer[0] let audioBufferR = mutableAudioBufferListPointer[1] let p:UnsafeMutablePointer<Float32> = processingAudioBuffer.mData!.bindMemory(to: Float32.self, capacity: Int(frameLength)) let pL: UnsafeMutablePointer<Float32> = audioBufferL.mData!.bindMemory(to: Float32.self, capacity: Int(frameLength)) let pR: UnsafeMutablePointer<Float32> = audioBufferR.mData!.bindMemory(to: Float32.self, capacity: Int(frameLength)) processingAudioBuffer.mDataByteSize = UInt32(Int(frameLength * 2) * MemoryLayout<Float32>.stride) memset(processingAudioBuffer.mData, 0, Int(processingAudioBuffer.mDataByteSize)) var index = 0; for i in 0...frameLength - 1 { p[index] = pL[Int(i)] index += 1 p[index] = pR[Int(i)] index += 1 } let audioBufferList = AudioBufferList(mNumberBuffers: 1, mBuffers: processingAudioBuffer) return audioBufferList } override init(){ renderSynchronizer.addRenderer(audioRenderer) //AVAudioFileを使う場合、Interleavedでバッファを読み込むとBuffer数=1, チャンネル数1のバッファになってしまうので //interleaved: false = Non Interleavedで読み込む sourceFile = try! AVAudioFile(forReading: sourceFileURL, commonFormat: .pcmFormatFloat32, interleaved: false) readingFormat = sourceFile.processingFormat } func nextSampleBuffer() -> CMSampleBuffer?{ let buffer = AVAudioPCMBuffer(pcmFormat: readingFormat, frameCapacity:processingFrameLength)! do{ //オーディオファイルからAVAudioPCMBufferにデータを読み込みます。 try sourceFile.read(into: buffer, frameCount: processingFrameLength) }catch { return nil } //audioStreamBasicDescription.mSampleRate = 再生するサンプリングレートとcurrentFrame = 現在位置を考慮してCMSampleTimingInfoを作成します。 var timing = CMSampleTimingInfo(duration: CMTimeMake(1, Int32(readingFormat.sampleRate)), presentationTimeStamp: CMTimeMake(Int64(currentFrame), Int32(readingFormat.sampleRate)), decodeTimeStamp: kCMTimeInvalid) print(CMTimeGetSeconds(CMTimeMake(Int64(currentFrame), Int32(readingFormat.sampleRate)))) currentFrame += buffer.frameLength //Non Interleavedで読み込んだがAVSampleBufferAudioRendererはInterleavedのCMSampleBufferを渡すと //レンダリングエラーになるのでInterleavedに変換します var audioBufferList = convertToInterleaved(audioBufferList: buffer.mutableAudioBufferList, frameLength: buffer.frameLength) //CMSampleBufferを作成します var sampleBuffer: CMSampleBuffer? = nil CMSampleBufferCreate(nil,nil,false,nil,nil, sampleBufferformatDescription, CMItemCount(buffer.frameLength), 1, &timing, 0, nil, &sampleBuffer) //CMSampleBufferにオーディオファイルから読み込んだバッファをセットします CMSampleBufferSetDataBufferFromAudioBufferList(sampleBuffer!, kCFAllocatorDefault, kCFAllocatorDefault, 0, &audioBufferList) return sampleBuffer } func startEnqueueing() { self.audioRenderer.requestMediaDataWhenReady(on: serializationQueue) { [weak self] in guard let strongSelf = self else { return } let audioRenderer = strongSelf.audioRenderer while audioRenderer.isReadyForMoreMediaData { let sampleBuffer = strongSelf.nextSampleBuffer() if let sampleBuffer = sampleBuffer { audioRenderer.enqueue(sampleBuffer) } else { audioRenderer.stopRequestingMediaData() print(audioRenderer.status.rawValue) break } } } } func play(){ serializationQueue.async { self.startEnqueueing() self.renderSynchronizer.rate = 1.0 self.audioRenderer.volume = 1.0 } } }
mit
6b0b510de11b763ed7bcff1dc010f10f
41.733728
131
0.622819
5.06807
false
false
false
false
salesawagner/wascar
Sources/Presentation/ViewControllers/PlaceListViewController.swift
1
6796
// // PlaceListViewController.swift // wascar // // Created by Wagner Sales on 23/11/16. // Copyright © 2016 Wagner Sales. All rights reserved. // import UIKit import SwiftLocation //************************************************************************************************** // // MARK: - Constants - // //************************************************************************************************** private let kDetailSegue = "DetailSegue" private let kNoGpsSegue = "NoGpsSegue" private let kNoPlacesSegue = "NoPlacesSegue" //************************************************************************************************** // // MARK: - Definitions - // //************************************************************************************************** //************************************************************************************************** // // MARK: - Class - PlaceListViewController // //************************************************************************************************** class PlaceListViewController: WCARTableViewController { //************************************************** // MARK: - Properties //************************************************** var viewModel: PlaceListViewModel = PlaceListViewModel() var refreshControl: UIRefreshControl! var openedViewController: UIViewController? var firstTime: Bool = true //************************************************** // MARK: - Constructors //************************************************** //************************************************** // MARK: - Private Methods //************************************************** private func setupPullRefresh() { self.refreshControl = UIRefreshControl() self.refreshControl.addTarget(self, action: #selector(self.didRefresh(_:)), for: .valueChanged) self.tableView.addSubview(self.refreshControl) } fileprivate func dismissIfNeed(_ completion: Completion? = nil) { self.openedViewController?.dismiss(animated: true, completion: { self.openedViewController = nil completion?() }) } //************************************************** // MARK: - Internal Methods //************************************************** internal func loadPlaces(_ loading: Bool = true, completion: CompletionSuccess? = nil) { if loading { self.startLoading() } self.viewModel.loadPlaces { (success) in // Dismiss view controller if need self.dismissIfNeed() // No location check if !success && Location.lastLocation == nil{ self.stopLoading(hasError: false) self.performSegue(withIdentifier: kNoGpsSegue, sender: nil) return } // No places check if self.viewModel.placeCellViewModels.count == 0 { self.stopLoading(hasError: false) self.performSegue(withIdentifier: kNoPlacesSegue, sender: nil) return } self.tableView.reloadData() self.stopLoading(hasError: !success) completion?(success) } } internal func didRefresh(_ refreshControl: UIRefreshControl) { self.loadPlaces(false) { (success) in self.refreshControl.endRefreshing() } } //************************************************** // MARK: - Public Methods //************************************************** //************************************************** // MARK: - Override Public Methods //************************************************** override func viewDidLoad() { super.viewDidLoad() self.setupPullRefresh() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if self.firstTime { self.loadPlaces() self.firstTime = false } } override func setupUI() { super.setupUI() self.title = self.viewModel.title } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == kDetailSegue { if let viewController = segue.destination as? PlaceDetailViewController { if let viewModel = sender as? PlaceDetailViewModel { viewController.viewModel = viewModel } } } else if segue.identifier == kNoPlacesSegue { self.openedViewController = segue.destination if let navigation = segue.destination as? UINavigationController { if let viewController = navigation.WCARrootViewController as? NoPlacesViewController{ viewController.delegate = self viewController.title = self.viewModel.title } } } else if segue.identifier == kNoGpsSegue { self.openedViewController = segue.destination if let navigation = segue.destination as? UINavigationController { if let viewController = navigation.WCARrootViewController{ viewController.title = self.viewModel.title } } } } } //********************************************************************************************************** // // MARK: - Extension - UITableViewDataSource // //********************************************************************************************************** extension PlaceListViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.viewModel.placeCellViewModels.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell! if let myCell = tableView.dequeueReusableCell(withIdentifier: kPlaceCellIdentifier) as? PlaceCell { let placeCellViewModels = self.viewModel.placeCellViewModels let cellViewModel = placeCellViewModels[indexPath.row] myCell.setup(cellViewModel) cell = myCell } else { cell = UITableViewCell(style: .default, reuseIdentifier: kPlaceCellIdentifier) } return cell } } //********************************************************************************************************** // // MARK: - Extension - UITableViewDelegate // //********************************************************************************************************** extension PlaceListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 130 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let detailViewModels = self.viewModel.placeDetailViewModels let detailViewModel = detailViewModels[indexPath.row] self.performSegue(withIdentifier: kDetailSegue, sender: detailViewModel) } } //********************************************************************************************************** // // MARK: - Extension - UITableViewDelegate // //********************************************************************************************************** extension PlaceListViewController: NoPlacesViewControllerDelegate { func loadButtonTapped() { self.dismissIfNeed { self.loadPlaces() } } }
mit
ba5d4e33f9f998c9abe56307ded100e9
31.357143
108
0.528477
5.300312
false
false
false
false
mobilabsolutions/jenkins-ios
JenkinsiOS/Service/URLSessionTaskController.swift
1
1029
// // URLSessionTaskController.swift // JenkinsiOS // // Created by Robert on 01.12.16. // Copyright © 2016 MobiLab Solutions. All rights reserved. // import Foundation @objc protocol URLSessionTaskControllerDelegate { @objc optional func didCancel(task: URLSessionTask) @objc optional func didSuspend(task: URLSessionTask) @objc optional func didResume(task: URLSessionTask) } class URLSessionTaskController { var delegate: URLSessionTaskControllerDelegate? private var task: URLSessionTask init(task: URLSessionTask, delegate: URLSessionTaskControllerDelegate? = nil) { self.task = task self.delegate = delegate } func cancelTask() { if task.state == .running { suspendTask() } task.cancel() delegate?.didCancel?(task: task) } func suspendTask() { task.suspend() delegate?.didSuspend?(task: task) } func resumeTask() { task.resume() delegate?.didResume?(task: task) } }
mit
679c52c67d3589687119557776a4c019
22.363636
83
0.655642
4.568889
false
false
false
false
DarielChen/DemoCode
iOS动画指南/iOS动画指南 - 3.Layer Animations的进阶使用/4.PullToRefresh/PullToRefresh/RefreshView.swift
1
4868
// // RefreshView.swift // PullToRefresh // // Created by Dariel on 16/6/22. // Copyright © 2016年 Dariel. All rights reserved. // import UIKit protocol RefreshViewDelegate { func refreshViewDidRefresh(refreshView: RefreshView) } class RefreshView: UIView, UIScrollViewDelegate { var delegate: RefreshViewDelegate? var scrollView: UIScrollView? var progress: CGFloat = 0.0 var refreshing:Bool = false var isRefreshing = false let ovalShapeLayer: CAShapeLayer = CAShapeLayer() let airplaneLayer: CALayer = CALayer() init(frame: CGRect, scrollView: UIScrollView) { super.init(frame: frame) self.scrollView = scrollView backgroundColor = UIColor(red: 0, green: 155/255.0, blue: 226/255.0, alpha: 1) // 白色的圈 ovalShapeLayer.strokeColor = UIColor.whiteColor().CGColor ovalShapeLayer.fillColor = UIColor.clearColor().CGColor ovalShapeLayer.lineWidth = 4.0 ovalShapeLayer.lineDashPattern = [2, 3] let refreshRadius = frame.size.height/2 * 0.8 ovalShapeLayer.path = UIBezierPath(ovalInRect: CGRect(x: frame.size.width/2 - refreshRadius, y:frame.size.height/2 - refreshRadius , width: 2*refreshRadius, height: 2*refreshRadius)).CGPath layer.addSublayer(ovalShapeLayer) // 添加飞机图片 let airplaneImage = UIImage(named: "airplane") airplaneLayer.contents = airplaneImage?.CGImage airplaneLayer.bounds = CGRect(x: 0.0, y: 0.0, width: (airplaneImage?.size.width)!, height: airplaneImage!.size.height) airplaneLayer.position = CGPoint(x: frame.size.width/2 + frame.size.height/2 * 0.8, y: frame.size.height/2) layer.addSublayer(airplaneLayer) airplaneLayer.opacity = 1.0 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func scrollViewDidScroll(scrollView: UIScrollView) { let offsetY = CGFloat( max(-(scrollView.contentOffset.y + scrollView.contentInset.top), 0.0)) self.progress = min(max( offsetY / frame.size.height, 0.0), 1.0) if !refreshing { redrawFromProgress(progress) } } func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { if !refreshing && self.progress >= 1.0 { delegate?.refreshViewDidRefresh(self) beginRefreshing() } } // 开始刷新 func beginRefreshing() { isRefreshing = true UIView.animateWithDuration(0.3, animations: { var newInsets = self.scrollView!.contentInset newInsets.top += self.frame.size.height self.scrollView!.contentInset = newInsets }) let strokeStartAnimation = CABasicAnimation(keyPath: "strokeStart") strokeStartAnimation.fromValue = -0.5 strokeStartAnimation.toValue = 1.0 let strokeEndAnimation = CABasicAnimation(keyPath: "strokeEnd") strokeEndAnimation.fromValue = 0.0 strokeEndAnimation.toValue = 1.0 let strokeAnimationGroup = CAAnimationGroup() strokeAnimationGroup.duration = 1.5 strokeAnimationGroup.repeatDuration = 5.0 strokeAnimationGroup.animations = [strokeStartAnimation, strokeEndAnimation] ovalShapeLayer.addAnimation(strokeAnimationGroup, forKey: nil) let flightAnimation = CAKeyframeAnimation(keyPath: "position") flightAnimation.path = ovalShapeLayer.path flightAnimation.calculationMode = kCAAnimationPaced let airplaneOrientationAnimation = CABasicAnimation(keyPath: "transform.rotation") airplaneOrientationAnimation.fromValue = 0 airplaneOrientationAnimation.toValue = 2 * M_PI let flightAnimationGroup = CAAnimationGroup() flightAnimationGroup.duration = 1.5 flightAnimationGroup.repeatDuration = 5.0 flightAnimationGroup.animations = [flightAnimation, airplaneOrientationAnimation] airplaneLayer.addAnimation(flightAnimationGroup, forKey: nil) } // 结束刷新 func endRefreshing() { isRefreshing = false UIView.animateWithDuration(0.3, delay:0.0, options: .CurveEaseOut ,animations: { var newInsets = self.scrollView!.contentInset newInsets.top -= self.frame.size.height self.scrollView!.contentInset = newInsets }, completion: {_ in }) } func redrawFromProgress(progress: CGFloat) { ovalShapeLayer.strokeEnd = progress airplaneLayer.opacity = 1 } }
mit
1864862e1b3d78f8c9a18ca15b8d0505
33.492857
197
0.648581
4.937628
false
false
false
false
brentdax/swift
test/SILOptimizer/sil_combine_protocol_conf.swift
1
14759
// RUN: %target-swift-frontend %s -O -wmo -emit-sil -Xllvm -sil-disable-pass=DeadFunctionElimination | %FileCheck %s // case 1: class protocol -- should optimize internal protocol SomeProtocol : class { func foo(x:SomeProtocol) -> Int func foo_internal() -> Int } internal class SomeClass: SomeProtocol { func foo_internal() ->Int { return 10 } func foo(x:SomeProtocol) -> Int { return x.foo_internal() } } // case 2: non-class protocol -- should optimize internal protocol SomeNonClassProtocol { func bar(x:SomeNonClassProtocol) -> Int func bar_internal() -> Int } internal class SomeNonClass: SomeNonClassProtocol { func bar_internal() -> Int { return 20 } func bar(x:SomeNonClassProtocol) -> Int { return x.bar_internal() } } // case 3: class conforming to protocol has a derived class -- should not optimize internal protocol DerivedProtocol { func foo() -> Int } internal class SomeDerivedClass: DerivedProtocol { func foo() -> Int { return 20 } } internal class SomeDerivedClassDerived: SomeDerivedClass { } // case 3: public protocol -- should not optimize public protocol PublicProtocol { func foo() -> Int } internal class SomePublicClass: PublicProtocol { func foo() -> Int { return 20 } } // case 4: Chain of protocols P1->P2->C -- optimize internal protocol MultiProtocolChain { func foo() -> Int } internal protocol RefinedMultiProtocolChain : MultiProtocolChain { func bar() -> Int } internal class SomeMultiClass: RefinedMultiProtocolChain { func foo() -> Int { return 20 } func bar() -> Int { return 30 } } // case 5: Generic conforming type -- should not optimize internal protocol GenericProtocol { func foo() -> Int } internal class GenericClass<T> : GenericProtocol { var items = [T]() func foo() -> Int { return items.count } } // case 6: two classes conforming to protocol internal protocol MultipleConformanceProtocol { func foo() -> Int } internal class Klass1: MultipleConformanceProtocol { func foo() -> Int { return 20 } } internal class Klass2: MultipleConformanceProtocol { func foo() -> Int { return 30 } } internal class Other { let x:SomeProtocol let y:SomeNonClassProtocol let z:DerivedProtocol let p:PublicProtocol let q:MultiProtocolChain let r:GenericProtocol let s:MultipleConformanceProtocol init(x:SomeProtocol, y:SomeNonClassProtocol, z:DerivedProtocol, p:PublicProtocol, q:MultiProtocolChain, r:GenericProtocol, s:MultipleConformanceProtocol) { self.x = x; self.y = y; self.z = z; self.p = p; self.q = q; self.r = r; self.s = s; } // CHECK-LABEL: sil hidden [noinline] @$s25sil_combine_protocol_conf5OtherC11doWorkClassSiyF : $@convention(method) (@guaranteed Other) -> Int { // CHECK: bb0 // CHECK: debug_value // CHECK: integer_literal // CHECK: [[R1:%.*]] = ref_element_addr %0 : $Other, #Other.z // CHECK: [[O1:%.*]] = open_existential_addr immutable_access [[R1]] : $*DerivedProtocol to $*@opened("{{.*}}") DerivedProtocol // CHECK: [[W1:%.*]] = witness_method $@opened("{{.*}}") DerivedProtocol, #DerivedProtocol.foo!1 : <Self where Self : DerivedProtocol> (Self) -> () -> Int, [[O1]] : $*@opened("{{.*}}") DerivedProtocol : $@convention(witness_method: DerivedProtocol) <τ_0_0 where τ_0_0 : DerivedProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: apply [[W1]]<@opened("{{.*}}") DerivedProtocol>([[O1]]) : $@convention(witness_method: DerivedProtocol) <τ_0_0 where τ_0_0 : DerivedProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: struct_extract // CHECK: integer_literal // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: [[R2:%.*]] = ref_element_addr %0 : $Other, #Other.p // CHECK: [[O2:%.*]] = open_existential_addr immutable_access [[R2]] : $*PublicProtocol to $*@opened("{{.*}}") PublicProtocol // CHECK: [[W2:%.*]] = witness_method $@opened("{{.*}}") PublicProtocol, #PublicProtocol.foo!1 : <Self where Self : PublicProtocol> (Self) -> () -> Int, [[O2]] : $*@opened("{{.*}}") PublicProtocol : $@convention(witness_method: PublicProtocol) <τ_0_0 where τ_0_0 : PublicProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: apply [[W2]]<@opened("{{.*}}") PublicProtocol>([[O2]]) : $@convention(witness_method: PublicProtocol) <τ_0_0 where τ_0_0 : PublicProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: struct_extract // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: integer_literal // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: [[R3:%.*]] = ref_element_addr %0 : $Other, #Other.r // CHECK: [[O3:%.*]] = open_existential_addr immutable_access [[R3]] : $*GenericProtocol to $*@opened("{{.*}}") GenericProtocol // CHECK: [[W3:%.*]] = witness_method $@opened("{{.*}}") GenericProtocol, #GenericProtocol.foo!1 : <Self where Self : GenericProtocol> (Self) -> () -> Int, [[O3]] : $*@opened("{{.*}}") GenericProtocol : $@convention(witness_method: GenericProtocol) <τ_0_0 where τ_0_0 : GenericProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: apply [[W3]]<@opened("{{.*}}") GenericProtocol>([[O3]]) : $@convention(witness_method: GenericProtocol) <τ_0_0 where τ_0_0 : GenericProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: struct_extract // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: [[R4:%.*]] = ref_element_addr %0 : $Other, #Other.s // CHECK: [[O4:%.*]] = open_existential_addr immutable_access %36 : $*MultipleConformanceProtocol to $*@opened("{{.*}}") MultipleConformanceProtocol // CHECK: [[W4:%.*]] = witness_method $@opened("{{.*}}") MultipleConformanceProtocol, #MultipleConformanceProtocol.foo!1 : <Self where Self : MultipleConformanceProtocol> (Self) -> () -> Int, %37 : $*@opened("{{.*}}") MultipleConformanceProtocol : $@convention(witness_method: MultipleConformanceProtocol) <τ_0_0 where τ_0_0 : MultipleConformanceProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: apply [[W4]]<@opened("{{.*}}") MultipleConformanceProtocol>(%37) : $@convention(witness_method: MultipleConformanceProtocol) <τ_0_0 where τ_0_0 : MultipleConformanceProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: struct_extract // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: struct // CHECK: return // CHECK: } // end sil function '$s25sil_combine_protocol_conf5OtherC11doWorkClassSiyF' @inline(never) func doWorkClass () ->Int { return self.x.foo(x:self.x) // optimize + self.y.bar(x:self.y) // optimize + self.z.foo() // do not optimize + self.p.foo() // do not optimize + self.q.foo() // optimize + self.r.foo() // do not optimize + self.s.foo() // do not optimize } } // case 1: struct -- optimize internal protocol PropProtocol { var val: Int { get set } } internal struct PropClass: PropProtocol { var val: Int init(val: Int) { self.val = val } } // case 2: generic struct -- do not optimize internal protocol GenericPropProtocol { var val: Int { get set } } internal struct GenericPropClass<T>: GenericPropProtocol { var val: Int init(val: Int) { self.val = val } } // case 3: nested struct -- optimize internal protocol NestedPropProtocol { var val: Int { get } } struct Outer { struct Inner : NestedPropProtocol { var val: Int init(val: Int) { self.val = val } } } // case 4: generic nested struct -- do not optimize internal protocol GenericNestedPropProtocol { var val: Int { get } } struct GenericOuter<T> { struct GenericInner : GenericNestedPropProtocol { var val: Int init(val: Int) { self.val = val } } } internal class OtherClass { var arg1: PropProtocol var arg2: GenericPropProtocol var arg3: NestedPropProtocol var arg4: GenericNestedPropProtocol init(arg1:PropProtocol, arg2:GenericPropProtocol, arg3: NestedPropProtocol, arg4: GenericNestedPropProtocol) { self.arg1 = arg1 self.arg2 = arg2 self.arg3 = arg3 self.arg4 = arg4 } // CHECK-LABEL: sil hidden [noinline] @$s25sil_combine_protocol_conf10OtherClassC12doWorkStructSiyF : $@convention(method) (@guaranteed OtherClass) -> Int { // CHECK: bb0 // CHECK: debug_value // CHECK: [[A1:%.*]] = alloc_stack $PropProtocol // CHECK: [[R1:%.*]] = ref_element_addr %0 : $OtherClass, #OtherClass.arg1 // CHECK: copy_addr [[R1]] to [initialization] [[A1]] : $*PropProtocol // CHECK: [[O1:%.*]] = open_existential_addr immutable_access [[A1]] : $*PropProtocol to $*@opened("{{.*}}") PropProtocol // CHECK: [[U1:%.*]] = unchecked_addr_cast [[O1]] : $*@opened("{{.*}}") PropProtocol to $*PropClass // CHECK: [[S1:%.*]] = struct_element_addr [[U1]] : $*PropClass, #PropClass.val // CHECK: [[S11:%.*]] = struct_element_addr [[S1]] : $*Int, #Int._value // CHECK: load [[S11]] // CHECK: destroy_addr [[A1]] : $*PropProtocol // CHECK: [[A2:%.*]] = alloc_stack $GenericPropProtocol // CHECK: [[R2:%.*]] = ref_element_addr %0 : $OtherClass, #OtherClass.arg2 // CHECK: copy_addr [[R2]] to [initialization] [[A2]] : $*GenericPropProtocol // CHECK: [[O2:%.*]] = open_existential_addr immutable_access [[A2]] : $*GenericPropProtocol to $*@opened("{{.*}}") GenericPropProtocol // CHECK: [[W2:%.*]] = witness_method $@opened("{{.*}}") GenericPropProtocol, #GenericPropProtocol.val!getter.1 : <Self where Self : GenericPropProtocol> (Self) -> () -> Int, [[O2]] : $*@opened("{{.*}}") GenericPropProtocol : $@convention(witness_method: GenericPropProtocol) <τ_0_0 where τ_0_0 : GenericPropProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: apply [[W2]]<@opened("{{.*}}") GenericPropProtocol>([[O2]]) : $@convention(witness_method: GenericPropProtocol) <τ_0_0 where τ_0_0 : GenericPropProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: destroy_addr [[A2]] : $*GenericPropProtocol // CHECK: struct_extract // CHECK: integer_literal // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: dealloc_stack [[A2]] : $*GenericPropProtocol // CHECK: dealloc_stack [[A1]] : $*PropProtocol // CHECK: [[A4:%.*]] = alloc_stack $NestedPropProtocol // CHECK: [[R4:%.*]] = ref_element_addr %0 : $OtherClass, #OtherClass.arg3 // CHECK: copy_addr [[R4]] to [initialization] [[A4]] : $*NestedPropProtocol // CHECK: [[O4:%.*]] = open_existential_addr immutable_access [[A4]] : $*NestedPropProtocol to $*@opened("{{.*}}") NestedPropProtocol // CHECK: [[U4:%.*]] = unchecked_addr_cast [[O4]] : $*@opened("{{.*}}") NestedPropProtocol to $*Outer.Inner // CHECK: [[S4:%.*]] = struct_element_addr [[U4]] : $*Outer.Inner, #Outer.Inner.val // CHECK: [[S41:%.*]] = struct_element_addr [[S4]] : $*Int, #Int._value // CHECK: load [[S41]] // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: dealloc_stack [[A4]] : $*NestedPropProtocol // CHECK: [[A5:%.*]] = alloc_stack $GenericNestedPropProtocol // CHECK: [[R5:%.*]] = ref_element_addr %0 : $OtherClass, #OtherClass.arg4 // CHECK: copy_addr [[R5]] to [initialization] [[A5]] : $*GenericNestedPropProtocol // CHECK: [[O5:%.*]] = open_existential_addr immutable_access [[A5]] : $*GenericNestedPropProtocol to $*@opened("{{.*}}") GenericNestedPropProtocol // CHECK: [[W5:%.*]] = witness_method $@opened("{{.*}}") GenericNestedPropProtocol, #GenericNestedPropProtocol.val!getter.1 : <Self where Self : GenericNestedPropProtocol> (Self) -> () -> Int, [[O5:%.*]] : $*@opened("{{.*}}") GenericNestedPropProtocol : $@convention(witness_method: GenericNestedPropProtocol) <τ_0_0 where τ_0_0 : GenericNestedPropProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: apply [[W5]]<@opened("{{.*}}") GenericNestedPropProtocol>([[O5]]) : $@convention(witness_method: GenericNestedPropProtocol) <τ_0_0 where τ_0_0 : GenericNestedPropProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: struct_extract // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: struct // CHECK: destroy_addr [[A5]] : $*GenericNestedPropProtocol // CHECK: dealloc_stack [[A5]] : $*GenericNestedPropProtocol // CHECK: return // CHECK: } // end sil function '$s25sil_combine_protocol_conf10OtherClassC12doWorkStructSiyF' @inline(never) func doWorkStruct () -> Int{ return self.arg1.val // optimize + self.arg2.val // do not optimize + self.arg3.val // optimize + self.arg4.val // do not optimize } } // case 1: enum -- optimize internal protocol AProtocol { var val: Int { get } } internal enum AnEnum : AProtocol { case avalue var val: Int { switch self { case .avalue: return 10 } } } // case 2: generic enum -- do not optimize internal protocol AGenericProtocol { var val: Int { get } } internal enum AGenericEnum<T> : AGenericProtocol { case avalue var val: Int { switch self { case .avalue: return 10 } } } internal class OtherKlass { var arg1: AProtocol var arg2: AGenericProtocol init(arg1:AProtocol, arg2:AGenericProtocol) { self.arg1 = arg1 self.arg2 = arg2 } // CHECK-LABEL: sil hidden [noinline] @$s25sil_combine_protocol_conf10OtherKlassC10doWorkEnumSiyF : $@convention(method) (@guaranteed OtherKlass) -> Int { // CHECK: bb0 // CHECK: debug_value // CHECK: integer_literal // CHECK: [[A1:%.*]] = alloc_stack $AGenericProtocol // CHECK: [[R1:%.*]] = ref_element_addr %0 : $OtherKlass, #OtherKlass.arg2 // CHECK: copy_addr [[R1]] to [initialization] [[A1]] : $*AGenericProtocol // CHECK: [[O1:%.*]] = open_existential_addr immutable_access [[A1]] : $*AGenericProtocol to $*@opened("{{.*}}") AGenericProtocol // CHECK: [[W1:%.*]] = witness_method $@opened("{{.*}}") AGenericProtocol, #AGenericProtocol.val!getter.1 : <Self where Self : AGenericProtocol> (Self) -> () -> Int, [[O1]] : $*@opened("{{.*}}") AGenericProtocol : $@convention(witness_method: AGenericProtocol) <τ_0_0 where τ_0_0 : AGenericProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: apply [[W1]]<@opened("{{.*}}") AGenericProtocol>([[O1]]) : $@convention(witness_method: AGenericProtocol) <τ_0_0 where τ_0_0 : AGenericProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: struct_extract // CHECK: integer_literal // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: struct // CHECK: destroy_addr [[A1]] : $*AGenericProtocol // CHECK: dealloc_stack [[A1]] : $*AGenericProtocol // CHECK: return // CHECK: } // end sil function '$s25sil_combine_protocol_conf10OtherKlassC10doWorkEnumSiyF' @inline(never) func doWorkEnum() -> Int { return self.arg1.val // optimize + self.arg2.val // do not optimize } }
apache-2.0
69649660f87a7f2c403ff88e50260edf
39.431319
388
0.656452
3.711728
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/TableviewCells/YesterdailyTaskCell.swift
1
4688
// // File.swift // Habitica // // Created by Phillip on 08.06.17. // Copyright © 2017 HabitRPG Inc. All rights reserved. // import UIKit import Habitica_Models import PinLayout import Down class YesterdailyTaskCell: UITableViewCell { @IBOutlet weak var wrapperView: UIView! @IBOutlet weak var checkbox: CheckboxView! @IBOutlet weak var titleTextView: UILabel! var onChecklistItemChecked: ((ChecklistItemProtocol) -> Void)? var checklistItems: [(UIView, ChecklistItemProtocol)] = [] override func awakeFromNib() { super.awakeFromNib() selectionStyle = .none wrapperView.layer.borderWidth = 1 let theme = ThemeService.shared.theme wrapperView.layer.borderColor = theme.separatorColor.cgColor wrapperView.backgroundColor = theme.contentBackgroundColor } func configure(task: TaskProtocol) { backgroundColor = ThemeService.shared.theme.windowBackgroundColor checkbox.configure(task: task) titleTextView.attributedText = try? Down(markdownString: task.text?.unicodeEmoji ?? "").toHabiticaAttributedString() checklistItems.forEach({ (view, _) in view.removeFromSuperview() }) checklistItems = [] for checklistItem in task.checklist { if let view = UIView.fromNib(nibName: "YesterdailyChecklistItem") { view.isUserInteractionEnabled = true view.backgroundColor = ThemeService.shared.theme.contentBackgroundColor let label = view.viewWithTag(2) as? UILabel label?.attributedText = try? Down(markdownString: checklistItem.text?.unicodeEmoji ?? "").toHabiticaAttributedString() let checkbox = view.viewWithTag(1) as? CheckboxView checkbox?.configure(checklistItem: checklistItem, withTitle: false, checkColor: .forTaskValueDarkest(Int(task.value)), checkboxColor: .forTaskValueLight(Int(task.value)), taskType: task.type) checkbox?.backgroundColor = ThemeService.shared.theme.windowBackgroundColor checkbox?.wasTouched = {[weak self] in if let checked = self?.onChecklistItemChecked { checked(checklistItem) } } wrapperView.addSubview(view) checklistItems.append((view, checklistItem)) let recognizer = UITapGestureRecognizer(target: self, action: #selector(YesterdailyTaskCell.handleChecklistTap(recognizer:))) recognizer.cancelsTouchesInView = true view.addGestureRecognizer(recognizer) } } } override func layoutSubviews() { super.layoutSubviews() layout() } override func sizeThatFits(_ size: CGSize) -> CGSize { contentView.pin.width(size.width) layout() return CGSize(width: contentView.frame.width, height: wrapperView.frame.height + 8) } private func layout() { wrapperView.pin.horizontally() checkbox.pin.width(40).start().top() titleTextView.pin.after(of: checkbox).marginStart(10).end(8).top().sizeToFit(.width) let textHeight = max(titleTextView.frame.size.height + 8, 48) checkbox.pin.height(textHeight) titleTextView.pin.height(textHeight) var checklistHeight = CGFloat(0) var topEdge = titleTextView.edge.bottom for (view, _) in checklistItems { guard let label = view.viewWithTag(2) as? UILabel else { continue } guard let itemCheckbox = view.viewWithTag(1) as? CheckboxView else { continue } view.pin.top(to: topEdge).horizontally() itemCheckbox.pin.width(40).start().top() label.pin.after(of: itemCheckbox).marginStart(10).end(8).top().sizeToFit(.width) let itemHeight = max(label.frame.size.height + 8, 40) label.pin.height(itemHeight) itemCheckbox.pin.height(itemHeight) view.pin.height(itemHeight) topEdge = view.edge.bottom checklistHeight += view.frame.size.height } let height = textHeight + checklistHeight + 1 wrapperView.pin.height(height).top(4) } @objc func handleChecklistTap(recognizer: UITapGestureRecognizer) { if let (_, checklistItem) = checklistItems.first(where: { (view, _) -> Bool in return view == recognizer.view }) { if let checked = onChecklistItemChecked { checked(checklistItem) } return } } }
gpl-3.0
d08235c58944d36e6240d8c80df61d9d
38.720339
207
0.62748
4.954545
false
false
false
false
ingresse/ios-sdk
IngresseSDKTests/Services/UserServiceTests.swift
1
18288
// // Copyright © 2018 Ingresse. All rights reserved. // import XCTest @testable import IngresseSDK class UserServiceTests: XCTestCase { var restClient: MockClient! var client: IngresseClient! var service: UserService! override func setUp() { super.setUp() restClient = MockClient() client = IngresseClient(apiKey: "1234", userAgent: "", restClient: restClient) service = IngresseService(client: client).user } } // MARK: - User Events extension UserServiceTests { func testGetUserEvents() { // Given let asyncExpectation = expectation(description: "userEvents") var response = [String: Any]() response["data"] = [["id": 1]] restClient.response = response restClient.shouldFail = false let delegate = UserEventsDownloaderDelegateSpy() delegate.asyncExpectation = asyncExpectation // When service.getEvents(fromUsertoken: "1234-token", page: 1, delegate: delegate) // Then waitForExpectations(timeout: 1) { (_) in XCTAssert(delegate.didDownloadEventsCalled) XCTAssertNotNil(delegate.resultData) XCTAssertEqual(delegate.resultData?[0]["id"] as? Int, 1) } } func testGetUserEventsWrongData() { // Given let asyncExpectation = expectation(description: "userEvents") var response = [String: Any]() response["data"] = nil restClient.response = response restClient.shouldFail = false let delegate = UserEventsDownloaderDelegateSpy() delegate.asyncExpectation = asyncExpectation // When service.getEvents(fromUsertoken: "1234-token", page: 1, delegate: delegate) // Then waitForExpectations(timeout: 1) { (_) in XCTAssert(delegate.didFailDownloadEventsCalled) XCTAssertNotNil(delegate.syncError) let defaultError = APIError.getDefaultError() XCTAssertEqual(delegate.syncError?.code, defaultError.code) XCTAssertEqual(delegate.syncError?.message, defaultError.message) } } func testGetUserEventsFail() { // Given let asyncExpectation = expectation(description: "userEvents") let error = APIError() error.code = 1 error.message = "message" error.category = "category" restClient.error = error restClient.shouldFail = true let delegate = UserEventsDownloaderDelegateSpy() delegate.asyncExpectation = asyncExpectation // When service.getEvents(fromUsertoken: "1234-token", page: 1, delegate: delegate) // Then waitForExpectations(timeout: 1) { (_) in XCTAssert(delegate.didFailDownloadEventsCalled) XCTAssertNotNil(delegate.syncError) XCTAssertEqual(delegate.syncError?.code, 1) XCTAssertEqual(delegate.syncError?.message, "message") XCTAssertEqual(delegate.syncError?.category, "category") } } } // MARK: - Create Account extension UserServiceTests { func testCreateAccount() { // Given let asyncExpectation = expectation(description: "createAccount") var response = [String: Any]() response["status"] = 1 response["data"] = [ "userId": 1, "token": "1-token", "authToken": "1-authToken" ] restClient.response = response restClient.shouldFail = false var success = false var result: IngresseUser? var request = Request.Auth.SignUp() request.name = "name lastname" request.phone = "phone" request.document = "cpf" request.email = "email" request.password = "password" // When service.createAccount( request: request, onSuccess: { (user) in success = true result = user asyncExpectation.fulfill() }, onError: { (_) in }) // Then waitForExpectations(timeout: 1) { (_) in XCTAssertTrue(success) XCTAssertNotNil(result) XCTAssertEqual(result?.userId, 1) } } func testCreateAccountNoStatus() { // Given let asyncExpectation = expectation(description: "createAccount") var response = [String: Any]() response["data"] = [ "userId": 1, "token": "1-token" ] restClient.response = response restClient.shouldFail = false var success = false var apiError: APIError? var request = Request.Auth.SignUp() request.name = "name lastname" request.phone = "phone" request.document = "cpf" request.email = "email" request.password = "password" // When service.createAccount( request: request, onSuccess: { (_) in }, onError: { (error) in success = false apiError = error asyncExpectation.fulfill() }) // Then waitForExpectations(timeout: 1) { (_) in XCTAssertFalse(success) XCTAssertNotNil(apiError) let defaultError = APIError.getDefaultError() XCTAssertEqual(apiError?.code, defaultError.code) XCTAssertEqual(apiError?.message, defaultError.message) } } func testCreateAccountNoMessage() { // Given let asyncExpectation = expectation(description: "createAccount") var response = [String: Any]() response["status"] = 0 restClient.response = response restClient.shouldFail = false var success = false var apiError: APIError? var request = Request.Auth.SignUp() request.name = "name lastname" request.phone = "phone" request.document = "cpf" request.email = "email" request.password = "password" // When service.createAccount( request: request, onSuccess: { (_) in }, onError: { (error) in success = false apiError = error asyncExpectation.fulfill() }) // Then waitForExpectations(timeout: 1) { (_) in XCTAssertFalse(success) XCTAssertNotNil(apiError) let defaultError = APIError.getDefaultError() XCTAssertEqual(apiError?.code, defaultError.code) XCTAssertEqual(apiError?.message, defaultError.message) } } func testCreateAccountError() { // Given let asyncExpectation = expectation(description: "createAccount") var response = [String: Any]() response["status"] = 0 response["message"] = ["name", "email"] restClient.response = response restClient.shouldFail = false var success = false var apiError: APIError? var request = Request.Auth.SignUp() request.name = "name lastname" request.phone = "phone" request.document = "cpf" request.email = "email" request.password = "password" // When service.createAccount( request: request, onSuccess: { (_) in }, onError: { (error) in success = false apiError = error asyncExpectation.fulfill() }) // Then waitForExpectations(timeout: 1) { (_) in XCTAssertFalse(success) XCTAssertNotNil(apiError) XCTAssertEqual(apiError?.code, 0) XCTAssertEqual(apiError?.title, "Verifique suas informações") XCTAssertEqual(apiError?.message, "name\nemail") } } func testCreateAccountFail() { // Given let asyncExpectation = expectation(description: "createAccount") let error = APIError() error.code = 1 error.message = "message" error.category = "category" restClient.error = error restClient.shouldFail = true var success = false var apiError: APIError? var request = Request.Auth.SignUp() request.name = "name lastname" request.phone = "phone" request.document = "cpf" request.email = "email" request.password = "password" // When service.createAccount( request: request, onSuccess: { (_) in }, onError: { (error) in success = false apiError = error asyncExpectation.fulfill() }) // Then waitForExpectations(timeout: 1) { (_) in XCTAssertFalse(success) XCTAssertNotNil(apiError) XCTAssertEqual(apiError?.code, 1) XCTAssertEqual(apiError?.message, "message") XCTAssertEqual(apiError?.category, "category") } } } // MARK: - Update basic infos extension UserServiceTests { func testUpdateBasicInfos() { // Given let asyncExpectation = expectation(description: "updateBasicInfos") var response = [String: Any]() response["status"] = 200 response["data"] = ["ddi": "ddi", "phone": "phone", "id": "id", "lastname": "lastname", "verified": "verified", "email": "email", "cpf": "cpf", "name": "name"] restClient.response = response restClient.shouldFail = false var request = Request.UpdateUser.BasicInfos() request.userId = "userId" request.userToken = "userToken" request.name = "name" request.lastname = "lastname" request.email = "email" request.phone = "phone" request.cpf = "cpf" var success = false var result: UpdatedUser? // When service.updateBasicInfos(request: request, onSuccess: { (user) in success = true result = user asyncExpectation.fulfill() }, onError: { (_) in }) // Then waitForExpectations(timeout: 1) { (_) in XCTAssertTrue(success) XCTAssertNotNil(result) XCTAssertEqual(result?.cpf, "cpf") } } func testUpdateBasicInfosFail() { // Given let asyncExpectation = expectation(description: "updateBasicInfos") let error = APIError() error.code = 1 error.message = "message" error.category = "category" restClient.error = error restClient.shouldFail = true var request = Request.UpdateUser.BasicInfos() request.userId = "userId" request.userToken = "userToken" request.name = "name" request.lastname = "lastname" request.email = "email" request.phone = "phone" request.cpf = "cpf" var success = false var apiError: APIError? // When service.updateBasicInfos(request: request, onSuccess: {_ in }, onError: { (error) in success = false apiError = error asyncExpectation.fulfill() }) // Then waitForExpectations(timeout: 1) { (_) in XCTAssertFalse(success) XCTAssertNotNil(apiError) XCTAssertEqual(apiError?.code, 1) XCTAssertEqual(apiError?.message, "message") XCTAssertEqual(apiError?.category, "category") } } func testUpdateBasicInfosWithWrongResponse() { // Given let asyncExpectation = expectation(description: "updateBasicInfos") var response = [String: Any]() response["data"] = [] restClient.response = response restClient.shouldFail = false var request = Request.UpdateUser.BasicInfos() request.userId = "userId" request.userToken = "userToken" request.name = "name" request.lastname = "lastname" request.email = "email" request.phone = "phone" request.cpf = "cpf" var success = false var apiError: APIError? // When service.updateBasicInfos(request: request, onSuccess: {_ in }, onError: { (error) in success = false apiError = error asyncExpectation.fulfill() }) // Then waitForExpectations(timeout: 1) { (_) in XCTAssertFalse(success) XCTAssertNotNil(apiError) XCTAssertEqual(apiError?.code, APIError.getDefaultError().code) XCTAssertEqual(apiError?.message, APIError.getDefaultError().message) XCTAssertEqual(apiError?.category, APIError.getDefaultError().category) } } func testUpdateBasicInfosWithStatusZero() { // Given let asyncExpectation = expectation(description: "updateBasicInfos") var response = [String: Any]() response["data"] = [] response["status"] = 0 response["message"] = ["message"] restClient.response = response restClient.shouldFail = false var request = Request.UpdateUser.BasicInfos() request.userId = "userId" request.userToken = "userToken" request.name = "name" request.lastname = "lastname" request.email = "email" request.phone = "phone" request.cpf = "cpf" var success = false var apiError: APIError? // When service.updateBasicInfos(request: request, onSuccess: {_ in }, onError: { (error) in success = false apiError = error asyncExpectation.fulfill() }) // Then waitForExpectations(timeout: 1) { (_) in XCTAssertFalse(success) XCTAssertNotNil(apiError) XCTAssertEqual(apiError?.code, 0) XCTAssertEqual(apiError?.message, "message") XCTAssertEqual(apiError?.category, "") } } func testUpdateBasicInfosWithStatusZeroWrongMessage() { // Given let asyncExpectation = expectation(description: "updateBasicInfos") var response = [String: Any]() response["data"] = [] response["status"] = 0 response["message"] = [1] restClient.response = response restClient.shouldFail = false var request = Request.UpdateUser.BasicInfos() request.userId = "userId" request.userToken = "userToken" request.name = "name" request.lastname = "lastname" request.email = "email" request.phone = "phone" request.cpf = "cpf" var success = false var apiError: APIError? // When service.updateBasicInfos(request: request, onSuccess: {_ in }, onError: { (error) in success = false apiError = error asyncExpectation.fulfill() }) // Then waitForExpectations(timeout: 1) { (_) in XCTAssertFalse(success) XCTAssertNotNil(apiError) XCTAssertEqual(apiError?.code, APIError.getDefaultError().code) XCTAssertEqual(apiError?.message, APIError.getDefaultError().message) XCTAssertEqual(apiError?.category, APIError.getDefaultError().category) } } } // MARK: - Change picture extension UserServiceTests { func testChangePicture() { // Given let asyncExpectation = expectation(description: "changePicture") var response = [String: Any]() response["status"] = 200 response["data"] = ["ddi": "ddi", "phone": "phone", "id": "id", "lastname": "lastname", "verified": "verified", "email": "email", "cpf": "cpf", "name": "name"] restClient.response = response restClient.shouldFail = false var success = false // When service.changePicture(userId: "userId", userToken: "userToken", imageData: "imageData", onSuccess: { success = true asyncExpectation.fulfill() }, onError: { (_) in }) // Then waitForExpectations(timeout: 1) { (_) in XCTAssertTrue(success) } } func testChangePictureFail() { // Given let asyncExpectation = expectation(description: "changePicture") let error = APIError() error.code = 1 error.message = "message" error.category = "category" restClient.error = error restClient.shouldFail = true var success = false var apiError: APIError? // When service.changePicture(userId: "userId", userToken: "userToken", imageData: "imageData", onSuccess: { }, onError: { (error) in success = false apiError = error asyncExpectation.fulfill() }) // Then waitForExpectations(timeout: 1) { (_) in XCTAssertFalse(success) XCTAssertNotNil(apiError) XCTAssertEqual(apiError?.code, 1) XCTAssertEqual(apiError?.message, "message") XCTAssertEqual(apiError?.category, "category") } } }
mit
dd202a6eb7505d0e1aab969be67a23ef
29.834739
92
0.540771
5.387448
false
false
false
false
zhugejunwei/LeetCode
101. Symmetric Tree.swift
1
1336
import Darwin public class TreeNode { public var val: Int public var left: TreeNode? public var right: TreeNode? public init(_ val: Int) { self.val = val self.left = nil self.right = nil } } // recursion, 160 ms //func isSymmetric(root: TreeNode?) -> Bool { // if root == nil { return true } // return sym(root?.left, root?.right) //} // //func sym(q: TreeNode?, _ p: TreeNode?) -> Bool { // if q == nil && p == nil { // return true // }else if q == nil || p == nil { // return false // } // return q?.val == p?.val && q?.left?.val == p?.right?.val && q?.right?.val == p?.left?.val && sym(q?.left, p?.right) && sym(q?.right, p?.left) //} // iteration, 128 ms func isSymmetric(root: TreeNode?) -> Bool { if root == nil { return true } var q = [root?.left, root?.right] while !q.isEmpty { let left = q.first!; q.removeAtIndex(0) let right = q.first!; q.removeAtIndex(0) if left == nil && right == nil { continue }else if left == nil || right == nil { return false }else if left?.val != right?.val { return false } q.append(left?.left) q.append(right?.right) q.append(left?.right) q.append(right?.left) } return true }
mit
f99c3317e882149e8309ded8026db22e
23.740741
147
0.520958
3.425641
false
false
false
false
muneebm/AsterockX
AsterockX/OrbitalViewController.swift
1
5874
// // TableViewController.swift // AsterockX // // Created by Muneeb Rahim Abdul Majeed on 1/3/16. // Copyright © 2016 beenum. All rights reserved. // import UIKit class OrbitalViewController: BaseTableViewController { struct Constants { static let CellReusableID = "OrbitalDataCell" static let OrbitID = "Orbit ID" static let OrbitDeterminationDate = "Orbit Determination Date" static let OrbitUncertainty = "Orbit Uncertainty" static let MinimumOrbitIntersection = "Minimum Orbit Intersection" static let JupiterTisserandInvariant = "Jupiter Tisserand Invariant" static let EpochOsculation = "Epoch Osculation" static let Eccentricity = "Eccentricity" static let SemiMajorAxis = "Semi Major Axis" static let Inclination = "Inclination" static let AscendingNodeLongitude = "Ascending Node Longitude" static let OrbitalPeriod = "Orbital Period" static let PerihelionDistance = "Perihelion Distance" static let PerihelionArgument = "Perihelion Argument" static let AphelionDistance = "Aphelion Distance" static let PerihelionTime = "Perihelion Time" static let MeanAnomaly = "Mean Anomaly" static let MeanMotion = "Mean Motion" static let Equinox = "Equinox" static let TableRowHeight: CGFloat = 30 } var orbitalDataArray = [(String, AnyObject)]() override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBarHidden = true tableView.rowHeight = Constants.TableRowHeight if let selectedAsteroid = (tabBarController as! DetailViewController).selectedAsteroid { if let orbitalData = selectedAsteroid.orbitalData { populateOrbitalDataArrayWithOrbitalData(orbitalData); } else { startActitvityIndicator() Utility.nearEarthObjectWS.neoForReferenceId(selectedAsteroid.neoReferenceId!) { (result, error) -> Void in if let error = error { Utility.displayAlert(self, message: error.localizedDescription) } else if let neo = result where result?.orbitalData != nil { let orbitInfo = OrbitInfo(orbit: neo.orbitalData, context: self.sharedContext) orbitInfo.asteroid = selectedAsteroid self.populateOrbitalDataArrayWithOrbitalData(selectedAsteroid.orbitalData!) } dispatch_async(dispatch_get_main_queue()) { () -> Void in self.tableView.reloadData() } self.stopActivityIndicator() } } } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return orbitalDataArray.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(Constants.CellReusableID, forIndexPath: indexPath) let (key, value) = orbitalDataArray[indexPath.row] cell.textLabel?.text = key cell.detailTextLabel?.text = "\(value)" return cell } func populateOrbitalDataArrayWithOrbitalData(data: OrbitInfo) { orbitalDataArray.append((Constants.OrbitID, data.orbitId ?? "")) orbitalDataArray.append((Constants.OrbitDeterminationDate, data.orbitDeterminationDate == nil ? "" : Utility.getFormattedStringFromDate(data.orbitDeterminationDate!, format: Utility.Constants.SectionHeaderDateFormat)!)) orbitalDataArray.append((Constants.OrbitUncertainty, data.orbitUncertainty ?? "")) orbitalDataArray.append((Constants.MinimumOrbitIntersection, getDoubleValue(data.minimumOrbitIntersection) ?? "")) orbitalDataArray.append((Constants.JupiterTisserandInvariant, getDoubleValue(data.jupiterTisserandInvariant) ?? "")) orbitalDataArray.append((Constants.EpochOsculation, getDoubleValue(data.epochOsculation) ?? "")) orbitalDataArray.append((Constants.Eccentricity, getDoubleValue(data.eccentricity) ?? "")) orbitalDataArray.append((Constants.SemiMajorAxis, getDoubleValue(data.semiMajorAxis) ?? "")) orbitalDataArray.append((Constants.Inclination, getDoubleValue(data.inclination) ?? "")) orbitalDataArray.append((Constants.AscendingNodeLongitude, getDoubleValue(data.ascendingNodeLongitude) ?? "")) orbitalDataArray.append((Constants.OrbitalPeriod, getDoubleValue(data.orbitalPeriod) ?? "")) orbitalDataArray.append((Constants.PerihelionDistance, getDoubleValue(data.perihelionDistance) ?? "")) orbitalDataArray.append((Constants.PerihelionArgument, getDoubleValue(data.perihelionArgument) ?? "")) orbitalDataArray.append((Constants.AphelionDistance, getDoubleValue(data.aphelionDistance) ?? "")) orbitalDataArray.append((Constants.PerihelionTime, getDoubleValue(data.perihelionTime) ?? "")) orbitalDataArray.append((Constants.MeanAnomaly, getDoubleValue(data.meanAnomaly) ?? "")) orbitalDataArray.append((Constants.MeanMotion, getDoubleValue(data.meanMotion) ?? "")) orbitalDataArray.append((Constants.Equinox, data.equinox ?? "")) } func getDoubleValue(string: String?) -> Double? { var double: Double? if let string = string { double = Double(string) double = double?.roundToDecimals() } return double } }
mit
5aaabb686f24eaaa0f76a8f32ea02303
45.611111
227
0.650264
4.841715
false
false
false
false
colbylwilliams/bugtrap
iOS/Code/Swift/bugTrap/bugTrapKit/SwiftyJSON.swift
1
29060
// SwiftyJSON.swift // // Copyright (c) 2014 Ruoyu Fu, Pinglin Tang // // 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 // MARK: - Error ///Error domain public let ErrorDomain: String! = "SwiftyJSONErrorDomain" ///Error code public let ErrorUnsupportedType: Int! = 999 public let ErrorIndexOutOfBounds: Int! = 900 public let ErrorWrongType: Int! = 901 public let ErrorNotExist: Int! = 500 // MARK: - JSON Type /** JSON's type definitions. See http://tools.ietf.org/html/rfc7231#section-4.3 */ public enum Type :Int{ case Number case String case Bool case Array case Dictionary case Null case Unknown } // MARK: - JSON Base public struct JSON { /** Creates a JSON using the data. :param: data The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary :param: opt The JSON serialization reading options. `.AllowFragments` by default. :param: error error The NSErrorPointer used to return the error. `nil` by default. :returns: The created JSON */ public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) { do { let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt) self.init(object) } catch let error1 as NSError { error.memory = error1 self.init(NSNull()) } } /** Creates a JSON using the object. :param: object The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. :returns: The created JSON */ public init(_ object: AnyObject) { self.object = object } /** Creates a JSON from a [JSON] :param: jsonArray A Swift array of JSON objects :returns: The created JSON */ public init(_ jsonArray:[JSON]) { self.init(jsonArray.map { $0.object }) } /** Creates a JSON from a [String: JSON] :param: jsonDictionary A Swift dictionary of JSON objects :returns: The created JSON */ public init(_ jsonDictionary:[String: JSON]) { var dictionary = [String: AnyObject]() for (key, json) in jsonDictionary { dictionary[key] = json.object } self.init(dictionary) } /// Private object private var _object: AnyObject = NSNull() /// Private type private var _type: Type = .Null /// prviate error private var _error: NSError? /// Object in JSON public var object: AnyObject { get { return _object } set { _object = newValue switch newValue { case let number as NSNumber: if number.isBool { _type = .Bool } else { _type = .Number } case _ as NSString: _type = .String case _ as NSNull: _type = .Null case _ as [AnyObject]: _type = .Array case _ as [String : AnyObject]: _type = .Dictionary default: _type = .Unknown _object = NSNull() _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) } } } /// json type public var type: Type { get { return _type } } /// Error in JSON public var error: NSError? { get { return self._error } } /// The static null json public static var nullJSON: JSON { get { return JSON(NSNull()) } } } // MARK: - SequenceType extension JSON : Swift.SequenceType { /// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `false`. public var isEmpty: Bool { get { switch self.type { case .Array: return (self.object as! [AnyObject]).isEmpty case .Dictionary: return (self.object as! [String : AnyObject]).isEmpty default: return false } } } /// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`. public var count: Int { get { switch self.type { case .Array: return (self.object as! [AnyObject]).count case .Dictionary: return (self.object as! [String : AnyObject]).count default: return 0 } } } /** If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty. :returns: Return a *generator* over the elements of this *sequence*. */ public func generate() -> AnyGenerator <(String, JSON)> { switch self.type { case .Array: let array_ = object as! [AnyObject] var generate_ = array_.generate() var index_: Int = 0 return anyGenerator { if let element_: AnyObject = generate_.next() { return ("\(index_++)", JSON(element_)) } else { return nil } } case .Dictionary: let dictionary_ = object as! [String : AnyObject] var generate_ = dictionary_.generate() return anyGenerator { if let (key_, value_): (String, AnyObject) = generate_.next() { return (key_, JSON(value_)) } else { return nil } } default: return anyGenerator { return nil } } } } // MARK: - Subscript /** * To mark both String and Int can be used in subscript. */ public protocol SubscriptType {} extension Int: SubscriptType {} extension String: SubscriptType {} extension JSON { /// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error. private subscript(index index: Int) -> JSON { get { if self.type != .Array { var errorResult_ = JSON.nullJSON errorResult_._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) return errorResult_ } let array_ = self.object as! [AnyObject] if index >= 0 && index < array_.count { return JSON(array_[index]) } var errorResult_ = JSON.nullJSON errorResult_._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) return errorResult_ } set { if self.type == .Array { var array_ = self.object as! [AnyObject] if array_.count > index { array_[index] = newValue.object self.object = array_ } } } } /// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error. private subscript(key key: String) -> JSON { get { var returnJSON = JSON.nullJSON if self.type == .Dictionary { let dictionary_ = self.object as! [String : AnyObject] if let object_: AnyObject = dictionary_[key] { returnJSON = JSON(object_) } else { returnJSON._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"]) } } else { returnJSON._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"]) } return returnJSON } set { if self.type == .Dictionary { var dictionary_ = self.object as! [String : AnyObject] dictionary_[key] = newValue.object self.object = dictionary_ } } } /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. private subscript(sub sub: SubscriptType) -> JSON { get { if sub is String { return self[key:sub as! String] } else { return self[index:sub as! Int] } } set { if sub is String { self[key:sub as! String] = newValue } else { self[index:sub as! Int] = newValue } } } /** Find a json in the complex data structuresby using the Int/String's array. :param: path The target json's path. Example: let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] The same as: let name = json[9]["list"]["person"]["name"] :returns: Return a json found by the path or a null json with error */ public subscript(path: [SubscriptType]) -> JSON { get { if path.count == 0 { return JSON.nullJSON } var next = self for sub in path { next = next[sub:sub] } return next } set { switch path.count { case 0: return case 1: self[sub:path[0]] = newValue default: var last = newValue var newPath = path newPath.removeLast() for sub in path.reverse() { var previousLast = self[newPath] previousLast[sub:sub] = last last = previousLast if newPath.count <= 1 { break } newPath.removeLast() } self[sub:newPath[0]] = last } } } /** Find a json in the complex data structuresby using the Int/String's array. :param: path The target json's path. Example: let name = json[9,"list","person","name"] The same as: let name = json[9]["list"]["person"]["name"] :returns: Return a json found by the path or a null json with error */ public subscript(path: SubscriptType...) -> JSON { get { return self[path] } set { self[path] = newValue } } } // MARK: - LiteralConvertible extension JSON: Swift.StringLiteralConvertible { public init(stringLiteral value: StringLiteralType) { self.init(value) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value) } } extension JSON: Swift.IntegerLiteralConvertible { public init(integerLiteral value: IntegerLiteralType) { self.init(value) } } extension JSON: Swift.BooleanLiteralConvertible { public init(booleanLiteral value: BooleanLiteralType) { self.init(value) } } extension JSON: Swift.FloatLiteralConvertible { public init(floatLiteral value: FloatLiteralType) { self.init(value) } } extension JSON: Swift.DictionaryLiteralConvertible { public init(dictionaryLiteral elements: (String, AnyObject)...) { var dictionary_ = [String : AnyObject]() for (key_, value) in elements { dictionary_[key_] = value } self.init(dictionary_) } } extension JSON: Swift.ArrayLiteralConvertible { public init(arrayLiteral elements: AnyObject...) { self.init(elements) } } extension JSON: Swift.NilLiteralConvertible { public init(nilLiteral: ()) { self.init(NSNull()) } } // MARK: - Raw extension JSON: Swift.RawRepresentable { public init?(rawValue: AnyObject) { if JSON(rawValue).type == .Unknown { return nil } else { self.init(rawValue) } } public var rawValue: AnyObject { return self.object } public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(rawValue: 0)) throws -> NSData { return try NSJSONSerialization.dataWithJSONObject(self.object, options: opt) } public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? { switch self.type { case .Array, .Dictionary: do { let data = try self.rawData(options: opt) return NSString(data: data, encoding: encoding) as? String } catch _ { return nil } case .String: return (self.object as! String) case .Number: return (self.object as! NSNumber).stringValue case .Bool: return (self.object as! Bool).description case .Null: return "null" default: return nil } } } // MARK: - Printable, DebugPrintable extension JSON: Swift.Printable, Swift.DebugPrintable { public var description: String { if let string = self.rawString(options:.PrettyPrinted) { return string } else { return "unknown" } } public var debugDescription: String { return description } } // MARK: - Array extension JSON { //Optional [JSON] public var array: [JSON]? { get { if self.type == .Array { return (self.object as! [AnyObject]).map{ JSON($0) } } else { return nil } } } //Non-optional [JSON] public var arrayValue: [JSON] { get { return self.array ?? [] } } //Optional [AnyObject] public var arrayObject: [AnyObject]? { get { switch self.type { case .Array: return self.object as? [AnyObject] default: return nil } } set { if newValue != nil { self.object = NSMutableArray(array: newValue!, copyItems: true) } else { self.object = NSNull() } } } } // MARK: - Dictionary extension JSON { private func _map<Key:Hashable ,Value, NewValue>(source: [Key: Value], transform: Value -> NewValue) -> [Key: NewValue] { var result = [Key: NewValue](minimumCapacity:source.count) for (key,value) in source { result[key] = transform(value) } return result } //Optional [String : JSON] public var dictionary: [String : JSON]? { get { if self.type == .Dictionary { return _map(self.object as! [String : AnyObject]){ JSON($0) } } else { return nil } } } //Non-optional [String : JSON] public var dictionaryValue: [String : JSON] { get { return self.dictionary ?? [:] } } //Optional [String : AnyObject] public var dictionaryObject: [String : AnyObject]? { get { switch self.type { case .Dictionary: return self.object as? [String : AnyObject] default: return nil } } set { if newValue != nil { self.object = NSMutableDictionary(dictionary: newValue!, copyItems: true) } else { self.object = NSNull() } } } } // MARK: - Bool extension JSON: Swift.BooleanType { //Optional bool public var bool: Bool? { get { switch self.type { case .Bool: return self.object.boolValue default: return nil } } set { if newValue != nil { self.object = NSNumber(bool: newValue!) } else { self.object = NSNull() } } } //Non-optional bool public var boolValue: Bool { get { switch self.type { case .Bool, .Number, .String: return self.object.boolValue default: return false } } set { self.object = NSNumber(bool: newValue) } } } // MARK: - String extension JSON { //Optional string public var string: String? { get { switch self.type { case .String: return self.object as? String default: return nil } } set { if newValue != nil { self.object = NSString(string:newValue!) } else { self.object = NSNull() } } } //Non-optional string public var stringValue: String { get { switch self.type { case .String: return self.object as! String case .Number: return self.object.stringValue case .Bool: return (self.object as! Bool).description default: return "" } } set { self.object = NSString(string:newValue) } } } // MARK: - Number extension JSON { //Optional number public var number: NSNumber? { get { switch self.type { case .Number, .Bool: return self.object as? NSNumber default: return nil } } set { self.object = newValue?.copy() ?? NSNull() } } //Non-optional number public var numberValue: NSNumber { get { switch self.type { case .String: let scanner = NSScanner(string: self.object as! String) if scanner.scanDouble(nil){ if (scanner.atEnd) { return NSNumber(double:(self.object as! NSString).doubleValue) } } return NSNumber(double: 0.0) case .Number, .Bool: return self.object as! NSNumber default: return NSNumber(double: 0.0) } } set { self.object = newValue.copy() } } } //MARK: - Null extension JSON { public var null: NSNull? { get { switch self.type { case .Null: return NSNull() default: return nil } } set { self.object = NSNull() } } } //MARK: - URL extension JSON { //Optional URL public var URL: NSURL? { get { switch self.type { case .String: if let encodedString_ = self.object.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) { return NSURL(string: encodedString_) } else { return nil } default: return nil } } set { self.object = newValue?.absoluteString ?? NSNull() } } } // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { public var double: Double? { get { return self.number?.doubleValue } set { if newValue != nil { self.object = NSNumber(double: newValue!) } else { self.object = NSNull() } } } public var doubleValue: Double { get { return self.numberValue.doubleValue } set { self.object = NSNumber(double: newValue) } } public var float: Float? { get { return self.number?.floatValue } set { if newValue != nil { self.object = NSNumber(float: newValue!) } else { self.object = NSNull() } } } public var floatValue: Float { get { return self.numberValue.floatValue } set { self.object = NSNumber(float: newValue) } } public var int: Int? { get { return self.number?.longValue } set { if newValue != nil { self.object = NSNumber(integer: newValue!) } else { self.object = NSNull() } } } public var intValue: Int { get { return self.numberValue.integerValue } set { self.object = NSNumber(integer: newValue) } } public var uInt: UInt? { get { return self.number?.unsignedLongValue } set { if newValue != nil { self.object = NSNumber(unsignedLong: newValue!) } else { self.object = NSNull() } } } public var uIntValue: UInt { get { return self.numberValue.unsignedLongValue } set { self.object = NSNumber(unsignedLong: newValue) } } public var int8: Int8? { get { return self.number?.charValue } set { if newValue != nil { self.object = NSNumber(char: newValue!) } else { self.object = NSNull() } } } public var int8Value: Int8 { get { return self.numberValue.charValue } set { self.object = NSNumber(char: newValue) } } public var uInt8: UInt8? { get { return self.number?.unsignedCharValue } set { if newValue != nil { self.object = NSNumber(unsignedChar: newValue!) } else { self.object = NSNull() } } } public var uInt8Value: UInt8 { get { return self.numberValue.unsignedCharValue } set { self.object = NSNumber(unsignedChar: newValue) } } public var int16: Int16? { get { return self.number?.shortValue } set { if newValue != nil { self.object = NSNumber(short: newValue!) } else { self.object = NSNull() } } } public var int16Value: Int16 { get { return self.numberValue.shortValue } set { self.object = NSNumber(short: newValue) } } public var uInt16: UInt16? { get { return self.number?.unsignedShortValue } set { if newValue != nil { self.object = NSNumber(unsignedShort: newValue!) } else { self.object = NSNull() } } } public var uInt16Value: UInt16 { get { return self.numberValue.unsignedShortValue } set { self.object = NSNumber(unsignedShort: newValue) } } public var int32: Int32? { get { return self.number?.intValue } set { if newValue != nil { self.object = NSNumber(int: newValue!) } else { self.object = NSNull() } } } public var int32Value: Int32 { get { return self.numberValue.intValue } set { self.object = NSNumber(int: newValue) } } public var uInt32: UInt32? { get { return self.number?.unsignedIntValue } set { if newValue != nil { self.object = NSNumber(unsignedInt: newValue!) } else { self.object = NSNull() } } } public var uInt32Value: UInt32 { get { return self.numberValue.unsignedIntValue } set { self.object = NSNumber(unsignedInt: newValue) } } public var int64: Int64? { get { return self.number?.longLongValue } set { if newValue != nil { self.object = NSNumber(longLong: newValue!) } else { self.object = NSNull() } } } public var int64Value: Int64 { get { return self.numberValue.longLongValue } set { self.object = NSNumber(longLong: newValue) } } public var uInt64: UInt64? { get { return self.number?.unsignedLongLongValue } set { if newValue != nil { self.object = NSNumber(unsignedLongLong: newValue!) } else { self.object = NSNull() } } } public var uInt64Value: UInt64 { get { return self.numberValue.unsignedLongLongValue } set { self.object = NSNumber(unsignedLongLong: newValue) } } } //MARK: - Comparable extension JSON: Swift.Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) == (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) == (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func <=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) <= (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) <= (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func >=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) >= (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) >= (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func >(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) > (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) > (rhs.object as! String) default: return false } } public func <(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) < (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) < (rhs.object as! String) default: return false } } private let trueNumber = NSNumber(bool: true) private let falseNumber = NSNumber(bool: false) private let trueObjCType = String.fromCString(trueNumber.objCType) private let falseObjCType = String.fromCString(falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber: Swift.Comparable { var isBool:Bool { get { let objCType = String.fromCString(self.objCType) if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){ return true } else { return false } } } } public func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedSame } } public func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } public func <(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedAscending } } public func >(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedDescending } } public func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedDescending } } public func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedAscending } } //MARK:- Unavailable @available(*, unavailable, renamed="JSON") public typealias JSONValue = JSON extension JSON { @available(*, unavailable, message="use 'init(_ object:AnyObject)' instead") public init(object: AnyObject) { self = JSON(object) } @available(*, unavailable, renamed="dictionaryObject") public var dictionaryObjects: [String : AnyObject]? { get { return self.dictionaryObject } } @available(*, unavailable, renamed="arrayObject") public var arrayObjects: [AnyObject]? { get { return self.arrayObject } } @available(*, unavailable, renamed="int8") public var char: Int8? { get { return self.number?.charValue } } @available(*, unavailable, renamed="int8Value") public var charValue: Int8 { get { return self.numberValue.charValue } } @available(*, unavailable, renamed="uInt8") public var unsignedChar: UInt8? { get{ return self.number?.unsignedCharValue } } @available(*, unavailable, renamed="uInt8Value") public var unsignedCharValue: UInt8 { get{ return self.numberValue.unsignedCharValue } } @available(*, unavailable, renamed="int16") public var short: Int16? { get{ return self.number?.shortValue } } @available(*, unavailable, renamed="int16Value") public var shortValue: Int16 { get{ return self.numberValue.shortValue } } @available(*, unavailable, renamed="uInt16") public var unsignedShort: UInt16? { get{ return self.number?.unsignedShortValue } } @available(*, unavailable, renamed="uInt16Value") public var unsignedShortValue: UInt16 { get{ return self.numberValue.unsignedShortValue } } @available(*, unavailable, renamed="int") public var long: Int? { get{ return self.number?.longValue } } @available(*, unavailable, renamed="intValue") public var longValue: Int { get{ return self.numberValue.longValue } } @available(*, unavailable, renamed="uInt") public var unsignedLong: UInt? { get{ return self.number?.unsignedLongValue } } @available(*, unavailable, renamed="uIntValue") public var unsignedLongValue: UInt { get{ return self.numberValue.unsignedLongValue } } @available(*, unavailable, renamed="int64") public var longLong: Int64? { get{ return self.number?.longLongValue } } @available(*, unavailable, renamed="int64Value") public var longLongValue: Int64 { get{ return self.numberValue.longLongValue } } @available(*, unavailable, renamed="uInt64") public var unsignedLongLong: UInt64? { get{ return self.number?.unsignedLongLongValue } } @available(*, unavailable, renamed="uInt64Value") public var unsignedLongLongValue: UInt64 { get{ return self.numberValue.unsignedLongLongValue } } @available(*, unavailable, renamed="int") public var integer: Int? { get { return self.number?.integerValue } } @available(*, unavailable, renamed="intValue") public var integerValue: Int { get { return self.numberValue.integerValue } } @available(*, unavailable, renamed="uInt") public var unsignedInteger: Int? { get { return self.number?.unsignedIntegerValue } } @available(*, unavailable, renamed="uIntValue") public var unsignedIntegerValue: Int { get { return self.numberValue.unsignedIntegerValue } } }
mit
be9bf3ca62d4ea95ac5333bda67348fd
20.305718
256
0.655919
3.341766
false
false
false
false
kickstarter/ios-oss
Kickstarter-iOS/Features/ProjectActivities/Controller/ProjectActivityViewControllerTests.swift
1
3620
@testable import Kickstarter_Framework @testable import KsApi import Library import Prelude import XCTest internal final class ProjectActivityViewControllerTests: TestCase { override func setUp() { super.setUp() AppEnvironment.pushEnvironment( apiService: MockService( oauthToken: OauthToken(token: "deadbeef"), fetchProjectActivitiesResponse: activityCategories.map { baseActivity |> Activity.lens.category .~ $0 } + backingActivities ), currentUser: Project.cosmicSurgery.creator, mainBundle: Bundle.framework ) UIView.setAnimationsEnabled(false) } override func tearDown() { AppEnvironment.popEnvironment() UIView.setAnimationsEnabled(true) super.tearDown() } func testProjectActivityView() { combos(Language.allLanguages, Device.allCases).forEach { language, device in withEnvironment(language: language) { let controller = ProjectActivitiesViewController.configuredWith(project: project) let (parent, _) = traitControllers(device: device, orientation: .portrait, child: controller) self.scheduler.run() FBSnapshotVerifyView( parent.view, identifier: "lang_\(language)_device_\(device)", overallTolerance: 0.03 ) } } } } private let project = Project.cosmicSurgery |> Project.lens.dates.deadline .~ 123_456_789.0 |> Project.lens.dates.launchedAt .~ 123_456_789.0 |> Project.lens.photo.small .~ "" |> Project.lens.photo.med .~ "" |> Project.lens.photo.full .~ "" private let user = User.brando |> \.avatar.large .~ "" |> \.avatar.medium .~ "" |> \.avatar.small .~ "" private let baseActivity = .template |> Activity.lens.createdAt .~ 123_456_789.0 |> Activity.lens.memberData.amount .~ 25 |> Activity.lens.project .~ project |> Activity.lens.update .~ ( .template |> Update.lens.title .~ "Spirit animal reward available again" |> Update.lens.body .~ ("Due to popular demand, and the inspirational momentum of this project, we've" + " added more spirit animal rewards!") |> Update.lens.publishedAt .~ 123_456_789.0 ) |> Activity.lens.user .~ user |> Activity.lens.memberData.backing .~ .some( .template |> Backing.lens.amount .~ 25 |> Backing.lens.backerId .~ user.id |> Backing.lens.backer .~ user ) private let backingActivity = baseActivity |> Activity.lens.category .~ .backing |> Activity.lens.memberData.amount .~ 25 |> Activity.lens.memberData.rewardId .~ 1 private let backingAmountActivity = baseActivity |> Activity.lens.category .~ .backingAmount |> Activity.lens.memberData.newAmount .~ 25 |> Activity.lens.memberData.newRewardId .~ 1 |> Activity.lens.memberData.oldRewardId .~ 2 |> Activity.lens.memberData.oldAmount .~ 100 private let backingCanceledActivity = baseActivity |> Activity.lens.category .~ .backingCanceled |> Activity.lens.memberData.amount .~ 25 |> Activity.lens.memberData.rewardId .~ 1 private let backingRewardActivity = baseActivity |> Activity.lens.category .~ .backingReward |> Activity.lens.memberData.newRewardId .~ 1 |> Activity.lens.memberData.oldRewardId .~ 2 private let activityCategories: [Activity.Category] = [ .update, .suspension, .cancellation, .failure, .success, .launch, .commentPost, .commentProject ] private let backingActivities = [ backingActivity, backingAmountActivity, backingCanceledActivity, backingRewardActivity ]
apache-2.0
cf3fdcc94d115676ff4497e146af24ce
27.96
110
0.671547
4.204413
false
false
false
false
tjw/swift
stdlib/public/core/StringGutsVisitor.swift
1
6856
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // TODO: describe // // HACK HACK HACK: For whatever reason, having this directly on String instead // of _StringGuts avoids a cascade of ARC. Also note, we can have a global // function that forwards, but that function **must not be on _StringGuts**, // else ARC. // extension String { @inlinable @inline(__always) func _visit<Result>( range: (Range<Int>, performBoundsCheck: Bool)? = nil, ascii: /*@convention(thin)*/ (_UnmanagedString<UInt8>) -> Result, utf16: /*@convention(thin)*/ (_UnmanagedString<UInt16>) -> Result, opaque: /*@convention(thin)*/ (_UnmanagedOpaqueString) -> Result ) -> Result { if _slowPath(_guts._isOpaque) { return self._visitOpaque( range: range, ascii: ascii, utf16: utf16, opaque: opaque) } defer { _fixLifetime(self) } if _guts.isASCII { var view = _guts._unmanagedASCIIView if let (range, boundsCheck) = range { if boundsCheck { view._boundsCheck(offsetRange: range) } view = view[range] } return ascii(view) } else { var view = _guts._unmanagedUTF16View if let (range, boundsCheck) = range { if boundsCheck { view._boundsCheck(offsetRange: range) } view = view[range] } return utf16(view) } } @usableFromInline @effects(readonly) @inline(never) // @_outlined func _visitOpaque<Result>( range: (Range<Int>, performBoundsCheck: Bool)? = nil, ascii: /*@convention(thin)*/ (_UnmanagedString<UInt8>) -> Result, utf16: /*@convention(thin)*/ (_UnmanagedString<UInt16>) -> Result, opaque: /*@convention(thin)*/ (_UnmanagedOpaqueString) -> Result ) -> Result { _sanityCheck(_guts._isOpaque) if _guts._isSmall { _sanityCheck(_guts._object._isSmallUTF8, "no other small forms yet") let small = _guts._smallUTF8String if small.isASCII { return small.withUnmanagedASCII { view in var view = view if let (range, boundsCheck) = range { if boundsCheck { view._boundsCheck(offsetRange: range) } view = view[range] } return ascii(view) } } return small.withUnmanagedUTF16 { view in var view = view if let (range, boundsCheck) = range { if boundsCheck { view._boundsCheck(offsetRange: range) } view = view[range] } return utf16(view) } } // TODO: But can it provide a pointer+length representation? defer { _fixLifetime(self) } var view = _guts._asOpaque() if let (range, boundsCheck) = range { if boundsCheck { view._boundsCheck(offsetRange: range) } view = view[range] } return opaque(view) } @inlinable @inline(__always) func _visit<T, Result>( range: (Range<Int>, performBoundsCheck: Bool)?, args x: T, ascii: /*@convention(thin)*/ (_UnmanagedString<UInt8>, T) -> Result, utf16: /*@convention(thin)*/ (_UnmanagedString<UInt16>, T) -> Result, opaque: /*@convention(thin)*/ (_UnmanagedOpaqueString, T) -> Result ) -> Result { if _slowPath(_guts._isOpaque) { return self._visitOpaque( range: range, args: x, ascii: ascii, utf16: utf16, opaque: opaque) } defer { _fixLifetime(self) } if _guts.isASCII { var view = _guts._unmanagedASCIIView if let (range, boundsCheck) = range { if boundsCheck { view._boundsCheck(offsetRange: range) } view = view[range] } return ascii(view, x) } else { var view = _guts._unmanagedUTF16View if let (range, boundsCheck) = range { if boundsCheck { view._boundsCheck(offsetRange: range) } view = view[range] } return utf16(view, x) } } @usableFromInline // @opaque @effects(readonly) @inline(never) func _visitOpaque<T, Result>( range: (Range<Int>, performBoundsCheck: Bool)?, args x: T, ascii: /*@convention(thin)*/ (_UnmanagedString<UInt8>, T) -> Result, utf16: /*@convention(thin)*/ (_UnmanagedString<UInt16>, T) -> Result, opaque: /*@convention(thin)*/ (_UnmanagedOpaqueString, T) -> Result ) -> Result { _sanityCheck(_guts._isOpaque) if _fastPath(_guts._isSmall) { _sanityCheck(_guts._object._isSmallUTF8, "no other small forms yet") let small = _guts._smallUTF8String if small.isASCII { return small.withUnmanagedASCII { view in var view = view if let (range, boundsCheck) = range { if boundsCheck { view._boundsCheck(offsetRange: range) } view = view[range] } return ascii(view, x) } } return small.withUnmanagedUTF16 { view in var view = view if let (range, boundsCheck) = range { if boundsCheck { view._boundsCheck(offsetRange: range) } view = view[range] } return utf16(view, x) } } // TODO: But can it provide a pointer+length representation? defer { _fixLifetime(self) } var view = _guts._asOpaque() if let (range, boundsCheck) = range { if boundsCheck { view._boundsCheck(offsetRange: range) } view = view[range] } return opaque(view, x) } } @inlinable @inline(__always) internal func _visitGuts<Result>( _ guts: _StringGuts, range: (Range<Int>, performBoundsCheck: Bool)? = nil, ascii: /*@convention(thin)*/ (_UnmanagedString<UInt8>) -> Result, utf16: /*@convention(thin)*/ (_UnmanagedString<UInt16>) -> Result, opaque: /*@convention(thin)*/ (_UnmanagedOpaqueString) -> Result ) -> Result { return String(guts)._visit( range: range, ascii: ascii, utf16: utf16, opaque: opaque) } @inlinable @inline(__always) internal func _visitGuts<T, Result>( _ guts: _StringGuts, range: (Range<Int>, performBoundsCheck: Bool)? = nil, args x: T, ascii: /*@convention(thin)*/ (_UnmanagedString<UInt8>, T) -> Result, utf16: /*@convention(thin)*/ (_UnmanagedString<UInt16>, T) -> Result, opaque: /*@convention(thin)*/ (_UnmanagedOpaqueString, T) -> Result ) -> Result { return String(guts)._visit( range: range, args: x, ascii: ascii, utf16: utf16, opaque: opaque) }
apache-2.0
b9757f70b6d29a569efff07bb484ad03
29.607143
80
0.587806
4.03057
false
false
false
false
roambotics/swift
test/SILGen/optional-cast.swift
2
8989
// RUN: %target-swift-emit-silgen %s | %FileCheck %s class A {} class B : A {} // CHECK-LABEL: sil hidden [ossa] @$s4main3fooyyAA1ACSgF : $@convention(thin) (@guaranteed Optional<A>) -> () { // CHECK: bb0([[ARG:%.*]] : @guaranteed $Optional<A>): // CHECK: [[X:%.*]] = alloc_box ${ var Optional<B> }, var, name "x" // CHECK: [[X_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[X]] // CHECK-NEXT: [[PB:%.*]] = project_box [[X_LIFETIME]] // Check whether the temporary holds a value. // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $Optional<A>, case #Optional.some!enumelt: [[IS_PRESENT:bb[0-9]+]], case #Optional.none!enumelt: [[NOT_PRESENT:bb[0-9]+]] // // If so, pull the value out and check whether it's a B. // CHECK: [[IS_PRESENT]]([[VAL:%.*]] : // CHECK-NEXT: [[X_VALUE:%.*]] = init_enum_data_addr [[PB]] : $*Optional<B>, #Optional.some // CHECK-NEXT: checked_cast_br [[VAL]] : $A to B, [[IS_B:bb.*]], [[NOT_B:bb[0-9]+]] // // If so, materialize that and inject it into x. // CHECK: [[IS_B]]([[T0:%.*]] : @owned $B): // CHECK-NEXT: store [[T0]] to [init] [[X_VALUE]] : $*B // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<B>, #Optional.some // CHECK-NEXT: br [[CONT:bb[0-9]+]] // // If not, destroy_value the A and inject nothing into x. // CHECK: [[NOT_B]]([[ORIGINAL_VALUE:%.*]] : @owned $A): // CHECK-NEXT: destroy_value [[ORIGINAL_VALUE]] // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<B>, #Optional.none // CHECK-NEXT: br [[CONT]] // // Finish the present path. // CHECK: [[CONT]]: // CHECK-NEXT: br [[RETURN_BB:bb[0-9]+]] // // Finish. // CHECK: [[RETURN_BB]]: // CHECK-NEXT: end_borrow [[X_LIFETIME]] // CHECK-NEXT: destroy_value [[X]] // CHECK-NOT: destroy_value [[ARG]] // CHECK-NEXT: tuple // CHECK-NEXT: return // // Finish the not-present path. // CHECK: [[NOT_PRESENT]]: // CHECK-NEXT: inject_enum_addr [[PB]] {{.*}}none // CHECK-NEXT: br [[RETURN_BB]] func foo(_ y : A?) { var x = (y as? B) } // CHECK-LABEL: sil hidden [ossa] @$s4main3baryyAA1ACSgSgSgSgF : $@convention(thin) (@guaranteed Optional<Optional<Optional<Optional<A>>>>) -> () { // CHECK: bb0([[ARG:%.*]] : @guaranteed $Optional<Optional<Optional<Optional<A>>>>): // CHECK: [[X:%.*]] = alloc_box ${ var Optional<Optional<Optional<B>>> }, var, name "x" // CHECK: [[X_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[X]] // CHECK-NEXT: [[PB:%.*]] = project_box [[X_LIFETIME]] // -- Check for some(...) // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK-NEXT: switch_enum [[ARG_COPY]] : ${{.*}}, case #Optional.some!enumelt: [[P:bb[0-9]+]], case #Optional.none!enumelt: [[NIL_DEPTH_1:bb[0-9]+]] // // CHECK: [[NIL_DEPTH_1]]: // CHECK: br [[FINISH_NIL_0:bb[0-9]+]] // // If so, drill down another level and check for some(some(...)). // CHECK: [[P]]([[VALUE_OOOA:%.*]] : // CHECK-NEXT: switch_enum [[VALUE_OOOA]] : ${{.*}}, case #Optional.some!enumelt: [[PP:bb[0-9]+]], case #Optional.none!enumelt: [[NIL_DEPTH_2:bb[0-9]+]] // // CHECK: [[NIL_DEPTH_2]]: // CHECK: br [[FINISH_NIL_0]] // // If so, drill down another level and check for some(some(some(...))). // CHECK: [[PP]]([[VALUE_OOA:%.*]] : // CHECK-NEXT: switch_enum [[VALUE_OOA]] : ${{.*}}, case #Optional.some!enumelt: [[PPP:bb[0-9]+]], case #Optional.none!enumelt: [[NIL_DEPTH_3:bb[0-9]+]] // // If so, drill down another level and check for some(some(some(some(...)))). // CHECK: [[PPP]]([[VALUE_OA:%.*]] : // CHECK-NEXT: switch_enum [[VALUE_OA]] : ${{.*}}, case #Optional.some!enumelt: [[PPPP:bb[0-9]+]], case #Optional.none!enumelt: [[NIL_DEPTH_4:bb[0-9]+]] // // If so, pull out the A and check whether it's a B. // CHECK: [[PPPP]]([[VAL:%.*]] : // CHECK-NEXT: checked_cast_br [[VAL]] : $A to B, [[IS_B:bb.*]], [[NOT_B:bb[0-9]+]] // // If so, inject it back into an optional. // TODO: We're going to switch back out of this; we really should peephole it. // CHECK: [[IS_B]]([[T0:%.*]] : @owned $B): // CHECK-NEXT: enum $Optional<B>, #Optional.some!enumelt, [[T0]] // CHECK-NEXT: br [[SWITCH_OB2:bb[0-9]+]]( // // If not, inject nothing into an optional. // CHECK: [[NOT_B]]([[ORIGINAL_VALUE:%.*]] : @owned $A): // CHECK-NEXT: destroy_value [[ORIGINAL_VALUE]] // CHECK-NEXT: enum $Optional<B>, #Optional.none!enumelt // CHECK-NEXT: br [[SWITCH_OB2]]( // // Switch out on the value in [[OB2]]. // CHECK: [[SWITCH_OB2]]([[VAL:%[0-9]+]] : @owned $Optional<B>): // CHECK-NEXT: switch_enum [[VAL]] : ${{.*}}, case #Optional.some!enumelt: [[HAVE_B:bb[0-9]+]], case #Optional.none!enumelt: [[FINISH_NIL_4:bb[0-9]+]] // // CHECK: [[FINISH_NIL_4]]: // CHECK: br [[FINISH_NIL_0]] // // CHECK: [[HAVE_B]]([[UNWRAPPED_VAL:%.*]] : // CHECK: [[REWRAPPED_VAL:%.*]] = enum $Optional<B>, #Optional.some!enumelt, [[UNWRAPPED_VAL]] // CHECK: br [[DONE_DEPTH0:bb[0-9]+]] // // CHECK: [[DONE_DEPTH0]]( // CHECK-NEXT: enum $Optional<Optional<B>>, #Optional.some!enumelt, // CHECK-NEXT: br [[DONE_DEPTH1:bb[0-9]+]] // // Set X := some(OOB). // CHECK: [[DONE_DEPTH1]] // CHECK-NEXT: enum $Optional<Optional<Optional<B>>>, #Optional.some!enumelt, // CHECK: br [[DONE_DEPTH2:bb[0-9]+]] // CHECK: [[DONE_DEPTH2]] // CHECK-NEXT: end_borrow [[X_LIFETIME]] // CHECK-NEXT: destroy_value [[X]] // CHECK-NOT: destroy_value %0 // CHECK: return // // On various failure paths, set OOB := nil. // CHECK: [[NIL_DEPTH_4]]: // CHECK-NEXT: enum $Optional<B>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE_DEPTH0]] // // CHECK: [[NIL_DEPTH_3]]: // CHECK-NEXT: enum $Optional<Optional<B>>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE_DEPTH1]] // // On various failure paths, set X := nil. // CHECK: [[FINISH_NIL_0]]: // CHECK-NEXT: inject_enum_addr [[PB]] {{.*}}none // CHECK-NEXT: br [[DONE_DEPTH2]] // Done. func bar(_ y : A????) { var x = (y as? B??) } // CHECK-LABEL: sil hidden [ossa] @$s4main3bazyyyXlSgF : $@convention(thin) (@guaranteed Optional<AnyObject>) -> () { // CHECK: bb0([[ARG:%.*]] : @guaranteed $Optional<AnyObject>): // CHECK: [[X:%.*]] = alloc_box ${ var Optional<B> }, var, name "x" // CHECK: [[X_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[X]] // CHECK-NEXT: [[PB:%.*]] = project_box [[X_LIFETIME]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] // CHECK: bb1([[VAL:%.*]] : @owned $AnyObject): // CHECK-NEXT: [[X_VALUE:%.*]] = init_enum_data_addr [[PB]] : $*Optional<B>, #Optional.some // CHECK-NEXT: checked_cast_br [[VAL]] : $AnyObject to B, [[IS_B:bb.*]], [[NOT_B:bb[0-9]+]] // CHECK: [[IS_B]]([[CASTED_VALUE:%.*]] : @owned $B): // CHECK: store [[CASTED_VALUE]] to [init] [[X_VALUE]] // CHECK: [[NOT_B]]([[ORIGINAL_VALUE:%.*]] : @owned $AnyObject): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: } // end sil function '$s4main3bazyyyXlSgF' func baz(_ y : AnyObject?) { var x = (y as? B) } // <rdar://problem/17013042> T! <-> T? conversions should not produce a diamond // CHECK-LABEL: sil hidden [ossa] @$s4main07opt_to_B8_trivialySiSgACF // CHECK: bb0(%0 : $Optional<Int>): // CHECK-NEXT: debug_value %0 : $Optional<Int>, let, name "x" // CHECK-NEXT: return %0 : $Optional<Int> // CHECK-NEXT:} func opt_to_opt_trivial(_ x: Int?) -> Int! { return x } // CHECK-LABEL: sil hidden [ossa] @$s4main07opt_to_B10_referenceyAA1CCSgAEF // CHECK: bb0([[ARG:%.*]] : @guaranteed $Optional<C>): // CHECK: debug_value [[ARG]] : $Optional<C>, let, name "x" // CHECK: [[RESULT:%.*]] = copy_value [[ARG]] // CHECK-NOT: destroy_value [[ARG]] // CHECK: return [[RESULT]] : $Optional<C> // CHECK: } // end sil function '$s4main07opt_to_B10_referenceyAA1CCSgAEF' func opt_to_opt_reference(_ x : C!) -> C? { return x } // CHECK-LABEL: sil hidden [ossa] @$s4main07opt_to_B12_addressOnly{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $*Optional<T>, %1 : $*Optional<T>): // CHECK-NEXT: debug_value %1 : $*Optional<T>, let, name "x", {{.*}} expr op_deref // CHECK-NEXT: copy_addr %1 to [init] %0 // CHECK-NOT: destroy_addr %1 func opt_to_opt_addressOnly<T>(_ x : T!) -> T? { return x } class C {} public struct TestAddressOnlyStruct<T> { func f(_ a : T?) {} // CHECK-LABEL: sil hidden [ossa] @$s4main21TestAddressOnlyStructV8testCall{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $*Optional<T>, %1 : $TestAddressOnlyStruct<T>): // CHECK: apply {{.*}}<T>(%0, %1) func testCall(_ a : T!) { f(a) } } // CHECK-LABEL: sil hidden [ossa] @$s4main35testContextualInitOfNonAddrOnlyTypeyySiSgF // CHECK: bb0(%0 : $Optional<Int>): // CHECK-NEXT: debug_value %0 : $Optional<Int>, let, name "a" // CHECK-NEXT: [[X:%.*]] = alloc_box ${ var Optional<Int> }, var, name "x" // CHECK-NEXT: [[PB:%.*]] = project_box [[X]] // CHECK-NEXT: store %0 to [trivial] [[PB]] : $*Optional<Int> // CHECK-NEXT: destroy_value [[X]] : ${ var Optional<Int> } func testContextualInitOfNonAddrOnlyType(_ a : Int?) { var x: Int! = a }
apache-2.0
2692f3ec600fb53cb1754b21827fc925
42.009569
163
0.578151
2.879244
false
false
false
false
chenchangqing/travelMapMvvm
travelMapMvvm/travelMapMvvm/ViewModels/POIMapViewModel.swift
1
3515
// // POIMapViewModel.swift // travelMapMvvm // // Created by green on 15/9/11. // Copyright (c) 2015年 travelMapMvvm. All rights reserved. // import ReactiveViewModel import ReactiveCocoa import MapKit class POIMapViewModel: POIListViewModel { // MARK: - 标注 var basicMapAnnotationDic = OrderedDictionary<BasicMapAnnotation,BasicMapAnnotationView>() var distanceAnnotationDic = OrderedDictionary<DistanceAnnotation,DistanceAnnotationView>() var selectedBasicMapAnnotation : BasicMapAnnotation! // MARK: - 定位类 let locationManager = LocationManager.sharedInstance dynamic var lastCoordinate: CLLocationCoordinate2DModel? dynamic var lastUserAnnotation: MKAnnotation? // MARK: - Commands var updatingLocationPlacemarkCommand: RACCommand! override init(paramTuple:(queryType:QueryTypeEnum, poiType:POITypeEnum?, param:String)) { super.init(paramTuple: paramTuple) locationManager.showVerboseMessage = true locationManager.autoUpdate = true // 标准定位 updatingLocationPlacemarkCommand = RACCommand(signalBlock: { (any:AnyObject!) -> RACSignal! in if let coordinateModel = any as? CLLocationCoordinate2DModel { return RACSignal.createSignal({ (subscriber:RACSubscriber!) -> RACDisposable! in self.locationManager.reverseGeocodeLocationWithLatLon(latitude: coordinateModel.latitude, longitude: coordinateModel.longitude) { (reverseGecodeInfo, placemark, error) -> Void in if error != nil { subscriber.sendError(ErrorEnum.GeocodeLocationError.error) } else { subscriber.sendNext(placemark) subscriber.sendCompleted() } } return nil }).materialize() } else { return RACSignal.empty() } }) self.didBecomeActiveSignal.subscribeNext { (any:AnyObject!) -> Void in self.refreshCommand.execute(nil) } } /** * 获得标注数组元组 */ func getAnnotationTuple(poiModel:POIModel, i:Int) -> (basicMapAnnotation:BasicMapAnnotation?,distanceAnnotation:DistanceAnnotation?) { var basicAnnotation : BasicMapAnnotation? var distanceAnnotation : DistanceAnnotation? var latitude : CLLocationDegrees? var longitude : CLLocationDegrees? if poiModel.latitude != nil && poiModel.latitude != "" { latitude = (poiModel.latitude! as NSString).doubleValue } if poiModel.longitude != nil && poiModel.longitude != "" { longitude = (poiModel.longitude! as NSString).doubleValue } if latitude != nil && longitude != nil { basicAnnotation = BasicMapAnnotation(latitude: latitude!, longitude: longitude!, index: i) distanceAnnotation = DistanceAnnotation(latitude: latitude!, longitude: longitude!, distance: "-") } return (basicAnnotation,distanceAnnotation) } }
apache-2.0
2aff5111c56b7b782778a8a95ef626e5
32.451923
198
0.576315
5.722039
false
false
false
false
embassem/NetworkService
Demo/Shared/GitHubAPI.swift
1
2729
import Foundation import Moya // MARK: - Provider setup private func JSONResponseDataFormatter(_ data: Data) -> Data { do { let dataAsJSON = try JSONSerialization.jsonObject(with: data) let prettyData = try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted) return prettyData } catch { return data // fallback to original data if it can't be serialized. } } let GitHubProvider = MoyaProvider<GitHub>(plugins: [NetworkLoggerPlugin(verbose: true, responseDataFormatter: JSONResponseDataFormatter)]) // MARK: - Provider support private extension String { var urlEscaped: String { return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! } } public enum GitHub { case zen case userProfile(String) case userRepositories(String) } extension GitHub: TargetType { public var baseURL: URL { return URL(string: "https://api.github.com")! } public var path: String { switch self { case .zen: return "/zen" case .userProfile(let name): return "/users/\(name.urlEscaped)" case .userRepositories(let name): return "/users/\(name.urlEscaped)/repos" } } public var method: Moya.Method { return .get } public var parameters: [String: Any]? { switch self { case .userRepositories(_): return ["sort": "pushed"] default: return nil } } public var parameterEncoding: ParameterEncoding { return URLEncoding.default } public var task: Task { return .requestPlain } public var validate: Bool { switch self { case .zen: return true default: return false } } public var sampleData: Data { switch self { case .zen: return "Half measures are as bad as nothing at all.".data(using: String.Encoding.utf8)! case .userProfile(let name): return "{\"login\": \"\(name)\", \"id\": 100}".data(using: String.Encoding.utf8)! case .userRepositories(_): return "[{\"name\": \"Repo Name\"}]".data(using: String.Encoding.utf8)! } } public var headers: [String: String]? { return nil } } public func url(_ route: TargetType) -> String { return route.baseURL.appendingPathComponent(route.path).absoluteString } //MARK: - Response Handlers extension Moya.Response { func mapNSArray() throws -> NSArray { let any = try self.mapJSON() guard let array = any as? NSArray else { throw MoyaError.jsonMapping(self) } return array } }
mit
a499039a5d8e6b7b7cf492f071e5f6e2
26.565657
138
0.608648
4.609797
false
false
false
false
marcelmueller/MyWeight
MyWeight/Screens/List/ListViewModel.swift
1
1373
// // ListViewModel.swift // MyWeight // // Created by Diogo on 09/10/16. // Copyright © 2016 Diogo Tridapalli. All rights reserved. // import Foundation public protocol ListViewModelProtocol { var items: UInt { get } var data: (_ item: UInt) -> MassViewModel { get } var buttonTitle: String { get } var emptyListViewModel: TitleDescriptionViewModelProtocol? { get } var didTapAction: () -> Void { get } } public struct ListViewModel: ListViewModelProtocol { public let items: UInt public let data: (UInt) -> MassViewModel public let buttonTitle: String public let emptyListViewModel: TitleDescriptionViewModelProtocol? public let didTapAction: () -> Void } extension ListViewModel { public init() { items = 0 data = { _ in MassViewModel() } buttonTitle = Localization.addButton didTapAction = { Log.debug("Add button tap") } emptyListViewModel = EmptyListViewModel() } } extension ListViewModel { public init(with masses: [Mass], didTap: @escaping () -> Void) { items = UInt(masses.count) data = { MassViewModel(with: masses[Int($0)], large: $0 == 0) } buttonTitle = Localization.addButton didTapAction = didTap emptyListViewModel = items == 0 ? EmptyListViewModel() : nil } }
mit
f1a47a7a8664f9ff745e76f75dd9cee2
18.884058
71
0.63484
4.369427
false
false
false
false
xcodeswift/xcproj
Sources/XcodeProj/Objects/Files/XCVersionGroup.swift
1
4234
import Foundation import PathKit /// Group that contains multiple files references to the different versions of a resource. /// Used to contain the different versions of a xcdatamodel public final class XCVersionGroup: PBXGroup { // MARK: - Attributes /// Current version. var currentVersionReference: PBXObjectReference? /// Returns the current version file reference. public var currentVersion: PBXFileReference? { get { currentVersionReference?.getObject() } set { currentVersionReference = newValue?.reference } } /// Version group type. public var versionGroupType: String? // MARK: - Init /// Initializes the group with its attributes. /// /// - Parameters: /// - currentVersion: current version file reference. /// - name: group name. /// - path: group relative path from `sourceTree`, if different than `name`. /// - sourceTree: group source tree. /// - versionGroupType: identifier of the group type. /// - children: group children. /// - includeInIndex: should the IDE index the files in the group? /// - wrapsLines: should the IDE wrap lines for files in the group? /// - usesTabs: group uses tabs. /// - indentWidth: the number of positions to indent blocks of code /// - tabWidth: the visual width of tab characters public init(currentVersion: PBXFileReference? = nil, path: String? = nil, name: String? = nil, sourceTree: PBXSourceTree? = nil, versionGroupType: String? = nil, children: [PBXFileElement] = [], includeInIndex: Bool? = nil, wrapsLines: Bool? = nil, usesTabs: Bool? = nil, indentWidth: UInt? = nil, tabWidth: UInt? = nil) { currentVersionReference = currentVersion?.reference self.versionGroupType = versionGroupType super.init(children: children, sourceTree: sourceTree, name: name, path: path, includeInIndex: includeInIndex, wrapsLines: wrapsLines, usesTabs: usesTabs, indentWidth: indentWidth, tabWidth: tabWidth) } // MARK: - Decodable fileprivate enum CodingKeys: String, CodingKey { case currentVersion case versionGroupType } public required init(from decoder: Decoder) throws { let objects = decoder.context.objects let objectReferenceRepository = decoder.context.objectReferenceRepository let container = try decoder.container(keyedBy: CodingKeys.self) if let currentVersionReference = try container.decodeIfPresent(String.self, forKey: .currentVersion) { self.currentVersionReference = objectReferenceRepository.getOrCreate(reference: currentVersionReference, objects: objects) } else { currentVersionReference = nil } versionGroupType = try container.decodeIfPresent(String.self, forKey: .versionGroupType) try super.init(from: decoder) } // MARK: - XCVersionGroup Extension (PlistSerializable) override func plistKeyAndValue(proj: PBXProj, reference: String) throws -> (key: CommentedString, value: PlistValue) { var dictionary: [CommentedString: PlistValue] = try super.plistKeyAndValue(proj: proj, reference: reference).value.dictionary ?? [:] dictionary["isa"] = .string(CommentedString(XCVersionGroup.isa)) if let versionGroupType = versionGroupType { dictionary["versionGroupType"] = .string(CommentedString(versionGroupType)) } if let currentVersionReference = currentVersionReference { let fileElement: PBXFileElement? = currentVersionReference.getObject() dictionary["currentVersion"] = .string(CommentedString(currentVersionReference.value, comment: fileElement?.fileName())) } return (key: CommentedString(reference, comment: path?.split(separator: "/").last.map(String.init)), value: .dictionary(dictionary)) } }
mit
61ad2381e2143328d5bcd8915f2f577a
41.34
140
0.636278
5.076739
false
false
false
false
fgengine/quickly
Quickly/ViewControllers/Push/Animation/QPushViewControllerInteractiveAnimation.swift
1
3783
// // Quickly // public final class QPushViewControllerInteractiveDismissAnimation : IQPushViewControllerInteractiveAnimation { public var viewController: IQPushViewController! public var position: CGPoint public var deltaPosition: CGFloat public var velocity: CGPoint public var dismissDistance: CGFloat public var acceleration: CGFloat public var deceleration: CGFloat public private(set) var canFinish: Bool public init(dismissDistance: CGFloat = 40, acceleration: CGFloat = 600, deceleration: CGFloat = 0.25) { self.position = CGPoint.zero self.deltaPosition = 0 self.velocity = CGPoint.zero self.dismissDistance = dismissDistance self.acceleration = acceleration self.deceleration = deceleration self.canFinish = false } public func prepare(viewController: IQPushViewController, position: CGPoint, velocity: CGPoint) { self.viewController = viewController self.viewController.layoutIfNeeded() self.viewController.prepareInteractiveDismiss() self.position = position self.velocity = velocity } public func update(position: CGPoint, velocity: CGPoint) { let deltaPosition = position.y - self.position.y if deltaPosition > 0 { let height = self.viewController.viewController.view.frame.height let progress = abs(deltaPosition) / height if progress > self.deceleration { var limit = self.deceleration var multiplier = self.deceleration while progress > limit { limit = limit + (limit * self.deceleration) multiplier *= multiplier } self.deltaPosition = deltaPosition * (self.deceleration + ((progress - self.deceleration) * multiplier)) } else { self.deltaPosition = deltaPosition * progress } self.canFinish = false } else { self.deltaPosition = deltaPosition self.canFinish = abs(deltaPosition) > self.dismissDistance } self.viewController.offset = self.deltaPosition } public func cancel(_ complete: @escaping (_ completed: Bool) -> Void) { let duration = TimeInterval(self.deltaPosition / self.acceleration) UIView.animate(withDuration: duration, delay: 0, options: [ .beginFromCurrentState, .layoutSubviews ], animations: { self.viewController.offset = 0 self.viewController.layoutIfNeeded() }, completion: { (completed: Bool) in self.viewController.cancelInteractiveDismiss() self.viewController = nil complete(completed) }) } public func finish(_ complete: @escaping (_ completed: Bool) -> Void) { self.viewController.willDismiss(animated: true) let offset = self.viewController.offset let height = self.viewController.viewController.view.frame.height let edgeInsets = self.viewController.inheritedEdgeInsets let hideOffset = height + edgeInsets.top let duration = TimeInterval((hideOffset - offset) / self.acceleration) UIView.animate(withDuration: duration, delay: 0, options: [ .beginFromCurrentState, .layoutSubviews ], animations: { self.viewController.offset = -hideOffset self.viewController.layoutIfNeeded() }, completion: { (completed: Bool) in self.viewController.didDismiss(animated: true) self.viewController.finishInteractiveDismiss() self.viewController.state = .hide self.viewController.offset = 0 self.viewController = nil complete(completed) }) } }
mit
c906bfe3951adf1f035ae2cc57bf94c0
41.033333
124
0.648692
5.381223
false
false
false
false
annecruz/MDCSwipeToChoose
Examples/SwiftLikedOrNope/SwiftLikedOrNope/ChoosePersonViewController.swift
2
9085
// // ChoosePersonViewController.swift // SwiftLikedOrNope // // Copyright (c) 2014 to present, Richard Burdish @rjburdish // // 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 class ChoosePersonViewController: UIViewController, MDCSwipeToChooseDelegate { var people:[Person] = [] let ChoosePersonButtonHorizontalPadding:CGFloat = 80.0 let ChoosePersonButtonVerticalPadding:CGFloat = 20.0 var currentPerson:Person! var frontCardView:ChoosePersonView! var backCardView:ChoosePersonView! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.people = defaultPeople() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.people = defaultPeople() // Here you can init your properties } override func viewDidLoad(){ super.viewDidLoad() // Display the first ChoosePersonView in front. Users can swipe to indicate // whether they like or dislike the person displayed. self.setMyFrontCardView(self.popPersonViewWithFrame(frontCardViewFrame())!) self.view.addSubview(self.frontCardView) // Display the second ChoosePersonView in back. This view controller uses // the MDCSwipeToChooseDelegate protocol methods to update the front and // back views after each user swipe. self.backCardView = self.popPersonViewWithFrame(backCardViewFrame())! self.view.insertSubview(self.backCardView, belowSubview: self.frontCardView) // Add buttons to programmatically swipe the view left or right. // See the `nopeFrontCardView` and `likeFrontCardView` methods. constructNopeButton() constructLikedButton() } func suportedInterfaceOrientations() -> UIInterfaceOrientationMask{ return UIInterfaceOrientationMask.Portrait } // This is called when a user didn't fully swipe left or right. func viewDidCancelSwipe(view: UIView) -> Void{ print("You couldn't decide on \(self.currentPerson.Name)"); } // This is called then a user swipes the view fully left or right. func view(view: UIView, wasChosenWithDirection: MDCSwipeDirection) -> Void{ // MDCSwipeToChooseView shows "NOPE" on swipes to the left, // and "LIKED" on swipes to the right. if(wasChosenWithDirection == MDCSwipeDirection.Left){ print("You noped: \(self.currentPerson.Name)") } else{ print("You liked: \(self.currentPerson.Name)") } // MDCSwipeToChooseView removes the view from the view hierarchy // after it is swiped (this behavior can be customized via the // MDCSwipeOptions class). Since the front card view is gone, we // move the back card to the front, and create a new back card. if(self.backCardView != nil){ self.setMyFrontCardView(self.backCardView) } backCardView = self.popPersonViewWithFrame(self.backCardViewFrame()) //if(true){ // Fade the back card into view. if(backCardView != nil){ self.backCardView.alpha = 0.0 self.view.insertSubview(self.backCardView, belowSubview: self.frontCardView) UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseInOut, animations: { self.backCardView.alpha = 1.0 },completion:nil) } } func setMyFrontCardView(frontCardView:ChoosePersonView) -> Void{ // Keep track of the person currently being chosen. // Quick and dirty, just for the purposes of this sample app. self.frontCardView = frontCardView self.currentPerson = frontCardView.person } func defaultPeople() -> [Person]{ // It would be trivial to download these from a web service // as needed, but for the purposes of this sample app we'll // simply store them in memory. return [Person(name: "Finn", image: UIImage(named: "finn"), age: 21, sharedFriends: 3, sharedInterest: 4, photos: 5), Person(name: "Jake", image: UIImage(named: "jake"), age: 21, sharedFriends: 3, sharedInterest: 4, photos: 5), Person(name: "Fiona", image: UIImage(named: "fiona"), age: 21, sharedFriends: 3, sharedInterest: 4, photos: 5), Person(name: "P.Gumball", image: UIImage(named: "prince"), age: 21, sharedFriends: 3, sharedInterest: 4, photos: 5)] } func popPersonViewWithFrame(frame:CGRect) -> ChoosePersonView?{ if(self.people.count == 0){ return nil; } // UIView+MDCSwipeToChoose and MDCSwipeToChooseView are heavily customizable. // Each take an "options" argument. Here, we specify the view controller as // a delegate, and provide a custom callback that moves the back card view // based on how far the user has panned the front card view. let options:MDCSwipeToChooseViewOptions = MDCSwipeToChooseViewOptions() options.delegate = self //options.threshold = 160.0 options.onPan = { state -> Void in if(self.backCardView != nil){ let frame:CGRect = self.frontCardViewFrame() self.backCardView.frame = CGRectMake(frame.origin.x, frame.origin.y-(state.thresholdRatio * 10.0), CGRectGetWidth(frame), CGRectGetHeight(frame)) } } // Create a personView with the top person in the people array, then pop // that person off the stack. let personView:ChoosePersonView = ChoosePersonView(frame: frame, person: self.people[0], options: options) self.people.removeAtIndex(0) return personView } func frontCardViewFrame() -> CGRect{ let horizontalPadding:CGFloat = 20.0 let topPadding:CGFloat = 60.0 let bottomPadding:CGFloat = 200.0 return CGRectMake(horizontalPadding,topPadding,CGRectGetWidth(self.view.frame) - (horizontalPadding * 2), CGRectGetHeight(self.view.frame) - bottomPadding) } func backCardViewFrame() ->CGRect{ let frontFrame:CGRect = frontCardViewFrame() return CGRectMake(frontFrame.origin.x, frontFrame.origin.y + 10.0, CGRectGetWidth(frontFrame), CGRectGetHeight(frontFrame)) } func constructNopeButton() -> Void{ let button:UIButton = UIButton(type: UIButtonType.System) let image:UIImage = UIImage(named:"nope")! button.frame = CGRectMake(ChoosePersonButtonHorizontalPadding, CGRectGetMaxY(self.backCardView.frame) + ChoosePersonButtonVerticalPadding, image.size.width, image.size.height) button.setImage(image, forState: UIControlState.Normal) button.tintColor = UIColor(red: 247.0/255.0, green: 91.0/255.0, blue: 37.0/255.0, alpha: 1.0) button.addTarget(self, action: "nopeFrontCardView", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(button) } func constructLikedButton() -> Void{ let button:UIButton = UIButton(type: UIButtonType.System) let image:UIImage = UIImage(named:"liked")! button.frame = CGRectMake(CGRectGetMaxX(self.view.frame) - image.size.width - ChoosePersonButtonHorizontalPadding, CGRectGetMaxY(self.backCardView.frame) + ChoosePersonButtonVerticalPadding, image.size.width, image.size.height) button.setImage(image, forState:UIControlState.Normal) button.tintColor = UIColor(red: 29.0/255.0, green: 245.0/255.0, blue: 106.0/255.0, alpha: 1.0) button.addTarget(self, action: "likeFrontCardView", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(button) } func nopeFrontCardView() -> Void{ self.frontCardView.mdc_swipe(MDCSwipeDirection.Left) } func likeFrontCardView() -> Void{ self.frontCardView.mdc_swipe(MDCSwipeDirection.Right) } }
mit
6bf305a5a3ffb254c6d2b504ac1a5a8c
47.329787
464
0.680462
4.455615
false
false
false
false
immortal79/BetterUpdates
BetterUpdates/mas-cli/NSURLSession+Synchronous.swift
1
2326
// // NSURLSession+Synchronous.swift // mas-cli // // Created by Michael Schneider on 4/14/16. // Copyright © 2016 Andrew Naylor. All rights reserved. // // Synchronous NSURLSession code found at: http://ericasadun.com/2015/11/12/more-bad-things-synchronous-nsurlsessions/ import Foundation /// NSURLSession synchronous behavior /// Particularly for playground sessions that need to run sequentially public extension URLSession { /// Return data from synchronous URL request public static func requestSynchronousData(_ request: URLRequest) -> Data? { var data: Data? = nil let semaphore = DispatchSemaphore(value: 0) let task = URLSession.shared.dataTask(with: request) { taskData, _, error -> () in data = taskData if data == nil, let error = error {print(error)} semaphore.signal() } task.resume() let _ = semaphore.wait(timeout: .distantFuture) return data } /// Return data synchronous from specified endpoint public static func requestSynchronousDataWithURLString(_ requestString: String) -> Data? { guard let url = URL(string:requestString) else {return nil} let request = URLRequest(url: url) return URLSession.requestSynchronousData(request) } /// Return JSON synchronous from URL request public static func requestSynchronousJSON(_ request: URLRequest) -> Any? { guard let data = URLSession.requestSynchronousData(request) else {return nil} return try! JSONSerialization.jsonObject(with: data, options: []) } /// Return JSON synchronous from specified endpoint public static func requestSynchronousJSONWithURLString(_ requestString: String) -> Any? { guard let url = URL(string: requestString) else {return nil} var request = URLRequest(url:url) request.httpMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Content-Type") return URLSession.requestSynchronousJSON(request) } } public extension String { /// Return an URL encoded string func URLEncodedString() -> String? { let customAllowedSet = CharacterSet.urlQueryAllowed return addingPercentEncoding(withAllowedCharacters: customAllowedSet) } }
mit
efe819aade8b0d51f012de2e5d2e5322
35.904762
118
0.68043
4.813665
false
false
false
false
vmanot/swift-package-manager
Sources/TestSupport/misc.swift
1
11561
/* 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 http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import func XCTest.XCTFail import class Foundation.NSDate import Basic import PackageDescription import PackageDescription4 import PackageGraph import PackageModel import POSIX import SourceControl import Utility import Workspace import Commands #if os(macOS) import class Foundation.Bundle #endif /// Test-helper function that runs a block of code on a copy of a test fixture /// package. The copy is made into a temporary directory, and the block is /// given a path to that directory. The block is permitted to modify the copy. /// The temporary copy is deleted after the block returns. The fixture name may /// contain `/` characters, which are treated as path separators, exactly as if /// the name were a relative path. public func fixture( name: String, file: StaticString = #file, line: UInt = #line, body: (AbsolutePath) throws -> Void ) { do { // Make a suitable test directory name from the fixture subpath. let fixtureSubpath = RelativePath(name) let copyName = fixtureSubpath.components.joined(separator: "_") // Create a temporary directory for the duration of the block. let tmpDir = try TemporaryDirectory(prefix: copyName) defer { // Unblock and remove the tmp dir on deinit. try? localFileSystem.chmod(.userWritable, path: tmpDir.path, options: [.recursive]) try? localFileSystem.removeFileTree(tmpDir.path) } // Construct the expected path of the fixture. // FIXME: This seems quite hacky; we should provide some control over where fixtures are found. let fixtureDir = AbsolutePath(#file).appending(RelativePath("../../../Fixtures")).appending(fixtureSubpath) // Check that the fixture is really there. guard isDirectory(fixtureDir) else { XCTFail("No such fixture: \(fixtureDir.asString)", file: file, line: line) return } // The fixture contains either a checkout or just a Git directory. if isFile(fixtureDir.appending(component: "Package.swift")) { // It's a single package, so copy the whole directory as-is. let dstDir = tmpDir.path.appending(component: copyName) try systemQuietly("cp", "-R", "-H", fixtureDir.asString, dstDir.asString) // Invoke the block, passing it the path of the copied fixture. try body(dstDir) } else { // Copy each of the package directories and construct a git repo in it. for fileName in try! localFileSystem.getDirectoryContents(fixtureDir).sorted() { let srcDir = fixtureDir.appending(component: fileName) guard isDirectory(srcDir) else { continue } let dstDir = tmpDir.path.appending(component: fileName) try systemQuietly("cp", "-R", "-H", srcDir.asString, dstDir.asString) initGitRepo(dstDir, tag: "1.2.3", addFile: false) } // Invoke the block, passing it the path of the copied fixture. try body(tmpDir.path) } } catch SwiftPMProductError.executionFailure(let error, let output, let stderr) { print("**** FAILURE EXECUTING SUBPROCESS ****") print("output:", output) print("stderr:", stderr) XCTFail("\(error)", file: file, line: line) } catch { XCTFail("\(error)", file: file, line: line) } } /// Test-helper function that creates a new Git repository in a directory. The new repository will contain /// exactly one empty file unless `addFile` is `false`, and if a tag name is provided, a tag with that name will be /// created. public func initGitRepo( _ dir: AbsolutePath, tag: String? = nil, addFile: Bool = true, file: StaticString = #file, line: UInt = #line ) { initGitRepo(dir, tags: tag.flatMap({ [$0] }) ?? [], addFile: addFile, file: file, line: line) } public func initGitRepo( _ dir: AbsolutePath, tags: [String], addFile: Bool = true, file: StaticString = #file, line: UInt = #line ) { do { if addFile { let file = dir.appending(component: "file.swift") try systemQuietly(["touch", file.asString]) } try systemQuietly([Git.tool, "-C", dir.asString, "init"]) try systemQuietly([Git.tool, "-C", dir.asString, "config", "user.email", "[email protected]"]) try systemQuietly([Git.tool, "-C", dir.asString, "config", "user.name", "Example Example"]) try systemQuietly([Git.tool, "-C", dir.asString, "config", "commit.gpgsign", "false"]) let repo = GitRepository(path: dir) try repo.stageEverything() try repo.commit(message: "msg") for tag in tags { try repo.tag(name: tag) } } catch { XCTFail("\(error)", file: file, line: line) } } public enum Configuration { case Debug case Release } private var globalSymbolInMainBinary = 0 @discardableResult public func executeSwiftBuild( _ packagePath: AbsolutePath, configuration: Configuration = .Debug, printIfError: Bool = false, Xcc: [String] = [], Xld: [String] = [], Xswiftc: [String] = [], env: [String: String]? = nil ) throws -> String { var args = ["--configuration"] switch configuration { case .Debug: args.append("debug") case .Release: args.append("release") } args += Xcc.flatMap({ ["-Xcc", $0] }) args += Xld.flatMap({ ["-Xlinker", $0] }) args += Xswiftc.flatMap({ ["-Xswiftc", $0] }) return try SwiftPMProduct.SwiftBuild.execute(args, packagePath: packagePath, env: env, printIfError: printIfError) } /// Test helper utility for executing a block with a temporary directory. public func mktmpdir( function: StaticString = #function, file: StaticString = #file, line: UInt = #line, body: (AbsolutePath) throws -> Void ) { do { let cleanedFunction = function.description .replacingOccurrences(of: "(", with: "") .replacingOccurrences(of: ")", with: "") .replacingOccurrences(of: ".", with: "") let tmpDir = try TemporaryDirectory(prefix: "spm-tests-\(cleanedFunction)") defer { // Unblock and remove the tmp dir on deinit. try? localFileSystem.chmod(.userWritable, path: tmpDir.path, options: [.recursive]) try? localFileSystem.removeFileTree(tmpDir.path) } try body(tmpDir.path) } catch { XCTFail("\(error)", file: file, line: line) } } public func systemQuietly(_ args: [String]) throws { // Discard the output, by default. // // FIXME: Find a better default behavior here. try Process.checkNonZeroExit(arguments: args) } public func systemQuietly(_ args: String...) throws { try systemQuietly(args) } /// Loads a mock package graph based on package packageMap dictionary provided where key is path to a package. public func loadMockPackageGraph( _ packageMap: [String: PackageDescription.Package], root: String, diagnostics: DiagnosticsEngine = DiagnosticsEngine(), in fs: FileSystem ) -> PackageGraph { var externalManifests = [Manifest]() var rootManifest: Manifest! for (url, package) in packageMap { let manifest = Manifest( path: AbsolutePath(url).appending(component: Manifest.filename), url: url, package: .v3(package), version: "1.0.0" ) if url == root { rootManifest = manifest } else { externalManifests.append(manifest) } } let root = PackageGraphRoot(input: PackageGraphRootInput(packages: [AbsolutePath(root)]), manifests: [rootManifest]) return PackageGraphLoader().load(root: root, externalManifests: externalManifests, diagnostics: diagnostics, fileSystem: fs) } public func loadMockPackageGraph4( _ packageMap: [String: PackageDescription4.Package], root: String, diagnostics: DiagnosticsEngine = DiagnosticsEngine(), in fs: FileSystem ) -> PackageGraph { var externalManifests = [Manifest]() var rootManifest: Manifest! for (url, package) in packageMap { let manifest = Manifest( path: AbsolutePath(url).appending(component: Manifest.filename), url: url, package: .v4(package), version: "1.0.0" ) if url == root { rootManifest = manifest } else { externalManifests.append(manifest) } } let root = PackageGraphRoot(input: PackageGraphRootInput(packages: [AbsolutePath(root)]), manifests: [rootManifest]) return PackageGraphLoader().load(root: root, externalManifests: externalManifests, diagnostics: diagnostics, fileSystem: fs) } /// Temporary override environment variables /// /// WARNING! This method is not thread-safe. POSIX environments are shared /// between threads. This means that when this method is called simultaneously /// from different threads, the environment will neither be setup nor restored /// correctly. /// /// - throws: errors thrown in `body`, POSIX.SystemError.setenv and /// POSIX.SystemError.unsetenv public func withCustomEnv(_ env: [String: String], body: () throws -> Void) throws { let state = Array(env.keys).map({ ($0, getenv($0)) }) let restore = { for (key, value) in state { if let value = value { try setenv(key, value: value) } else { try unsetenv(key) } } } do { for (key, value) in env { try setenv(key, value: value) } try body() } catch { try? restore() throw error } try restore() } /// Waits for a file to appear for around 1 second. /// Returns true if found, false otherwise. public func waitForFile(_ path: AbsolutePath) -> Bool { let endTime = NSDate().timeIntervalSince1970 + 2 while NSDate().timeIntervalSince1970 < endTime { // Sleep for a bit so we don't burn a lot of CPU. try? usleep(microSeconds: 10000) if localFileSystem.exists(path) { return true } } return false } extension Process { /// If the given pid is running or not. /// /// - Parameters: /// - pid: The pid to check. /// - orDefunct: If set to true, the method will also check if pid is defunct and return false. /// - Returns: True if the given pid is running. public static func running(_ pid: ProcessID, orDefunct: Bool = false) throws -> Bool { // Shell out to `ps -s` instead of using getpgid() as that is more deterministic on linux. let result = try Process.popen(arguments: ["ps", "-p", String(pid)]) // If ps -p exited with return code 1, it means there is no entry for the process. var exited = result.exitStatus == .terminated(code: 1) if orDefunct { // Check if the process became defunct. exited = try exited || result.utf8Output().contains("defunct") } return !exited } } extension Destination { public static let host = try! hostDestination() }
apache-2.0
5187461684d6411a16dfbc7a34aca8de
34.903727
128
0.634547
4.323485
false
false
false
false
seanooi/DocuParse
DocuParse/AppDelegate.swift
1
2914
// // AppDelegate.swift // DocuParse // // Created by Sean Ooi on 6/25/15. // Copyright (c) 2015 Sean Ooi. All rights reserved. // import UIKit import Parse import Bolts @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { Parse.enableLocalDatastore() // Initialize Parse. Parse.setApplicationId("pGf1Ah95DLQeFh9RQUYqnw9ga6ZbOnIiqOQlx0JZ", clientKey: "bOubHTXRiUSIpmzlad7M4I39TzNd5pdtuTHOopm8") if PFUser.currentUser() == nil { let storyboard = UIStoryboard(name: "Login", bundle: nil) let loginController = storyboard.instantiateViewControllerWithIdentifier("LoginViewController") window?.rootViewController = loginController } else { let storyboard = UIStoryboard(name: "Main", bundle: nil) let mainController = storyboard.instantiateViewControllerWithIdentifier("MainNavigationController") as! UINavigationController window?.rootViewController = mainController } return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
5e4f1f4b8cb82267464f7ab897f4b4c6
44.53125
285
0.727179
5.288566
false
false
false
false
nodekit-io/nodekit-darwin
src/nodekit/NKElectro/NKEDialog/NKEDialog-ios.swift
1
2911
/* * nodekit.io * * Copyright (c) 2016 OffGrid Networks. All Rights Reserved. * Portions Copyright (c) 2013 GitHub, Inc. under MIT License * * 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. */ #if os(iOS) import Foundation import UIKit extension NKE_Dialog: NKScriptExport { static func attachTo(context: NKScriptContext) { let principal = NKE_Dialog() context.loadPlugin(principal, namespace: "io.nodekit.electro.dialog", options: [String:AnyObject]()) } } class NKE_Dialog: NSObject, NKE_DialogProtocol { private static func NotImplemented(functionName: String = #function) -> Void { NKLogging.log("!dialog.\(functionName) is not available for iOS") } func showOpenDialog(browserWindow: NKE_BrowserWindow?, options: Dictionary<String, AnyObject>?, callback: NKScriptValue?) -> Void { NKE_Dialog.NotImplemented() } func showSaveDialog(browserWindow: NKE_BrowserWindow?, options: Dictionary<String, AnyObject>?, callback: NKScriptValue?)-> Void { NKE_Dialog.NotImplemented() } func showMessageBox(browserWindow: NKE_BrowserWindow?, options: Dictionary<String, AnyObject>?, callback: NKScriptValue?) -> Void { let buttons: [String] = (options?["buttons"] as? [String]) ?? ["Ok"] let title: String = (options?["title"] as? String) ?? "" let message: String = (options?["message"] as? String) ?? "" let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) for i in 0 ..< buttons.count { let buttonTitle: String = buttons[i] ?? "" let buttonAction = UIAlertAction(title: buttonTitle, style: (buttonTitle == "Cancel" ? .Cancel : .Default)) { (action) in callback?.callWithArguments([i], completionHandler: nil) } alertController.addAction(buttonAction) } guard let viewController = UIApplication.sharedApplication().delegate!.window!?.rootViewController else {return;} viewController.presentViewController(alertController, animated: true, completion: nil) } func showErrorBox(title: String, content: String) -> Void { self.showMessageBox(nil, options: ["message": title, "detail": content, "type": "error"], callback: nil) } } #endif
apache-2.0
bc2c0c6eed254695aa837f52b514a712
29.020619
135
0.662315
4.569859
false
false
false
false
AgaKhanFoundation/WCF-iOS
Steps4Impact/Journey/Cells/CurrentMilestoneCell.swift
1
6063
// // MilestoneCell.swift // Steps4Impact // // Created by Aalim Mulji on 11/17/19. // Copyright © 2019 AKDN. All rights reserved. // import UIKit import SnapKit struct CurrentMilestoneContext: CellContext { var identifier: String = CurrentMilestoneCell.identifier var sequence = 0 var distance = 0 var name = "" var flagName = "" var journeyMap = "" var description = "" var title = "" var subTitle = "" var media = "" var content = "" var status: MilestoneStatus = .current var progress: CGFloat = 0.0 } class CurrentMilestoneCell: ConfigurableTableViewCell { static let identifier: String = "CurrentMilestoneCell" weak var delegate: MilestoneNameButtonDelegate? let circle: UIView = { var view = UIView(frame: .zero) view.layer.cornerRadius = Style.Size.s12 view.backgroundColor = Style.Colors.FoundationGreen return view }() let verticalBar: UIView = { var view = UIView(frame: .zero) view.frame.size.width = Style.Padding.p2 view.backgroundColor = Style.Colors.Seperator return view }() let verticalProgressBar: UIView = { var view = UIView(frame: .zero) view.frame.size.width = Style.Padding.p2 return view }() let progressCircle: UIView = { var view = UIView(frame: .zero) view.layer.cornerRadius = Style.Size.s12 view.layer.applySketchShadow(color: Style.Colors.FoundationGreen, alpha: 0.5, x: 0, y: 0, blur: 8, spread: 0) return view }() let milestoneCountLabel: UILabel = { var label = UILabel(typography: .smallRegular) label.textColor = Style.Colors.black return label }() let milestoneNameButton: UIButton = { var button = UIButton() button.contentHorizontalAlignment = .left button.setTitleColor(Style.Colors.blue, for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: Style.Size.s16, weight: .regular) return button }() let containerRectangle = CardViewV2() let journeyMapImageView = WebImageView() // let journeyMapImageView: UIImageView = { // let imagevIew = UIImageView() // imagevIew.contentMode = .scaleAspectFill // imagevIew.image = Assets.journeyEmpty.image // imagevIew.clipsToBounds = true // return imagevIew // }() override func commonInit() { super.commonInit() contentView.addSubview(circle) { $0.top.equalToSuperview() $0.leading.equalToSuperview().offset(Style.Padding.p16) $0.width.height.equalTo(Style.Size.s24) } containerRectangle.addSubview(milestoneCountLabel) { $0.top.equalToSuperview().offset(Style.Padding.p4) $0.leading.equalToSuperview().offset(Style.Padding.p12) $0.trailing.equalToSuperview().inset(Style.Padding.p12) $0.height.equalTo(Style.Size.s24) } containerRectangle.addSubview(milestoneNameButton) { $0.top.equalTo(milestoneCountLabel.snp.bottom).offset(Style.Padding.p2) $0.leading.equalToSuperview().offset(Style.Padding.p12) $0.trailing.equalToSuperview().inset(Style.Padding.p12) $0.height.equalTo(Style.Size.s24) } containerRectangle.addSubview(journeyMapImageView) { $0.top.equalTo(milestoneNameButton.snp.bottom).offset(Style.Padding.p8) $0.bottom.equalToSuperview().inset(Style.Padding.p16) $0.leading.equalToSuperview().offset(Style.Padding.p12) $0.trailing.equalToSuperview().inset(Style.Padding.p12) $0.height.width.equalTo(Style.Size.s128) } contentView.addSubview(containerRectangle) { $0.top.equalToSuperview() $0.leading.equalTo(circle.snp.trailing).offset(Style.Padding.p8) $0.trailing.equalToSuperview().inset(Style.Padding.p16) $0.bottom.equalToSuperview().inset(Style.Padding.p16) } contentView.addSubview(verticalBar) { $0.top.bottom.equalToSuperview() $0.centerX.equalTo(circle) $0.width.equalTo(Style.Padding.p2) } contentView.addSubview(progressCircle) { $0.top.equalToSuperview().offset(0) $0.leading.equalToSuperview().offset(Style.Padding.p16) $0.width.height.equalTo(Style.Size.s24) } contentView.addSubview(verticalProgressBar) { $0.top.equalToSuperview() $0.centerX.equalTo(circle) $0.width.equalTo(Style.Padding.p2) $0.bottom.equalTo(progressCircle.snp.top) } milestoneNameButton.addTarget(self, action: #selector(milestoneNameButtonPressed), for: .touchUpInside) contentView.bringSubviewToFront(circle) } func configure(context: CellContext) { guard let currentMilestone = context as? CurrentMilestoneContext else { return } let progressForCell = contentView.frame.height * (currentMilestone.progress/100) circle.backgroundColor = Style.Colors.FoundationGreen verticalBar.backgroundColor = Style.Colors.Seperator progressCircle.backgroundColor = Style.Colors.white verticalProgressBar.backgroundColor = Style.Colors.FoundationGreen if currentMilestone.sequence == 0 { milestoneCountLabel.text = "Start" milestoneNameButton.isHidden = true } else { milestoneNameButton.isHidden = false milestoneCountLabel.text = "Milestone \(currentMilestone.sequence)/8" } if currentMilestone.sequence == 8 { verticalBar.isHidden = true } else { verticalBar.isHidden = false } milestoneNameButton.setTitle("\(currentMilestone.name)", for: .normal) milestoneNameButton.tag = currentMilestone.sequence // swiftlint:disable:next line_length journeyMapImageView.fadeInImage(imageURL: URL(string: currentMilestone.journeyMap), placeHolderImage: Assets.journeyEmpty.image) UIView.animate(withDuration: 1) { self.progressCircle.snp.remakeConstraints { (make) in make.top.equalToSuperview().offset(progressForCell) make.leading.equalToSuperview().offset(Style.Padding.p16) make.width.height.equalTo(Style.Size.s24) } self.contentView.layoutSubviews() } } @objc func milestoneNameButtonPressed(button: UIButton) { delegate?.milestoneNameButtonTapped(sequence: button.tag) } }
bsd-3-clause
be4da192bc3df5bdfed6eca486221ec9
32.677778
132
0.709832
3.946615
false
false
false
false
f2m2/f2m2-swift-forms
FormGeneratorExample/FormGeneratorExample/ExampleFiles/FormViewControllers/SettingsViewController.swift
1
3928
// // SettingsViewController.swift // ExampleUsage // // Created by Michael L Mork on 12/8/14. // Copyright (c) 2014 f2m2. All rights reserved. // import Foundation import UIKit let LogoutToggle = "LogoutToggle" let AllowNotifications = "AllowNotis" class SettingsViewController: UIViewController, FormControllerProtocol { @IBAction func cancelAction(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } @IBOutlet weak var tableView: UITableView! var formController: FormController? func aFormController () -> (FormController) { let logoutToggle = FormBaseObject(sectionIdx: 0, rowIdx: 0, type: UIType.TypeCustomView) logoutToggle.identifier = LogoutToggle logoutToggle.reloadOnValueChange = true let viewPrivacyPolicy = FormBaseObject(sectionIdx: 0, rowIdx: 1, type: UIType.TypeCustomView) let allowNotifications = FormBaseObject(sectionIdx: 0, rowIdx: 2, type: UIType.TypeASwitch) allowNotifications.identifier = AllowNotifications let aNewFormController = newFormController([logoutToggle, viewPrivacyPolicy, allowNotifications]) aNewFormController.tableView.allowsSelection = false return aNewFormController } override func viewDidLoad() { formController = aFormController() } /** ******************************* Use of form generator delegate. ******************************* */ func formValueChanged(obj: FormObjectProtocol) { if obj.identifier == AllowNotifications { NSUserDefaults().setBool(obj.value as Bool, forKey: AllowNotifications) } println(" formValueChanged: \(obj.value)") } func customViewForFormObject(obj: FormObjectProtocol, aView: UIView) -> (UIView?) { aView.backgroundColor = UIColor.blackColor() var button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton button.frame = CGRectMake(0, 0, CGRectGetWidth(view.frame), 50) button.backgroundColor = UIColor.lightGrayColor() var selectorStr = "privacyPolicy:" var title = "Privacy policy" if obj.identifier == LogoutToggle { selectorStr = "logoutToggle:" let isLoggedIn = NSUserDefaults().boolForKey("isLoggedIn") title = isLoggedIn ? "Log out" : "Log in" } button.setTitle(title, forState: UIControlState.Normal) button.addTarget(self, action: Selector(selectorStr), forControlEvents: UIControlEvents.TouchUpInside) aView.addSubview(button) return aView } func accompanyingLabel(obj: FormObjectProtocol, aLabel: UILabel) -> (UILabel?) { aLabel.text = "Allow notifications" return aLabel } //custom actions: func privacyPolicy(sender: UIButton) { let webViewController: WebViewController = storyboard?.instantiateViewControllerWithIdentifier("webViewController") as WebViewController//webViewController navigationController?.pushViewController(webViewController, animated: true) } func logoutToggle(sender: UIButton) { let isLoggedIn = NSUserDefaults().boolForKey("isLoggedIn") formController?.updateDataModelWithIdentifier(LogoutToggle, newValue: !isLoggedIn) NSUserDefaults().setBool(!isLoggedIn, forKey: "isLoggedIn") NSUserDefaults().synchronize() if !isLoggedIn { let userViewController: LoginVC = storyboard?.instantiateViewControllerWithIdentifier("UserViewController") as LoginVC navigationController?.pushViewController(userViewController, animated: true) } } }
mit
24e71a5a8d32bcffbd3ecaf6cec9e124
30.943089
163
0.643839
5.55587
false
false
false
false
CSullivan102/LearnApp
Learn/PocketImport/PocketImportController.swift
1
7357
// // PocketImportController.swift // Learn // // Created by Christopher Sullivan on 9/8/15. // Copyright © 2015 Christopher Sullivan. All rights reserved. // import UIKit import LearnKit import CoreData class PocketImportController: UITableViewController, ManagedObjectContextSettable, PocketAPISettable { var managedObjectContext: NSManagedObjectContext! var pocketAPI: PocketAPI! var pocketItems = [PocketItem]() var importedPocketItemIDs = [Int]() @IBOutlet weak var importButton: UIBarButtonItem! private var fetching = false private let fetchCount = 10 private var fetchOffset = 0 private let smallModalTransitioningDelegate = SmallModalTransitioningDelegate() private var modalValid = false { didSet { importButton.enabled = modalValid } } override func viewDidLoad() { super.viewDidLoad() let request = NSFetchRequest(entityName: LearnItem.entityName) request.resultType = .DictionaryResultType request.returnsDistinctResults = true request.propertiesToFetch = ["pocketItemID"] if let pocketIDResultDict = try! managedObjectContext.executeFetchRequest(request) as? [[String: Int]] { for resultDict in pocketIDResultDict { guard let itemID = resultDict["pocketItemID"] else { continue } importedPocketItemIDs.append(itemID) } } if pocketAPI.isAuthenticated() { updateViewForPocketAuthentication() } else { performSegueWithIdentifier(SegueIdentifier.ShowPocketAuth.rawValue, sender: nil) } checkModalValid() } private func updateViewForPocketAuthentication() { if let authUser = pocketAPI.getAuthenticatedUserString() { navigationItem.title = authUser } fetchPocketItems { items in self.pocketItems = self.checkPocketItemsForImported(items) self.tableView.reloadData() } } private func checkPocketItemsForImported(pocketItems: [PocketItem]) -> [PocketItem] { return pocketItems.map { (item) -> PocketItem in var updatedItem = item if let itemID = Int(item.item_id) where self.importedPocketItemIDs.contains(itemID) { updatedItem.importedToLearn = true } else { updatedItem.importedToLearn = false } return updatedItem } } private func fetchPocketItems(completion: ([PocketItem]) -> ()) { if !fetching { fetching = true pocketAPI.getPocketItemsWithCount(fetchCount, andOffset: fetchOffset) { items in self.fetching = false self.fetchOffset += self.fetchCount completion(items) } } } private func checkModalValid() { if let indexPaths = tableView.indexPathsForSelectedRows where indexPaths.count > 0 { modalValid = true } else { modalValid = false } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { checkModalValid() } override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { checkModalValid() } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return pocketItems.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let pocketItem = pocketItems[indexPath.row] let identifier = "PocketItemTableViewCell" guard let cell = tableView.dequeueReusableCellWithIdentifier(identifier) as? PocketItemTableViewCell else { fatalError("Wrong cell type for \(identifier)") } cell.pocketItem = pocketItem return cell } override func scrollViewDidScroll(scrollView: UIScrollView) { let scrollPosition = scrollView.contentOffset.y let maxScrollPosition = scrollView.contentSize.height - tableView.frame.height if scrollPosition > maxScrollPosition && maxScrollPosition > 0 { fetchPocketItems({ items in let rowsToAddRange = (self.pocketItems.count ..< self.pocketItems.count + items.count) let indexPathsToAdd = rowsToAddRange.map { NSIndexPath(forRow: $0, inSection: 0) } self.pocketItems += self.checkPocketItemsForImported(items) self.tableView.insertRowsAtIndexPaths(indexPathsToAdd, withRowAnimation: .None) }) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { guard let identifier = segue.identifier, segueIdentifier = SegueIdentifier(rawValue: identifier) else { fatalError("Invalid segue identifier \(segue.identifier)") } switch segueIdentifier { case .ShowPocketAuth: guard let vc = segue.destinationViewController as? PocketAuthModalController else { fatalError("Unexpected view controller for \(identifier) segue") } vc.pocketAPI = pocketAPI vc.completionHandler = { success in if success { self.updateViewForPocketAuthentication() } self.dismissViewControllerAnimated(true, completion: nil) } vc.modalPresentationStyle = .Custom vc.transitioningDelegate = smallModalTransitioningDelegate case .ShowImportTopicPicker: guard let vc = segue.destinationViewController as? PocketImportModalController else { fatalError("Unexpected view controller for \(identifier) segue") } vc.managedObjectContext = managedObjectContext vc.transitioningDelegate = smallModalTransitioningDelegate vc.modalPresentationStyle = .Custom guard let indexPaths = tableView.indexPathsForSelectedRows where indexPaths.count > 0 else { return } let pocketItemsToImport = indexPaths.map({ (indexPath) -> PocketItem in return pocketItems[indexPath.row] }) vc.pocketItemsToImport = pocketItemsToImport vc.completionHandler = { items in for indexPath in indexPaths { self.tableView.deselectRowAtIndexPath(indexPath, animated: false) self.pocketItems[indexPath.row].setImported(true) } self.tableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.None) self.checkModalValid() self.dismissViewControllerAnimated(true, completion: nil) } } } enum SegueIdentifier: String { case ShowPocketAuth = "ShowPocketAuth" case ShowImportTopicPicker = "ShowImportTopicPicker" } }
mit
33045bf4eadd6dc4410ef3261d97ae56
36.535714
118
0.620038
5.880096
false
false
false
false
rad182/CellSignal
Watch Extension/SessionUtility.swift
1
3345
// // WCSession.swift // CellSignal // // Created by Royce Albert Dy on 15/11/2015. // Copyright © 2015 rad182. All rights reserved. // import Foundation import WatchConnectivity import ClockKit let SessionUtility = CSSessionUtility() class CSSessionUtility: NSObject { var currentSession: WCSession? var currentRadioAccessTechnology: String? var currentSignalStrengthPercentage = 0 override init () { super.init() self.currentSession = WCSession.defaultSession() self.currentSession!.delegate = self self.currentSession!.activateSession() } // MARK: - Public Methods func refreshComplications() { let server = CLKComplicationServer.sharedInstance() for complication in server.activeComplications { server.reloadTimelineForComplication(complication) } } func updateCurrentRadioAccessTechnologyAndCurrentSignalStrengthPercentage(completion: ((currentRadioAccessTechnology: String?, currentSignalStrengthPercentage: Int) -> Void)?) { if let currentSession = self.currentSession where currentSession.reachable { currentSession.sendMessage(["request": CSCurrentRadioAccessTechnologyAndCurrentSignalStrengthPercentageRequestKey], replyHandler: { (response) -> Void in print(response) let currentRadioAccessTechnology = response[CSCurrentRadioAccessTechnologyKey] as? String let currentSignalStrengthPercentage = response[CSCurrentSignalStrengthPercentageKey] as! Int completion?(currentRadioAccessTechnology: currentRadioAccessTechnology, currentSignalStrengthPercentage: currentSignalStrengthPercentage) }, errorHandler: { (error) -> Void in print(error) }) } else { completion?(currentRadioAccessTechnology: nil, currentSignalStrengthPercentage: 0) } } func reloadComplicationData() { if let currentSession = self.currentSession where currentSession.reachable { currentSession.sendMessage(["request": CSCurrentRadioAccessTechnologyAndCurrentSignalStrengthPercentageRequestKey], replyHandler: { (response) -> Void in print(response) self.currentRadioAccessTechnology = response[CSCurrentRadioAccessTechnologyKey] as? String self.currentSignalStrengthPercentage = response[CSCurrentSignalStrengthPercentageKey] as! Int self.refreshComplications() }, errorHandler: { (error) -> Void in print(error) self.refreshComplications() } ) } else { self.currentRadioAccessTechnology = nil self.currentSignalStrengthPercentage = 0 self.refreshComplications() } } } extension CSSessionUtility: WCSessionDelegate { func sessionReachabilityDidChange(session: WCSession) { print("sessionReachabilityDidChange \(session.reachable)") if session.reachable { self.reloadComplicationData() } } func session(session: WCSession, didReceiveMessage message: [String : AnyObject]) { self.reloadComplicationData() } }
mit
e1bc821e4afcb6372308c47fcace0975
38.821429
181
0.665371
6.025225
false
false
false
false
sharath-cliqz/browser-ios
Client/Frontend/Browser/NoImageModeHelper.swift
2
1761
/* 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 http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit import Shared struct NoImageModePrefsKey { static let NoImageModeButtonIsInMenu = PrefsKeys.KeyNoImageModeButtonIsInMenu static let NoImageModeStatus = PrefsKeys.KeyNoImageModeStatus } class NoImageModeHelper: TabHelper { fileprivate weak var tab: Tab? required init(tab: Tab) { self.tab = tab #if !CLIQZ // Cliqz: disable adding hide image user script as it is not used if let path = Bundle.main.path(forResource: "NoImageModeHelper", ofType: "js"), let source = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String { let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: true) tab.webView!.configuration.userContentController.addUserScript(userScript) } #endif } static func name() -> String { return "NoImageMode" } func scriptMessageHandlerName() -> String? { return "NoImageMode" } func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { // Do nothing. } static func isNoImageModeAvailable(_ state: AppState) -> Bool { return state.prefs.boolForKey(NoImageModePrefsKey.NoImageModeButtonIsInMenu) ?? AppConstants.MOZ_NO_IMAGE_MODE } static func isNoImageModeActivated(_ state: AppState) -> Bool { return state.prefs.boolForKey(NoImageModePrefsKey.NoImageModeStatus) ?? false } }
mpl-2.0
ddf4056536ab403d4bff7fce737f22dd
35.6875
189
0.720613
4.824658
false
false
false
false
justinyaoqi/SwiftForms
SwiftFormsApplication/ExampleFormViewController.swift
6
8342
// // ExampleFormViewController.swift // SwiftForms // // Created by Miguel Angel Ortuno on 20/08/14. // Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. // import UIKit import SwiftForms class ExampleFormViewController: FormViewController { struct Static { static let nameTag = "name" static let passwordTag = "password" static let lastNameTag = "lastName" static let jobTag = "job" static let emailTag = "email" static let URLTag = "url" static let phoneTag = "phone" static let enabled = "enabled" static let check = "check" static let segmented = "segmented" static let picker = "picker" static let birthday = "birthday" static let categories = "categories" static let button = "button" static let stepper = "stepper" static let slider = "slider" static let textView = "textview" } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.loadForm() } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Submit", style: .Plain, target: self, action: "submit:") } /// MARK: Actions func submit(_: UIBarButtonItem!) { let message = self.form.formValues().description let alert: UIAlertView = UIAlertView(title: "Form output", message: message, delegate: nil, cancelButtonTitle: "OK") alert.show() } /// MARK: Private interface private func loadForm() { let form = FormDescriptor() form.title = "Example Form" let section1 = FormSectionDescriptor() var row: FormRowDescriptor! = FormRowDescriptor(tag: Static.emailTag, rowType: .Email, title: "Email") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.placeholder" : "[email protected]", "textField.textAlignment" : NSTextAlignment.Right.rawValue] section1.addRow(row) row = FormRowDescriptor(tag: Static.passwordTag, rowType: .Password, title: "Password") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.placeholder" : "Enter password", "textField.textAlignment" : NSTextAlignment.Right.rawValue] section1.addRow(row) let section2 = FormSectionDescriptor() row = FormRowDescriptor(tag: Static.nameTag, rowType: .Name, title: "First Name") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.placeholder" : "e.g. Miguel Ángel", "textField.textAlignment" : NSTextAlignment.Right.rawValue] section2.addRow(row) row = FormRowDescriptor(tag: Static.lastNameTag, rowType: .Name, title: "Last Name") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.placeholder" : "e.g. Ortuño", "textField.textAlignment" : NSTextAlignment.Right.rawValue] section2.addRow(row) row = FormRowDescriptor(tag: Static.jobTag, rowType: .Text, title: "Job") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.placeholder" : "e.g. Entrepreneur", "textField.textAlignment" : NSTextAlignment.Right.rawValue] section2.addRow(row) let section3 = FormSectionDescriptor() row = FormRowDescriptor(tag: Static.URLTag, rowType: .URL, title: "URL") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.placeholder" : "e.g. gethooksapp.com", "textField.textAlignment" : NSTextAlignment.Right.rawValue] section3.addRow(row) row = FormRowDescriptor(tag: Static.phoneTag, rowType: .Phone, title: "Phone") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.placeholder" : "e.g. 0034666777999", "textField.textAlignment" : NSTextAlignment.Right.rawValue] section3.addRow(row) let section4 = FormSectionDescriptor() row = FormRowDescriptor(tag: Static.enabled, rowType: .BooleanSwitch, title: "Enable") section4.addRow(row) row = FormRowDescriptor(tag: Static.check, rowType: .BooleanCheck, title: "Doable") section4.addRow(row) row = FormRowDescriptor(tag: Static.segmented, rowType: .SegmentedControl, title: "Priority") row.configuration[FormRowDescriptor.Configuration.Options] = [0, 1, 2, 3] row.configuration[FormRowDescriptor.Configuration.TitleFormatterClosure] = { value in switch( value ) { case 0: return "None" case 1: return "!" case 2: return "!!" case 3: return "!!!" default: return nil } } as TitleFormatterClosure row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["titleLabel.font" : UIFont.boldSystemFontOfSize(30.0), "segmentedControl.tintColor" : UIColor.redColor()] section4.addRow(row) section4.headerTitle = "An example header title" section4.footerTitle = "An example footer title" let section5 = FormSectionDescriptor() row = FormRowDescriptor(tag: Static.picker, rowType: .Picker, title: "Gender") row.configuration[FormRowDescriptor.Configuration.Options] = ["F", "M", "U"] row.configuration[FormRowDescriptor.Configuration.TitleFormatterClosure] = { value in switch( value ) { case "F": return "Female" case "M": return "Male" case "U": return "I'd rather not to say" default: return nil } } as TitleFormatterClosure row.value = "M" section5.addRow(row) row = FormRowDescriptor(tag: Static.birthday, rowType: .Date, title: "Birthday") section5.addRow(row) row = FormRowDescriptor(tag: Static.categories, rowType: .MultipleSelector, title: "Categories") row.configuration[FormRowDescriptor.Configuration.Options] = [0, 1, 2, 3, 4] row.configuration[FormRowDescriptor.Configuration.AllowsMultipleSelection] = true row.configuration[FormRowDescriptor.Configuration.TitleFormatterClosure] = { value in switch( value ) { case 0: return "Restaurant" case 1: return "Pub" case 2: return "Shop" case 3: return "Hotel" case 4: return "Camping" default: return nil } } as TitleFormatterClosure section5.addRow(row) let section6 = FormSectionDescriptor() section6.headerTitle = "Stepper & Slider" row = FormRowDescriptor(tag: Static.stepper, rowType: .Stepper, title: "Step count") row.configuration[FormRowDescriptor.Configuration.MaximumValue] = 200.0 row.configuration[FormRowDescriptor.Configuration.MinimumValue] = 20.0 row.configuration[FormRowDescriptor.Configuration.Steps] = 2.0 section6.addRow(row) row = FormRowDescriptor(tag: Static.slider, rowType: .Slider, title: "Slider") row.value = 0.5 section6.addRow(row) let section7 = FormSectionDescriptor() row = FormRowDescriptor(tag: Static.textView, rowType: .MultilineText, title: "Notes") section7.headerTitle = "Multiline TextView" section7.addRow(row) let section8 = FormSectionDescriptor() row = FormRowDescriptor(tag: Static.button, rowType: .Button, title: "Dismiss") row.configuration[FormRowDescriptor.Configuration.DidSelectClosure] = { self.view.endEditing(true) } as DidSelectClosure section8.addRow(row) form.sections = [section1, section2, section3, section4, section5, section6, section7, section8] self.form = form } }
mit
59401c088dd2070391080166bf8aa5f1
39.877451
189
0.622617
4.870911
false
true
false
false
apple/swift-lldb
packages/Python/lldbsuite/test/lang/swift/materializer_archetype_binding/main.swift
2
2638
protocol Generic { associatedtype Associated: Decodable var test: String { get } } struct DecStruct: Decodable { let test: String } struct GenericImpl: Generic { typealias Associated = DecStruct let test: String = "test test" } protocol Problematic { func problemMethod<G: Generic>(param: G, anotherParam: String) } extension Problematic { func problemMethod<G>(param: G, anotherParam: String) where G : Generic { print("patatino") //%self.expect('frame var -d run-target -- param', //% substrs=['(a.GenericImpl) param = (test = "test test")']) //%self.expect('expr -d run-target -- param', //% substrs=['(a.GenericImpl)', '= (test = "test test")']) //%self.expect('frame var -d run-target -- anotherParam', //% substrs=['(String) anotherParam = "just a string"']) //%self.expect('expr -d run-target -- anotherParam', //% substrs=['(String)', '= "just a string"']) getAStringAsync { string in print("breakpoint") } } } class ProblematicImpl: Problematic {} protocol NotProblematic { func problemMethod<G: Generic>(param: G, anotherParam: String) } extension NotProblematic { func problemMethod<G>(param: G, anotherParam: String) where G : Generic {} } class NotProblematicImpl: NotProblematic { func problemMethod<G>(param: G, anotherParam: String) where G : Generic { print("patatino") //%self.expect('frame var -d run-target -- param', //% substrs=['(a.GenericImpl) param = (test = "test test")']) //%self.expect('expr -d run-target -- param', //% substrs=['(a.GenericImpl)', '= (test = "test test")']) //%self.expect('frame var -d run-target -- anotherParam', //% substrs=['(String) anotherParam = "just a string"']) //%self.expect('expr -d run-target -- anotherParam', //% substrs=['(String)', '= "just a string"']) getAStringAsync { string in print("breakpoint") } } } func getAStringAsync(completion: @escaping (String) -> ()) { completion("asd") } let useCase = ProblematicImpl() let data = GenericImpl() useCase.problemMethod(param: data, anotherParam: "just a string") let useCase2 = NotProblematicImpl() let data2 = GenericImpl() useCase2.problemMethod(param: data2, anotherParam: "just a string")
apache-2.0
1a591d05ed13c6d685dd2e66d558ee93
36.169014
89
0.558757
4.331691
false
true
false
false
getcircle/protobuf-swift
src/ProtocolBuffers/ProtocolBuffersTests/SizeTest.swift
7
670
// // SizeTest.swift // ProtocolBuffers // // Created by Alexey Khokhlov on 10.11.14. // Copyright (c) 2014 alexeyxo. All rights reserved. // import Foundation import XCTest class SizeTest: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testTypeSizes() { XCTAssertTrue(4 == sizeof(Int32)) XCTAssertTrue(8 == sizeof(Int64)) XCTAssertTrue(8 == sizeof(UInt64)) XCTAssertTrue(4 == sizeof(UInt32)) XCTAssertTrue(4 == sizeof(Float)) XCTAssertTrue(8 == sizeof(Double)) XCTAssertTrue(1 == sizeof(Bool)) } }
apache-2.0
705df054555a42fdb981e8d6912169c3
19.9375
53
0.601493
3.964497
false
true
false
false
maximkhatskevich/MKHStoryboardHelpers
Example/iOS/MKHStoryboardHelpers/UI.swift
1
4562
// // UI.swift // MKHStoryboardHelpers // // Created by Maxim Khatskevich on 2/4/16. // Copyright © 2016 Maxim Khatskevich. All rights reserved. // import UIKit //=== enum Storyboard // might be class or struct as well { // Consider to name this type just "UI" (to make it shorter and nicer to use) // and use as UI objects factory, as UI router, etc. //=== // storyboards: enum Main: String, SBHStoryboard { // non-subclassed ViewControllers: case NextVC } enum Second: String, SBHStoryboard { // non-subclassed ViewControllers: case SomeVC } enum Third: SBHStoryboard // might be class or struct as well { // this storyboard contains only initial VC, // so no need to define explicit IDs, // // NOTE: this enum is should not declare a raw type, // until it has at least one case (explicit ID). //=== // Here declare segues that are available // inside this ("Third") storyboard, // but defined inside non-subclassed VC. // // NOTE: the name of the type doesn't matter in this case. enum SegueID: String, SBHStoryboardSegue { case AnotherSegue } // NOTE: you can group segue declarations // into several separate types, it works too, // just make sure every type conforms to 'SBHStoryboardSegue' } } //=== class BaseVC: UIViewController, SBHStoryboardVC { // MARK: Segue definition enum SegueID: String, SBHStoryboardSegue { case TheOneSegue } // MARK: IBActions @IBAction func showModalHandler(_ sender: AnyObject) { // for modal view controller we have custom UIViewController subclass // 'ModalVC', which also conforms to protocol 'SBHStoryboardIDInferable', // so we are allowed to infer desired storyboardID based on class name // and can use generic-based 'instantiateVC' let modalVC: ModalVC = Storyboard.Main.instantiateVC() //=== present(modalVC, animated: true, completion: nil) } @IBAction func showNextHandler(_ sender: AnyObject) { // for next view controller we do NOT have custom UIViewController subclass, // so we have to define desired storyboardID explicitly let nextVC = Storyboard.Main.NextVC.instantiate() //=== navigationController?.pushViewController(nextVC, animated: true) } @IBAction func showSomeHandler(_ sender: AnyObject) { // for some view controller we do NOT have custom UIViewController subclass as well, // so we have to define desired storyboardID explicitly let someVC = Storyboard.Second.SomeVC.instantiate() //=== navigationController?.pushViewController(someVC, animated: true) } @IBAction func showThirdSBInitialHandler(_ sender: AnyObject) { // in Third storyboard we do not have explicit storyboardIDs or // custom UIViewController subclasses assigned to view controllers, // we only have initial view controller there let thirdInitialVC = Storyboard.Third.instantiateInitialVC() //=== navigationController?.pushViewController(thirdInitialVC, animated: true) //=== // lets push another VC right away, // be sure to pass correct VC: Storyboard.Third.SegueID.AnotherSegue.perform(from: thirdInitialVC, sender: nil) } @IBAction func callSegueHandler(_ sender: AnyObject) { performSegue(.TheOneSegue, sender: sender) //=== // // alternative way to do the same, // // when you call it outside of custom VC: // // let aVC = self // SegueID.TheOneSegue.perform(aVC, sender: sender) } // MARK: Overrided methods override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch SegueID(from: segue) { case .TheOneSegue: print("Segue with ID 'TheOneSegue' will be performed!") } } } //=== class ModalVC: UIViewController, SBHStoryboardIDInferable { @IBAction func dismissHandler(_ sender: AnyObject) { dismiss(animated: true, completion: nil) } }
mit
811b9fe94814d6a3bc21c44a485f6d64
26.311377
92
0.594387
4.984699
false
false
false
false
centrifugal/centrifuge-ios
CentrifugeiOS/Classes/CentrifugeClientImpl.swift
2
9707
// // Clients.swift // Pods // // Created by German Saprykin on 20/04/16. // // import Starscream typealias CentrifugeBlockingHandler = ([CentrifugeServerMessage]?, Error?) -> Void class CentrifugeClientImpl: NSObject, CentrifugeClient, WebSocketDelegate { var ws: WebSocket! var url: String! var creds: CentrifugeCredentials! var builder: CentrifugeClientMessageBuilder! var parser: CentrifugeServerMessageParser! weak var delegate: CentrifugeClientDelegate? var messageCallbacks = [String : CentrifugeMessageHandler]() var subscription = [String : CentrifugeChannelDelegate]() /** Handler is used to process websocket delegate method. If it is not nil, it blocks default actions. */ var blockingHandler: CentrifugeBlockingHandler? var connectionCompletion: CentrifugeMessageHandler? //MARK: - Public interface //MARK: Server related method func connect(withCompletion completion: @escaping CentrifugeMessageHandler) { blockingHandler = connectionProcessHandler connectionCompletion = completion ws = WebSocket(url: URL(string: url)!) ws.delegate = self ws.connect() } func disconnect() { ws.disconnect() } func ping(withCompletion completion: @escaping CentrifugeMessageHandler) { let message = builder.buildPingMessage() messageCallbacks[message.uid] = completion send(message: message) } //MARK: Channel related method func subscribe(toChannel channel: String, delegate: CentrifugeChannelDelegate, completion: @escaping CentrifugeMessageHandler) { let message = builder.buildSubscribeMessageTo(channel: channel) subscription[channel] = delegate messageCallbacks[message.uid] = completion send(message: message) } func subscribe(privateChannel channel: String, client: String, sign: String, delegate: CentrifugeChannelDelegate, completion: @escaping CentrifugeMessageHandler) { let channel = channel.hasPrefix(CentrifugePrivateChannelPrefix) ? channel : CentrifugePrivateChannelPrefix + channel let message = builder.buildSubscribeMessageToPrivate(channel: channel, client: client, sign: sign) subscription[channel] = delegate messageCallbacks[message.uid] = completion send(message: message) } func subscribe(toChannel channel: String, delegate: CentrifugeChannelDelegate, lastMessageUID uid: String, completion: @escaping CentrifugeMessageHandler) { let message = builder.buildSubscribeMessageTo(channel: channel, lastMessageUUID: uid) subscription[channel] = delegate messageCallbacks[message.uid] = completion send(message: message) } func publish(toChannel channel: String, data: [String : Any], completion: @escaping CentrifugeMessageHandler) { let message = builder.buildPublishMessageTo(channel: channel, data: data) messageCallbacks[message.uid] = completion send(message: message) } func unsubscribe(fromChannel channel: String, completion: @escaping CentrifugeMessageHandler) { let message = builder.buildUnsubscribeMessageFrom(channel: channel) messageCallbacks[message.uid] = completion send(message: message) } func presence(inChannel channel: String, completion: @escaping CentrifugeMessageHandler) { let message = builder.buildPresenceMessage(channel: channel) messageCallbacks[message.uid] = completion send(message: message) } func history(ofChannel channel: String, completion: @escaping CentrifugeMessageHandler) { let message = builder.buildHistoryMessage(channel: channel) messageCallbacks[message.uid] = completion send(message: message) } //MARK: - Helpers func unsubscribeFrom(channel: String) { subscription[channel] = nil } func send(message: CentrifugeClientMessage) { let dict: [String:Any] = ["uid" : message.uid, "method" : message.method.rawValue, "params" : message.params] let data = try! JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions()) ws.write(data: data) } func setupConnectedState() { blockingHandler = defaultProcessHandler } func resetState() { blockingHandler = nil connectionCompletion = nil messageCallbacks.removeAll() subscription.removeAll() } //MARK: - Handlers /** Handler is using while connecting to server. */ func connectionProcessHandler(messages: [CentrifugeServerMessage]?, error: Error?) -> Void { guard let handler = connectionCompletion else { assertionFailure("Error: No connectionCompletion") return } resetState() if let err = error { handler(nil, err) return } guard let message = messages?.first else { assertionFailure("Error: Empty messages array") return } if message.error == nil{ setupConnectedState() handler(message, nil) } else { let error = NSError.errorWithMessage(message: message) handler(nil, error) } } /** Handler is using while normal working with server. */ func defaultProcessHandler(messages: [CentrifugeServerMessage]?, error: Error?) { if let error = error { resetState() delegate?.client(self, didDisconnectWithError: error) return } guard let msgs = messages else { assertionFailure("Error: Empty messages array without error") return } for message in msgs { defaultProcessHandler(message: message) } } func defaultProcessHandler(message: CentrifugeServerMessage) { var handled = false if let uid = message.uid, messageCallbacks[uid] == nil { assertionFailure("Error: Untracked message is received") return } if let uid = message.uid, let handler = messageCallbacks[uid], message.error != nil { let error = NSError.errorWithMessage(message: message) handler(nil, error) messageCallbacks[uid] = nil return } if let uid = message.uid, let handler = messageCallbacks[uid] { handler(message, nil) messageCallbacks[uid] = nil handled = true } if (handled && (message.method != .unsubscribe && message.method != .disconnect)) { return } switch message.method { // Channel events case .message: guard let channel = message.body?["channel"] as? String, let delegate = subscription[channel] else { assertionFailure("Error: Invalid \(message.method) handler") return } delegate.client(self, didReceiveMessageInChannel: channel, message: message) case .join: guard let channel = message.body?["channel"] as? String, let delegate = subscription[channel] else { assertionFailure("Error: Invalid \(message.method) handler") return } delegate.client(self, didReceiveJoinInChannel: channel, message: message) case .leave: guard let channel = message.body?["channel"] as? String, let delegate = subscription[channel] else { assertionFailure("Error: Invalid \(message.method) handler") return } delegate.client(self, didReceiveLeaveInChannel: channel, message: message) case .unsubscribe: guard let channel = message.body?["channel"] as? String, let delegate = subscription[channel] else { assertionFailure("Error: Invalid \(message.method) handler") return } delegate.client(self, didReceiveUnsubscribeInChannel: channel, message: message) unsubscribeFrom(channel: channel) // Client events case .disconnect: resetState() ws.disconnect() delegate?.client(self, didDisconnectWithError: NSError.errorWithMessage(message: message)) case .refresh: delegate?.client(self, didReceiveRefreshMessage: message) default: assertionFailure("Error: Invalid method type") } } //MARK: - WebSocketDelegate func websocketDidConnect(socket: WebSocketClient) { let message = builder.buildConnectMessage(credentials: creds) send(message: message) } func websocketDidDisconnect(socket: WebSocketClient, error: Error?) { guard let handler = blockingHandler else { return } handler(nil, error) } func websocketDidReceiveMessage(socket: WebSocketClient, text: String) { let data = text.data(using: String.Encoding.utf8)! let messages = try! parser.parse(data: data) if let handler = blockingHandler { handler(messages, nil) } } func websocketDidReceiveData(socket: WebSocketClient, data: Data) { let messages = try! parser.parse(data: data) if let handler = blockingHandler { handler(messages, nil) } } }
mit
af50359a9a83ee55da49916d2809ffd5
35.355805
167
0.626867
5.247027
false
false
false
false
jonnguy/HSTracker
HSTracker/Logging/CoreManager.swift
1
16414
/* * This file is part of the HSTracker package. * (c) Benjamin Michotte <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Created on 13/02/16. */ import Foundation //import HearthAssets import HearthMirror import kotlin_hslog enum HearthstoneLogError: Error { case canNotCreateDir, canNotReadFile, canNotCreateFile } struct HearthstoneRunState { var isRunning = false var isActive = false init(isRunning: Bool, isActive: Bool) { self.isRunning = isRunning self.isActive = isActive } } class MacOSConsole: Kotlin_consoleConsole { func debug(message: String) { logger.debug(message) } func error(message: String) { logger.error(message) } func error(throwable: KotlinThrowable) { throwable.printStackTrace() } } final class CoreManager: NSObject { static let applicationName = "Hearthstone" var logReaderManager: LogReaderManager! //static var assetGenerator: HearthAssets? // watchers let packWatcher = PackWatcher() let game: Game var cardJson: CardJson! var hsLog: HSLog! var queue = DispatchQueue(label: "net.hearthsim.hstracker.readers", attributes: []) override init() { self.game = Game(hearthstoneRunState: HearthstoneRunState(isRunning: CoreManager.isHearthstoneRunning(), isActive: CoreManager.isHearthstoneActive())) super.init() logReaderManager = LogReaderManager(logPath: Settings.hearthstonePath, coreManager: self) let lang: Language.Hearthstone if Settings.hearthstoneLanguage == nil { lang = Language.Hearthstone.enUS } else { lang = Settings.hearthstoneLanguage! } let maybeUrl = Bundle(for: type(of: self)) .url(forResource: "Resources/Cards/cardsDB.\(lang)", withExtension: "json") if let url = maybeUrl, let fileHandle = try? FileHandle(forReadingFrom: url) { let input = PosixInputKt.Input(fileDescriptor: fileHandle.fileDescriptor) logger.debug("building CardJson...") self.cardJson = CardJson.Companion().fromLocalizedJson(input: input) logger.debug("building HSLog...") hsLog = HSLog(console: MacOSConsole(), cardJson: cardJson, debounceDelay: 100) hsLog.setListener(listener: HSTLogListener(windowManager: game.windowManager)) } } func processPower(rawLine: String) { DispatchQueue.main.async { self.hsLog.processPower(rawLine: rawLine, isOldData: false) } } deinit { NotificationCenter.default.removeObserver(self) } static func validatedHearthstonePath(_ path: String = "\(Settings.hearthstonePath)/Hearthstone.app") -> Bool { let exists = FileManager.default.fileExists(atPath: path) AppHealth.instance.setHSInstalled(flag: exists) return exists } // MARK: - Initialisation func start() { startListeners() if CoreManager.isHearthstoneRunning() { logger.info("Hearthstone is running, starting trackers now.") startTracking() } } /** Configures Hearthstone app logging so we can read them */ func setup() throws -> Bool { let fileManager = FileManager.default let requireVerbose = [LogLineNamespace.power] // make sure the path exists let dir = NSString(string: configPath).deletingLastPathComponent logger.verbose("Check if \(dir) exists") var isDir: ObjCBool = false if !fileManager.fileExists(atPath: dir, isDirectory: &isDir) || !isDir.boolValue { do { logger.verbose("Creating \(dir)") try fileManager.createDirectory(atPath: dir, withIntermediateDirectories: true, attributes: nil) } catch let error as NSError { AppHealth.instance.setLoggerWorks(flag: false) logger.error("\(error.description)") throw HearthstoneLogError.canNotCreateDir } } let zones = LogLineNamespace.usedValues() var missingZones: [LogLineZone] = [] logger.verbose("Check if \(configPath) exists") if !fileManager.fileExists(atPath: configPath) { for zone in zones { missingZones.append(LogLineZone(namespace: zone)) } } else { var fileContent: String? do { fileContent = try String(contentsOfFile: configPath) } catch { logger.error("\(error)") } if let fileContent = fileContent { var zonesFound: [LogLineZone] = [] let splittedZones = fileContent.components(separatedBy: "[") .map { $0.replacingOccurrences(of: "]", with: "") .components(separatedBy: "\n") .filter { !$0.isEmpty } } .filter { !$0.isEmpty } for splittedZone in splittedZones { var zoneData = splittedZone.filter { !$0.isBlank } if zoneData.count < 1 { continue } let zone = zoneData.removeFirst() if let currentZone = LogLineNamespace(rawValue: zone) { let logLineZone = LogLineZone(namespace: currentZone) logLineZone.requireVerbose = requireVerbose.contains(currentZone) for line in zoneData { let kv = line.components(separatedBy: "=") if let key = kv.first, let value = kv.last { switch key { case "LogLevel": logLineZone.logLevel = Int(value) ?? 1 case "FilePrinting": logLineZone.filePrinting = value case "ConsolePrinting": logLineZone.consolePrinting = value case "ScreenPrinting": logLineZone.screenPrinting = value case "Verbose": logLineZone.verbose = value == "true" default: break } } } zonesFound.append(logLineZone) } } logger.verbose("Zones found : \(zonesFound)") for zone in zones { var currentZoneFound: LogLineZone? for zoneFound in zonesFound where zoneFound.namespace == zone { currentZoneFound = zoneFound break } if let currentZone = currentZoneFound { logger.verbose("Is \(currentZone.namespace) valid ? " + "\(currentZone.isValid())") if !currentZone.isValid() { missingZones.append(currentZone) } } else { logger.verbose("Zone \(zone) is missing") missingZones.append(LogLineZone(namespace: zone)) } } } } logger.verbose("Missing zones : \(missingZones)") if !missingZones.isEmpty { var fileContent: String = "" for zone in zones { let logZone = LogLineZone(namespace: zone) logZone.requireVerbose = requireVerbose.contains(zone) fileContent += logZone.toString() } do { try fileContent.write(toFile: configPath, atomically: true, encoding: .utf8) } catch { logger.error("\(error)") throw HearthstoneLogError.canNotCreateFile } if CoreManager.isHearthstoneRunning() { AppHealth.instance.setLoggerWorks(flag: false) return false } } AppHealth.instance.setLoggerWorks(flag: true) return true } func startTracking() { // Starting logreaders after short delay is as game might be still in loading state let time = DispatchTime.now() + .seconds(1) DispatchQueue.main.asyncAfter(deadline: time) { [unowned(unsafe) self] in logger.info("Start Tracking") self.logReaderManager.start() } } func stopTracking() { logger.info("Stop Tracking") logReaderManager.stop(eraseLogFile: !CoreManager.isHearthstoneRunning()) DeckWatcher.stop() ArenaDeckWatcher.stop() CollectionWatcher.stop() MirrorHelper.destroy() } var triggers: [NSObjectProtocol] = [] // MARK: - Events func startListeners() { if self.triggers.count == 0 { let center = NSWorkspace.shared.notificationCenter let notifications = [ NSWorkspace.activeSpaceDidChangeNotification: spaceChange, NSWorkspace.didLaunchApplicationNotification: appLaunched, NSWorkspace.didTerminateApplicationNotification: appTerminated, NSWorkspace.didActivateApplicationNotification: appActivated, NSWorkspace.didDeactivateApplicationNotification: appDeactivated ] for (event, trigger) in notifications { let observer = center.addObserver(forName: event, object: nil, queue: OperationQueue.main) { note in trigger(note) } triggers.append(observer) } } } func spaceChange(_ notification: Notification) { logger.verbose("Receive space changed event") NotificationCenter.default .post(name: Notification.Name(rawValue: Events.space_changed), object: nil) } func appLaunched(_ notification: Notification) { if let app = notification.userInfo!["NSWorkspaceApplicationKey"] as? NSRunningApplication, app.localizedName == CoreManager.applicationName { logger.verbose("Hearthstone is now launched") self.startTracking() self.game.setHearthstoneRunning(flag: true) NotificationCenter.default.post(name: Notification.Name(rawValue: Events.hearthstone_running), object: nil) } } func appTerminated(_ notification: Notification) { if let app = notification.userInfo!["NSWorkspaceApplicationKey"] as? NSRunningApplication, app.localizedName == CoreManager.applicationName { logger.verbose("Hearthstone is now closed") self.stopTracking() self.game.setHearthstoneRunning(flag: false) AppHealth.instance.setHearthstoneRunning(flag: false) if Settings.quitWhenHearthstoneCloses { NSApplication.shared.terminate(self) } else { logger.info("Not closing app since setting says so.") } } } func appActivated(_ notification: Notification) { if let app = notification.userInfo!["NSWorkspaceApplicationKey"] as? NSRunningApplication { if app.localizedName == CoreManager.applicationName { NotificationCenter.default.post(name: Notification.Name(rawValue: Events.hearthstone_active), object: nil) // TODO: add observer here as well self.game.setHearthstoneActived(flag: true) self.game.setSelfActivated(flag: false) } if app.bundleIdentifier == Bundle.main.bundleIdentifier { self.game.setSelfActivated(flag: true) } } } func appDeactivated(_ notification: Notification) { if let app = notification.userInfo!["NSWorkspaceApplicationKey"] as? NSRunningApplication { if app.localizedName == CoreManager.applicationName { self.game.setHearthstoneActived(flag: false) } if app.bundleIdentifier == Bundle.main.bundleIdentifier { self.game.setSelfActivated(flag: false) } } } static func bringHSToFront() { if let hsapp = CoreManager.hearthstoneApp { hsapp.activate(options: NSApplication.ActivationOptions.activateIgnoringOtherApps) } } // MARK: - Paths / Utils var configPath: String { return NSString(string: "~/Library/Preferences/Blizzard/Hearthstone/log.config") .expandingTildeInPath } private static func isHearthstoneRunning() -> Bool { return CoreManager.hearthstoneApp != nil } static var hearthstoneApp: NSRunningApplication? { let apps = NSWorkspace.shared.runningApplications return apps.first { $0.bundleIdentifier == "unity.Blizzard Entertainment.Hearthstone" } } static func isHearthstoneActive() -> Bool { return CoreManager.hearthstoneApp?.isActive ?? false } // MARK: - Deck detection static func autoDetectDeck(mode: Mode, playerClass: CardClass? = nil) -> Deck? { let selectedModes: [Mode] = [.tavern_brawl, .tournament, .friendly, .adventure, .gameplay] if selectedModes.contains(mode) { // Try dungeon run deck if mode == .adventure && Settings.autoImportDungeonRun { if let opponentId = MirrorHelper.getMatchInfo()?.opposingPlayer.playerId.intValue { if DungeonRunDeckWatcher.initialOpponents.contains(opponentId), let playerClass = playerClass { // get player class MirrorHelper.get let cards = DefaultDecks.DungeonRun.deck(for: playerClass) logger.info("Found starter dungeon run deck") return RealmHelper.checkAndUpdateDungeonRunDeck(cards: cards, reset: true) } } let cards = DungeonRunDeckWatcher.dungeonRunDeck if cards.count > 0 { logger.info("Found dungeon run deck via watcher") return RealmHelper.checkAndUpdateDungeonRunDeck(cards: cards) } } logger.info("Trying to import deck from Hearthstone") var selectedDeckId: Int64 = 0 if let selectedId = MirrorHelper.getSelectedDeck() { selectedDeckId = selectedId logger.info("Found selected deck id via mirror: \(selectedDeckId)") } else { selectedDeckId = DeckWatcher.selectedDeckId logger.info("Found selected deck id via watcher: \(selectedDeckId)") } if selectedDeckId <= 0 { if mode != .tavern_brawl { return nil } } if let decks = MirrorHelper.getDecks() { guard let selectedDeck = decks.first(where: { $0.id as? Int64 ?? 0 == selectedDeckId }) else { logger.warning("No deck with id=\(selectedDeckId) found") return nil } logger.info("Found selected deck : \(selectedDeck.name)") if let deck = RealmHelper.checkAndUpdateDeck(deckId: selectedDeckId, selectedDeck: selectedDeck) { return deck } // deck does not exist, add it return RealmHelper.add(mirrorDeck: selectedDeck) } else { logger.warning("Mirror returned no decks") return nil } } else if mode == .draft { logger.info("Trying to import arena deck from Hearthstone") var hsMirrorDeck: MirrorDeck? if let mDeck = MirrorHelper.getArenaDeck()?.deck { hsMirrorDeck = mDeck } else { hsMirrorDeck = ArenaDeckWatcher.selectedDeck } guard let hsDeck = hsMirrorDeck else { logger.warning("Can't get arena deck") return nil } return RealmHelper.checkOrCreateArenaDeck(mirrorDeck: hsDeck) } logger.error("Auto-importing deck of \(mode) is not supported") return nil } }
mit
570f46e726bd2f7c74e03151af678ec8
36.051919
122
0.580846
5.072311
false
false
false
false
Olinguito/YoIntervengoiOS
Yo Intervengo/Helpers/TabBar/JOTabBar.swift
1
5200
// // JOTabBar.swift // Yo Intervengo // // Created by Jorge Raul Ovalle Zuleta on 1/30/15. // Copyright (c) 2015 Olinguito. All rights reserved. // import UIKit @objc protocol JOTabBarDelegate{ optional func tappedButton() } class JOTabBar: UIView { var delegate:JOTabBarDelegate! var buttons:NSMutableArray! var data:NSMutableArray! var container:UIView! var actual:Int! var colorView:UIColor! required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(frame: CGRect, data:NSMutableArray, color: UIColor) { super.init(frame: frame) self.data = data buttons = NSMutableArray() colorView = color var counter = 0 var w = (frame.size.width/CGFloat(data.count)) let font = UIFont(name: "Roboto-Regular", size: 10) for button in data { var xAxis = CGFloat(counter)*w var but: UIButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton but.frame = CGRect(x: xAxis, y: 0, width: w, height: 55) but.backgroundColor = UIColor.whiteColor() but.layer.borderWidth = 1 but.tag = counter+1 but.titleLabel?.font = font var imageBtn = UIImage(named: (data.objectAtIndex(counter)[0] as! String)) but.setImage(imageBtn, forState: UIControlState.Normal) but.setTitle( (data.objectAtIndex(counter)[0] as! String), forState: UIControlState.Normal) var spacing:CGFloat = 6 var imageSize = but.imageView?.image?.size var title:NSString = "\(but.titleLabel?.text)" var titleSize = title.sizeWithAttributes([NSFontAttributeName: but.titleLabel?.font ?? UIFont.systemFontOfSize(100)]) var size:CGSize = imageBtn?.size ?? CGSizeZero but.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Center but.titleEdgeInsets = UIEdgeInsetsMake(0.0, (-size.width) , -(size.height + spacing), 0.0) but.imageEdgeInsets = UIEdgeInsetsMake(-(titleSize.height + spacing), (titleSize.width-(size.width*1.7))/2 , 0.0, 0) but.layer.borderColor = UIColor.greyButtons().CGColor but.addTarget(self, action: Selector("buttonTapped:"), forControlEvents: UIControlEvents.TouchUpInside) self.addSubview(but) counter++ buttons.addObject(but) } setTab(1) } func buttonTapped(sender:UIButton!){ setTab(sender.tag) } func getActHelper() ->UIButton{ var returnBtn = UIButton() switch(actual){ case 1: returnBtn.tag = 0 case 2: returnBtn.tag = 0 case 3: returnBtn.setImage(UIImage(named: "linkHelper"), forState: UIControlState.Normal) returnBtn.tag = 1 case 4: returnBtn.setImage(UIImage(named: "linkHelper"), forState: UIControlState.Normal) returnBtn.tag = 2 default: returnBtn.tag = 0 } return returnBtn } func setTab(index:Int){ var counter = 1 actual = index for button in buttons{ (button as! UIButton).backgroundColor = UIColor.whiteColor() /*if counter+1==index{ var mask = CAShapeLayer() mask.path = (UIBezierPath(roundedRect: button.bounds, byRoundingCorners: UIRectCorner.BottomRight, cornerRadii: CGSize(width: 5.0, height: 10.0))).CGPath button.layer.mask = mask } if counter-1==index{ var mask = CAShapeLayer() mask.path = (UIBezierPath(roundedRect: button.bounds, byRoundingCorners: UIRectCorner.BottomLeft, cornerRadii: CGSize(width: 5.0, height: 10.0))).CGPath button.layer.mask = mask }*/ (button as! UIButton).layer.borderColor = UIColor.greyButtons().CGColor (button as! UIButton).tintColor = UIColor.greyDark() if counter==index{ if (container?.isDescendantOfView(self) != nil){ container.removeFromSuperview() } (button as! UIButton).layer.borderColor = UIColor.clearColor().CGColor (button as! UIButton).tintColor = colorView container = self.data.objectAtIndex(index-1)[1] as! UIView container.frame = (self.data.objectAtIndex(index-1)[1] as! UIView).frame container.frame.origin = CGPoint(x: 0, y: 55) self.frame = CGRect(x: 0, y: self.frame.origin.y, width: 320, height: container.frame.maxY) self.addSubview(container) var pop = POPSpringAnimation(propertyNamed: kPOPViewFrame) pop.toValue = NSValue(CGRect: CGRect(origin: self.frame.origin, size: CGSize(width: self.frame.size.width, height: container.frame.height+55))) self.pop_addAnimation(pop, forKey: "Increase") self.delegate?.tappedButton!() } counter++ } } }
mit
18bb1bc5dd507ea7b37b8f2aef173e9c
40.935484
170
0.595577
4.577465
false
false
false
false
Intell/question
question/Utility/UIViewExt.swift
2
1820
// // UIView-Frame.swift // JokeClient-Swift // // Created by YANGReal on 14-6-7. // Copyright (c) 2014年 YANGReal. All rights reserved. // import UIKit import Foundation extension UIView { func x()->CGFloat { return self.frame.origin.x } func right()-> CGFloat { return self.frame.origin.x + self.frame.size.width } func y()->CGFloat { return self.frame.origin.y } func bottom()->CGFloat { return self.frame.origin.y + self.frame.size.height } func width()->CGFloat { return self.frame.size.width } func height()-> CGFloat { return self.frame.size.height } func setX(x: CGFloat) { var rect:CGRect = self.frame rect.origin.x = x self.frame = rect } func setRight(right: CGFloat) { var rect:CGRect = self.frame rect.origin.x = right - rect.size.width self.frame = rect } func setY(y: CGFloat) { var rect:CGRect = self.frame rect.origin.y = y self.frame = rect } func setBottom(bottom: CGFloat) { var rect:CGRect = self.frame rect.origin.y = bottom - rect.size.height self.frame = rect } func setWidth(width: CGFloat) { var rect:CGRect = self.frame rect.size.width = width self.frame = rect } func setHeight(height: CGFloat) { var rect:CGRect = self.frame rect.size.height = height self.frame = rect } class func showAlertView(title:String,message:String) { var alert = UIAlertView() alert.title = title alert.message = message alert.addButtonWithTitle("好") alert.show() } }
apache-2.0
d51c0f9bdda890d16f075ff35e7165f2
18.956044
59
0.548458
3.939262
false
false
false
false
Yurssoft/QuickFile
QuickFile/Controllers/YSDriveViewController.swift
1
15261
// // YSDriveViewController.swift // YSGGP // // Created by Yurii Boiko on 9/20/16. // Copyright © 2016 Yurii Boiko. All rights reserved. // import UIKit import SwiftMessages import M13ProgressSuite import DZNEmptyDataSet class YSDriveViewController: UITableViewController { var selectedIndexes = Set<IndexPath>() var viewModel: YSDriveViewModelProtocol? { willSet { viewModel?.viewDelegate = nil } didSet { viewModel?.viewDelegate = self refreshDisplay() } } override func viewDidLoad() { super.viewDidLoad() let bundle = Bundle(for: YSDriveFileTableViewCell.self) let nib = UINib(nibName: YSDriveFileTableViewCell.nameOfClass, bundle: bundle) tableView.register(nib, forCellReuseIdentifier: YSDriveFileTableViewCell.nameOfClass) tableView.emptyDataSetSource = self tableView.emptyDataSetDelegate = self tableView.tableFooterView = UIView.init(frame: CGRect.zero) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) navigationController?.setIndeterminate(viewModel?.isDownloadingMetadata ?? false) } func containingViewControllerViewDidLoad() { refreshDisplay() tableView.allowsMultipleSelectionDuringEditing = true configurePullToRefresh() navigationController?.showProgress() } func configurePullToRefresh() { let footer = MJRefreshAutoNormalFooter.init { [weak self] () -> Void in SwiftMessages.hide(id: YSConstants.kOffineStatusBarMessageID) logDriveSubdomain(.Controller, .Info, "Footer requested") guard let viewModel = self?.viewModel as? YSDriveViewModel, let isEditing = self?.isEditing, !isEditing else { logDriveSubdomain(.Controller, .Info, "Footer cancelled, no model or editing") self?.tableView.mj_footer.endRefreshing() return } viewModel.getNextPartOfFiles { [weak viewModel] in logDriveSubdomain(.Controller, .Info, "Footer finished with data") guard let viewModel = viewModel, viewModel.allPagesDownloaded else { self?.tableView.mj_footer.endRefreshing() return } self?.tableView.mj_footer.endRefreshingWithNoMoreData() } } footer?.isAutomaticallyHidden = true tableView.mj_footer = footer tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: { [weak self] () -> Void in SwiftMessages.hide(id: YSConstants.kOffineStatusBarMessageID) logDriveSubdomain(.Controller, .Info, "Header requested") guard let viewModel = self?.viewModel as? YSDriveViewModel, let isEditing = self?.isEditing, !isEditing else { logDriveSubdomain(.Controller, .Info, "Header cancelled, no model or editing") self?.tableView.mj_header.endRefreshing() return } viewModel.refreshFiles { logDriveSubdomain(.Controller, .Info, "Header finished with data") self?.tableView.mj_header.endRefreshing() //set state to idle to have opportunity to fetch more data after user scrolled to bottom self?.tableView.mj_footer.state = .idle } }) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) guard let viewModel = viewModel, !viewModel.isLoggedIn else { return } let errorMessage = YSError(errorType: YSErrorType.notLoggedInToDrive, messageType: Theme.warning, title: "Warning", message: "Could not get list, please login", buttonTitle: "Login", debugInfo: "") errorDidChange(viewModel: viewModel, error: errorMessage) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) SwiftMessages.hide() } func deleteToolbarButtonTapped(_ sender: UIBarButtonItem) { logDriveSubdomain(.Controller, .Info, "") viewModel?.removeDownloads() } func refreshDisplay() { logDriveSubdomain(.Controller, .Info, "") if viewIfLoaded != nil { tableView.reloadData() } } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let viewModel = viewModel { return viewModel.numberOfFiles } return 0 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return YSConstants.kCellHeight } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: YSDriveFileTableViewCell.nameOfClass, for: indexPath) if let cell = cell as? YSDriveFileTableViewCell { let file = viewModel?.file(at: indexPath.row) let download = viewModel?.download(for: file?.id ?? "") cell.configureForDrive(file, self, download) } if isEditing && selectedIndexes.contains(indexPath) { tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none) } return cell } override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { return isFileAudio(at: indexPath) || !isEditing } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { return (isFileAudio(at: indexPath) || !isEditing) ? indexPath : nil } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { logDriveSubdomain(.Controller, .Info, "Index: \(indexPath.row)") if isEditing { if !isFileAudio(at: indexPath) { return } selectedIndexes.insert(indexPath) } else { viewModel?.useFile(at: (indexPath as NSIndexPath).row) tableView.deselectRow(at: indexPath, animated: true) } } override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { logDriveSubdomain(.Controller, .Info, "Index: \(indexPath.row)") if isEditing { if !isFileAudio(at: indexPath) { return } selectedIndexes.remove(indexPath) } } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return isFileAudio(at: indexPath) } override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { return isFileAudio(at: indexPath) ? .insert : .none } private func isFileAudio(at indexPath: IndexPath) -> Bool { return (viewModel?.file(at: indexPath.row)?.isAudio ?? false) } } extension YSDriveViewController: YSDriveFileTableViewCellDelegate { func downloadButtonPressed(_ id: String) { logDriveSubdomain(.Controller, .Info, "File id: " + id) viewModel?.download(id) } func stopDownloadButtonPressed(_ id: String) { logDriveSubdomain(.Controller, .Info, "File id: " + id) viewModel?.stopDownloading(id) } } extension YSDriveViewController: YSDriveViewModelViewDelegate { func filesDidChange(viewModel: YSDriveViewModelProtocol) { logDriveSubdomain(.Controller, .Info, "") DispatchQueue.main.async { [weak self] in self?.tableView.reloadData() } } func metadataDownloadStatusDidChange(viewModel: YSDriveViewModelProtocol) { logDriveSubdomain(.Controller, .Info, "") DispatchQueue.main.async { [weak self] in self?.navigationController?.setIndeterminate(viewModel.isDownloadingMetadata) if viewModel.allPagesDownloaded && !viewModel.isDownloadingMetadata { self?.tableView.mj_footer.endRefreshingWithNoMoreData() } } } func downloadErrorDidChange(viewModel: YSDriveViewModelProtocol, error: YSErrorProtocol, id: String) { logDriveSubdomain(.Controller, .Info, "File id: " + id + " Error: message: " + error.message + " debug message" + error.debugInfo) let message = SwiftMessages.createMessage(error) switch error.errorType { case .couldNotDownloadFile: message.buttonTapHandler = { _ in self.downloadButtonPressed(id) SwiftMessages.hide() } default: break } SwiftMessages.showDefaultMessage(message, isMessageErrorMessage: error.messageType == .error) } func downloadErrorDidChange(viewModel: YSDriveViewModelProtocol, error: YSErrorProtocol, download: YSDownloadProtocol) { downloadErrorDidChange(viewModel: viewModel, error: error, id: download.id) } func errorDidChange(viewModel: YSDriveViewModelProtocol, error: YSErrorProtocol) { logDriveSubdomain(.Controller, .Info, "File id: " + " Error: message: " + error.message + " debug message" + error.debugInfo) if error.isNoInternetError() { SwiftMessages.showNoInternetError(error) return } let message = SwiftMessages.createMessage(error) switch error.errorType { case .cancelledLoginToDrive, .couldNotLoginToDrive, .notLoggedInToDrive: message.buttonTapHandler = { _ in self.viewModel?.loginToDrive() SwiftMessages.hide() } case .loggedInToToDrive: message.buttonTapHandler = { _ in SwiftMessages.hide() } case .couldNotGetFileList: message.buttonTapHandler = { _ in SwiftMessages.hide() viewModel.refreshFiles {} } default: break } SwiftMessages.showDefaultMessage(message, isMessageErrorMessage: error.messageType == .error) } func reloadFile(at index: Int, viewModel: YSDriveViewModelProtocol) { logDriveSubdomain(.Controller, .Info, "Inex: \(index)") DispatchQueue.main.async { let indexPath = IndexPath.init(row: index, section: 0) self.tableView.reloadRows(at: [indexPath], with: .none) } } func reloadFileDownload(at index: Int, download: YSDownloadProtocol, viewModel: YSDriveViewModelProtocol) { logDriveSubdomain(.Controller, .Info, "Inex: \(index)") DispatchQueue.main.async { let indexPath = IndexPath.init(row: index, section: 0) switch download.downloadStatus { case .downloaded, .downloadError, .pending, .cancelled: self.tableView.reloadRows(at: [indexPath], with: .none) default: if let cell = self.tableView.cellForRow(at: indexPath) as? YSDriveFileTableViewCell { cell.updateDownloadButton(download: download) } else { self.tableView.reloadRows(at: [indexPath], with: .none) } } } } } extension YSDriveViewController: DZNEmptyDataSetSource { func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! { var promptText = "Browse your audio files from Google Drive" if let viewModel = viewModel, viewModel.isLoggedIn { promptText = "Folder is empty or there are no .mp3 files" } let attributes = [NSAttributedStringKey.foregroundColor: YSConstants.kDefaultBlueColor, NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 18.0)] let attributedString = NSAttributedString.init(string: promptText, attributes: attributes) return attributedString } func buttonTitle(forEmptyDataSet scrollView: UIScrollView!, for state: UIControlState) -> NSAttributedString! { var promptText = "Login" if let viewModel = viewModel, viewModel.isLoggedIn { promptText = "Reload" } let attributes = [NSAttributedStringKey.foregroundColor: UIColor.black, NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 17.0)] let attributedString = NSAttributedString.init(string: promptText, attributes: attributes) return attributedString } func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! { if let viewModel = viewModel, viewModel.isLoggedIn { return UIImage(named: "folder_small") } return UIImage(named: "drive") } func backgroundColor(forEmptyDataSet scrollView: UIScrollView!) -> UIColor! { return UIColor.white } } extension YSDriveViewController: DZNEmptyDataSetDelegate { func emptyDataSetShouldDisplay(_ scrollView: UIScrollView!) -> Bool { guard let viewModel = viewModel, !viewModel.isDownloadingMetadata else { return false } return !viewModel.isLoggedIn || viewModel.numberOfFiles < 1 } func emptyDataSet(_ scrollView: UIScrollView!, didTap button: UIButton!) { guard let viewModel = viewModel else { return } viewModel.isLoggedIn ? viewModel.refreshFiles {} : viewModel.loginToDrive() } func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView!) -> Bool { return true } } extension YSDriveViewController: YSToolbarViewDelegate { func selectAllButtonTapped(toolbar: YSToolbarView) { selectedIndexes.removeAll() if let viewModel = viewModel { for index in 0..<viewModel.numberOfFiles { if let file = viewModel.file(at: index), file.isAudio { let indexPath = IndexPath.init(row: index, section: 0) tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none) selectedIndexes.insert(indexPath) } } } } func downloadButtonTapped(toolbar: YSToolbarView) { viewModel?.downloadFilesFor(selectedIndexes) } func deleteButtonTapped(toolbar: YSToolbarView) { if selectedIndexes.count < 1 { let error = YSError.init(errorType: .none, messageType: .warning, title: "Select files", message: "Please, select at least one file", buttonTitle: "") if let viewModel = viewModel { errorDidChange(viewModel: viewModel, error: error) } return } let alertController = UIAlertController(title: "Confirm", message: "Deleting \(selectedIndexes.count) local files", preferredStyle: .actionSheet) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) alertController.addAction(cancelAction) let destroyAction = UIAlertAction(title: "Confirm", style: .destructive) { (_) in self.viewModel?.deleteDownloadsFor(self.selectedIndexes) } alertController.addAction(destroyAction) YSAppDelegate.topViewController()?.present(alertController, animated: true) } }
mit
4bff3c055e189905b3f14e9758e2125f
39.911528
205
0.650721
5.155405
false
false
false
false
nwest/Conway
Conway/Board.swift
1
1558
// // Board.swift // Conway // // Created by Nate West on 2/22/15. // Copyright (c) 2015 Nate West. All rights reserved. // import Foundation public struct Board { public let cells: [Cell] public func addCell(cell: Cell) -> Board { var cells = self.cells if let existing = find(self.cells, cell) { cells.removeAtIndex(existing) } cells.insert(cell, atIndex: cells.count) return Board(cells: cells) } public func cellAtLocation(location: Coordinate) -> (Cell?, Int?) { for var index = 0; index < self.cells.count; ++index { let cell = self.cells[index] if (cell.location == location) { return (cell, index) } } return (nil, nil) } public func toggle(location: Coordinate) -> Board { let (cell, index) = cellAtLocation(location) if let unwrappedCell = cell { let inverted = unwrappedCell.toggle() return addCell(inverted) } return self } } func generateBoard(width:Int, height:Int) -> Board { var newCells: [Cell] = [] for var x = 0; x < width; x++ { for var y = 0; y < height; y++ { let newCell = Cell(location: Coordinate(x: x, y: y), state: .Off) newCells.insert(newCell, atIndex: newCells.endIndex) } } return Board(cells: newCells) } extension Array { func contains<T where T :Equatable>(obj: T) -> Bool { return self.filter({$0 as? T == obj}).count > 0 } }
mit
5283af256165d3f85bc07958ee4195b4
24.966667
77
0.560334
3.772397
false
false
false
false
306244907/Weibo
JLSina/JLSina/Classes/ViewModel(视图模型)/JLStatusViewModel.swift
1
8320
// // JLStatusViewModel.swift // JLSina // // Created by 盘赢 on 2017/11/15. // Copyright © 2017年 JinLong. All rights reserved. // import Foundation //单条微博的视图模型 /** 如果没有任何父类,如果希望在开发时调试,输出调试信息 1,遵守 CustomStringConvertible 2,实现 description 计算型属性 关于表格的性能优化 - 尽量少计算,所有的素材提前计算好 - 控件上不要设置圆角半径,所有图像渲染的属性,都要注意 - 不要动态创建空间,所有需要的控件,都要提前创建好,在显示的时候,根据数据隐藏,显示 (用内存换取CPU) - cell中控件的层次越少越好,数量越少越好 - 要测量,不要猜测! */ class JLStatusViewModel: CustomStringConvertible { //微博模型 var status: JLStatus //会员图标 var memberIcon: UIImage? //认证类型。-1:没有认证 0:认证用户,2,3,5企业认真 , 220:达人 var vipIcon: UIImage? //转发文字 var retweetedStr: String? //评论文字 var commentsStr: String? //点赞文字 var likeStr: String? //配图视图大小 var pictureViewSize = CGSize() //如果是被转发的微博,原创微博一定没有图片 var picURLs: [JLStatusPicture]? { //如果有被转发的微博,返回被转发微博配图 //如果没有被转发的微博,返回原创微博的配图 //如果都没有,返回 nil return status.retweeted_status?.pic_urls ?? status.pic_urls } //微博正文属性文本 var statusAttrText: NSAttributedString? //被转发微博文字 var retweetedAttrText: NSAttributedString? //行高 var rowHeight: CGFloat = 0 //构造函数 init(model: JLStatus) { self.status = model //common_icon_membership_level1 //会员等级0-6 if (model.user?.mbrank)! > 0 && (model.user?.mbrank)! < 7 { let imageName = "common_icon_membership_level\(model.user?.mbrank ?? 1)" memberIcon = UIImage.init(named: imageName) } //认证图标 switch model.user?.verified_type ?? -1 { case 0: vipIcon = UIImage.init(named: "avatar_vip") case 2, 3, 5: vipIcon = UIImage.init(named: "avatar_enterprise_vip") case 220: vipIcon = UIImage.init(named: "avatar_grassroot") default: break } // model.reposts_count = Int(arc4random_uniform(100000)) //设置底部计数字符串 retweetedStr = countString(count: status.reposts_count, defaultString: "转发") commentsStr = countString(count: status.comments_count, defaultString: "评论") likeStr = countString(count: status.attitudes_count, defaultString: "点赞") //计算配图视图大小(有原创,计算原创,有转发计算转发) pictureViewSize = calcPictureViewSize(count: picURLs?.count) //--设置微博文本-- let originalFont = UIFont.systemFont(ofSize: 15) let retweetedFont = UIFont.systemFont(ofSize: 14) //微博正文的属性文本 statusAttrText = CZEmoticonManager.shared.emoticonString(string: model.text ?? "", font: originalFont) //设置被转发微博文字 let subStr = "@" + (status.retweeted_status?.user?.screen_name ?? "") + ":" let rText = subStr + (status.retweeted_status?.text ?? "") retweetedAttrText = CZEmoticonManager.shared.emoticonString(string: rText, font: retweetedFont) //计算行高 updateRowHeight() } //根据当前视图模型内容,计算行高 func updateRowHeight() { let margin: CGFloat = 12 let iconHeight: CGFloat = 34 let toolBarHeight: CGFloat = 35 var height: CGFloat = 0 let viewSize = CGSize(width: UIScreen.cz_screenWidth() - 2 * margin, height: CGFloat(MAXFLOAT)) // let originalFont = UIFont.systemFont(ofSize: 15) // let retweetedFont = UIFont.systemFont(ofSize: 14) //1,计算顶部位置 height = 2 * margin + iconHeight + margin //2,正文高度 if let text = statusAttrText { //属性文本中本身已经包含了字体属性 height += text.boundingRect(with: viewSize, options: [.usesLineFragmentOrigin], context: nil).height // height += (text as NSString).boundingRect(with: viewSize, options: [.usesLineFragmentOrigin], attributes: [NSAttributedStringKey.font: originalFont], context: nil).height } //3,判断是否转发微博 if status.retweeted_status != nil { height += 2 * margin //转发文本的高度 - 一定用retweetedText,拼接过后的字符串 if let text = retweetedAttrText { height += text.boundingRect(with: viewSize, options: [.usesLineFragmentOrigin], context: nil).height } } //4,配图视图 height += pictureViewSize.height height += margin //5,底部工具栏 height += toolBarHeight //6,使用属性记录 rowHeight = height } //使用单个图像,更新配图视图的大小 //新浪针对单张图片,都是缩略图,偶尔有张特别大的图 //新浪微博,为了鼓励原创,支持‘长微博’,但是有的时候有特别长的微博,长到宽度只有一个点 //image:网络缓存的单张图像 func updateSingleImageSize(image: UIImage) { var size = image.size //过宽图像处理 let maxWidth: CGFloat = 300 let minWidth: CGFloat = 40 if size.width > maxWidth { size.width = maxWidth //等比例调整高度 size.height = size.width * image.size.height / image.size.width } //过窄图像处理 if size.width < minWidth { size.width = minWidth //要特殊处理高度,高度太大,会影响用户体验 size.height = size.width * image.size.height / image.size.width / 4 } //特例:有些图像,本身就是很窄很长 ->定义 minHeight,思路同上 //在工作中,如果看到代码中有些疑惑的分支处理,不要动,有风险 //注意,尺寸需要增加顶部12个点,便于布局 size.height += JLStatusPictureViewOutterMargin //重新设置配图视图大小 pictureViewSize = size //更新行高 updateRowHeight() } //计算指定数量的图片,对应的配图视图的大小 //count:配图数量 return:配图视图大小 private func calcPictureViewSize(count: Int?) -> CGSize { if count == 0 || count == nil{ return CGSize() } //2,计算高度 //1>,根据count知道行数 1-9 let row = (count! - 1) / 3 + 1 //2>根据行数算高度 var height = JLStatusPictureViewOutterMargin height += CGFloat(row) * JLStatusPictureItemWidth height += CGFloat(row - 1) * JLStatusPictureViewInnerMargin return CGSize(width: JlStatusPictureViewWidth, height: height) } //给定一个数字,返回对应的描述函数 //count 数字 //defailtString 默认字符串 转发/评论/赞 //returns: 描述结果 /** 0 - 显示默认标题 > 10000 ,显示x.xx万 < 10000 ,显示实际数字 */ private func countString(count: Int , defaultString: String) -> String { if count == 0 { return defaultString } if count < 10000 { return count.description } return String(format: "%.02f 万" , Double(count / 10000)) } var description: String { return status.description } }
mit
3dde33c0e48b8f3e14586fd331159a48
26.717213
183
0.56469
3.857958
false
false
false
false
macemmi/HBCI4Swift
HBCI4Swift/HBCI4Swift/Source/Message/HBCICustomMessage.swift
1
7076
// // HBCICustomMessage.swift // HBCI4Swift // // Created by Frank Emminghaus on 04.02.15. // Copyright (c) 2015 Frank Emminghaus. All rights reserved. // import Foundation // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // 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 } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // 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 default: return !(lhs < rhs) } } open class HBCICustomMessage : HBCIMessage { let dialog:HBCIDialog; var success = false; var tan:String? open var orders = Array<HBCIOrder>(); var result:HBCIResultMessage? init(msg:HBCIMessage, dialog:HBCIDialog) { self.dialog = dialog; super.init(description: msg.descr); self.children = msg.children; self.name = msg.name; self.length = msg.length; } open class func newInstance(_ dialog:HBCIDialog) ->HBCICustomMessage? { if let md = dialog.syntax.msgs["CustomMessage"] { if let msg = md.compose() as? HBCIMessage { if let dialogId = dialog.dialogId { if !msg.setElementValue(dialogId, path: "MsgHead.dialogid") { return nil; } if !msg.setElementValue(dialog.messageNum, path: "MsgHead.msgnum") { return nil; } if !msg.setElementValue(dialog.messageNum, path: "MsgTail.msgnum") { return nil; } return HBCICustomMessage(msg: msg, dialog: dialog); } else { logInfo("No dialog started yet (dialog ID is missing)"); } } } return nil; } open func addOrder(_ order:HBCIOrder, afterSegmentCode:String? = nil) -> Bool { if let segment = order.segment { orders.append(order); if let segmentCode = afterSegmentCode { if !self.insertAfterSegmentCode(segment, segmentCode) { logInfo("Error adding segment after "+segmentCode); return false; } } else { self.children.insert(segment, at: 2); } } else { logInfo("Order comes without segment!"); return false; } return true; } func addTanOrder(_ order:HBCITanOrder) ->Bool { guard let refOrder = orders.last else { logInfo("No order in message"); return false; } if !order.finalize(refOrder) { return false; } return addOrder(order, afterSegmentCode: refOrder.segment.code); } func segmentWithName(_ segName:String) ->HBCISegment? { if let segVersions = self.descr.syntax.segs[segName] { // now find the right segment version // check which segment versions are supported by the bank var supportedVersions = Array<Int>(); for seg in dialog.user.parameters.bpSegments { if seg.name == segName+"Par" { // check if this version is also supported by us if segVersions.isVersionSupported(seg.version) { supportedVersions.append(seg.version); } } } if supportedVersions.count == 0 { // this process is not supported by the bank logInfo("Process \(segName) is not supported, no parameter information found"); // In some cases the bank does not send any Parameter but the process is still supported // let's just try it out supportedVersions = segVersions.versionNumbers; } // now sort the versions - we take the latest supported version supportedVersions.sort(by: >); if let sd = segVersions.segmentWithVersion(supportedVersions.first!) { if let segment = sd.compose() as? HBCISegment { segment.name = segName; return segment; } } } else { logInfo("Segment \(segName) is not supported by HBCI4Swift"); } return nil; } open func send() throws ->Bool { // check if orders.count == 0 { logInfo("Custom message contains no orders"); return false; } if dialog.user.securityMethod is HBCISecurityMethodDDV { return try sendNoTan(); } // first check if there is one order which needs a TAN - then there can be only one order var needsTan = false; for order in orders { if order.needsTan { needsTan = true; } } if needsTan && orders.count > 1 { logInfo("Custom message contains several TAN-based orders. This is not supported"); return false; } if needsTan { if dialog.user.tanMethod == nil { logInfo("Custom message order needs TAN but no TAN method provided for user"); return false; } // if order needs TAN transfer to TAN message processor let process = HBCITanProcess_2(dialog: self.dialog); return try process.processMessage(self, orders.last!) } return try sendNoTan(); } func sendNoTan() throws ->Bool { if let result = try self.dialog.sendMessage(self) { self.result = result; let responses = result.responsesForMessage(); self.success = true; for response in responses { if Int(response.code) >= 9000 { logError("Banknachricht: "+response.description); self.success = false; } else { logInfo("Banknachricht: "+response.description); } } if self.success { for order in orders { order.updateResult(result); } return true; } } return false; } override func validate() ->Bool { var success = true; // The custom message is a template message, we therefore have to check the segments one by one for childElem in children { if !childElem.isEmpty { if !childElem.validate() { success = false; } } } return success; } }
gpl-2.0
530e132dc880f53cba8b163d2c4f70de
32.856459
104
0.53844
4.755376
false
false
false
false
theappbusiness/TABResourceLoader
Example/Models/Multiple responses example/CitiesResponse.swift
1
826
// // CitiesResponse.swift // TABResourceLoader // // Created by Luciano Marisi on 22/02/2017. // Copyright © 2017 Kin + Carta. All rights reserved. // import Foundation enum CitiesResponseError: Error { case parsingFailed } enum CitiesResponse { case cities([City]) case city(City) case serverError(ServerError) } extension CitiesResponse { public init(jsonDictionary: [String: Any]) throws { if let citiesJSONArray = jsonDictionary["cities"] as? [[String: Any]] { self = .cities(citiesJSONArray.compactMap(City.init)) } else if let city = City(jsonDictionary: jsonDictionary) { self = .city(city) } else if let serverError = ServerError(jsonDictionary: jsonDictionary) { self = .serverError(serverError) } else { throw CitiesResponseError.parsingFailed } } }
mit
0e82873b4ccba2282da097cf362fe3f6
24
77
0.698182
4.064039
false
false
false
false
MyBar/MyBarMusic
MyBarMusic/MyBarMusic/Classes/Player/View/MBPlayerAlbumCoverView.swift
1
2913
// // MBPlayerAlbumCoverView.swift // MyBarMusic // // Created by lijingui2010 on 2017/7/11. // Copyright © 2017年 MyBar. All rights reserved. // import UIKit class MBPlayerAlbumCoverView: UIView { @IBOutlet weak var singerLabel: UILabel! @IBOutlet weak var albumCoverImageView: RotationAnimationImageView! @IBOutlet weak var lyricLabel: UILabel! @IBOutlet weak var playerEffectView: UIView! class var playerAlbumCoverView: MBPlayerAlbumCoverView { let playerAlbumCoverView = Bundle.main.loadNibNamed("MBPlayerAlbumCoverView", owner: nil, options: nil)?.last as? MBPlayerAlbumCoverView playerAlbumCoverView?.backgroundColor = UIColor.clear playerAlbumCoverView?.setupAlbumCoverView() return playerAlbumCoverView! } func setupAlbumCoverView() { self.albumCoverImageView.image = UIImage(named: "player_albumcover_default")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal) self.albumCoverImageView.backgroundColor = UIColor.black let margin: CGFloat = 8.0 let albumMargin: CGFloat = 24.0 let width = self.frame.width - 2 * albumMargin let height = self.frame.height - playerEffectView.frame.maxY - lyricLabel.frame.height - margin - 2 * albumMargin if width >= height { self.albumCoverImageView.frame = CGRect(x: albumMargin + (width - height) / 2, y: albumMargin + playerEffectView.frame.maxY, width: height, height: height) } else { self.albumCoverImageView.frame = CGRect(x: albumMargin, y: albumMargin + playerEffectView.frame.maxY + (height - width) / 2, width: width, height: width) } self.albumCoverImageView.layer.cornerRadius = self.albumCoverImageView.frame.width / 2 self.albumCoverImageView.layer.masksToBounds = true self.albumCoverImageView.layer.borderWidth = 8 self.albumCoverImageView.layer.borderColor = UIColor.lightGray.cgColor } func updateAlbumCoverView(with: UIImage?) { self.albumCoverImageView.image = (with ?? UIImage(named: "player_albumcover_default"))?.withRenderingMode(UIImageRenderingMode.alwaysOriginal) } var rotationAngle: CGFloat { return self.albumCoverImageView.rotationAngle } //初始化动画 func initAnimation(with rotationAngle: CGFloat = 0.0) { self.albumCoverImageView.initAnimation(with: rotationAngle) } //启动动画 func resumeAnimation() { self.albumCoverImageView.resumeAnimation() } //暂停动画 func pauseAnimation() { self.albumCoverImageView.pauseAnimation() } //移除动画 func removeAnimation() { self.albumCoverImageView.removeAnimation() } }
mit
cbcdb0da9fa0181c9efcef92125da7bc
32.057471
167
0.663074
4.707038
false
false
false
false
saragiotto/TMDbFramework
Example/TMDbFramework/OverviewCell.swift
1
4252
// // OverviewCell.swift // TMDbFramework // // Created by Leonardo Augusto N Saragiotto on 18/08/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit class OverviewCell: BaseCell { var overviewTextView: UILabel override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { self.overviewTextView = UILabel() super.init(style: style, reuseIdentifier: reuseIdentifier) self.commomInit() } required init?(coder aDecoder: NSCoder) { self.overviewTextView = UILabel() super.init(coder: aDecoder) self.commomInit() } func commomInit() { self.overviewTextView = OverviewCell.labelConfiguration() self.contentView.addSubview(self.overviewTextView) self.setConstraints() } static func labelConfiguration() -> UILabel { let label = UILabel() label.textColor = UIColor.lightText label.font = UIFont.systemFont(ofSize: 12.0) label.textAlignment = .justified label.numberOfLines = 0 label.lineBreakMode = .byWordWrapping label.backgroundColor = UIColor.clear label.translatesAutoresizingMaskIntoConstraints = false return label } static func getOverviewCellSize(for viewCellModel: OverviewCellViewModel) -> CGSize { let autoLayoutLabel = OverviewCell.labelConfiguration() let margins = CGFloat(16.0) autoLayoutLabel.text = viewCellModel.overview let screenSize = UIScreen.main.bounds let labelSize = autoLayoutLabel.sizeThatFits(CGSize(width: Double(screenSize.width - margins), height: Double(MAXFLOAT))) return CGSize(width: screenSize.width - margins, height: labelSize.height + margins) } override func layoutSubviews() { super.layoutSubviews() } func setConstraints() { self.contentView.addConstraints([NSLayoutConstraint.init(item: self.overviewTextView, attribute: .left, relatedBy: .equal, toItem: self.contentView, attribute: .left, multiplier: 1.0, constant: 8.0), NSLayoutConstraint.init(item: self.overviewTextView, attribute: .top, relatedBy: .equal, toItem: self.contentView, attribute: .top, multiplier: 1.0, constant: 8.0), NSLayoutConstraint.init(item: self.overviewTextView, attribute: .right, relatedBy: .equal, toItem: self.contentView, attribute: .right, multiplier: 1.0, constant: -8.0)]) } func configureWith(_ viewCellModel: OverviewCellViewModel) { self.overviewTextView.text = viewCellModel.overview self.overviewTextView.sizeToFit() self.contentView.sizeToFit() } }
mit
9f581272ca411ebd6638a0f9607197e7
39.485714
129
0.474006
6.580495
false
false
false
false
335g/TwitterAPIKit
Sources/Utils.swift
1
551
// // Utils.swift // TwitterAPIKit // // Created by Yoshiki Kudo on 2015/07/04. // Copyright © 2015年 Yoshiki Kudo. All rights reserved. // import Foundation internal func queryStringsFromParameters(infos: [String: AnyObject?]) -> [String: String] { var strings: [String: String] = [:] for (key, obj) in infos { if let obj: AnyObject = obj { let objString = obj as? String ?? "\(obj)" if objString != "" { strings[key] = objString } } } return strings }
mit
730a16b40c87a8a4ad5c8c00d9c825fc
22.826087
91
0.562044
3.805556
false
false
false
false
ZhengShouDong/CloudPacker
Sources/CloudPacker/Service/CodeEncrypt.swift
1
4086
// // CodeEncrypt.swift // CloudPacker // // Created by ZHENGSHOUDONG on 2018/4/9. // import Foundation /// -------------------------------------------------------------------------------------------------------------- /// fileprivate var key = "O3lWqyqg3mFhHMEm" fileprivate var iv = "fua5vC5Msgvt7gTH" struct CodeEncrypt { enum encryptDecryptDisposeType { /// 加密 case encrypt /// 解密 case decrypt } /// 加密 private static func fileEncrypt(fileContent: String) -> String { do { let cipher = try AES(key: key, iv: iv, padding: .pkcs7) let ciphertext = try cipher.encrypt(Array(fileContent.utf8)).toBase64() return ciphertext ?? String() } catch { printLog(message: "\(error)", type: .error) return String() } } /// 解密 private static func fileDecrypt(fileContent: String) -> String { do { let cipher = try AES(key: key, iv: iv, padding: .pkcs7) let result = try fileContent.decryptBase64ToString(cipher: cipher) return result } catch { printLog(message: "\(error)", type: .error) return String() } } /// 递归目录,遍历寻找指定文件进行加密 public static func recursiveDirEncrypt(_ path: String, type: encryptDecryptDisposeType) { if (path.isEmpty || !FileManager.default.fileExists(atPath: path)) { printLog(message: "传入的路径有误!\(path)", type: .error) return } do { let names = try FileManager.default.contentsOfDirectory(atPath: path) for name in names { if (name.hasPrefix(".")) { // 过滤隐藏文件 continue } var secondLevelPath = String(format: "%@/%@", path, name) var isDir: ObjCBool = ObjCBool(false) let isExist = FileManager.default.fileExists(atPath: secondLevelPath, isDirectory: &isDir) if (!isExist) { continue } if (isDir.boolValue) { DispatchQueue.global().async { recursiveDirEncrypt(secondLevelPath, type: type) } }else { if (name.hasSuffix(".js") || name.hasSuffix(".xml") || name.hasSuffix(".css") || name.hasSuffix(".html") || name.hasSuffix(".json")) { let data = try String(contentsOfFile: secondLevelPath, encoding: .utf8) var base64String = String() if (type == .decrypt) { base64String = fileDecrypt(fileContent: data) }else { base64String = fileEncrypt(fileContent: data) } if (!base64String.isEmpty) { if (name == "config.xml") { // 特殊处理config.xml try "<?xml version=\"1.0\" encoding=\"UTF-8\"?><widget></widget>".write(toFile: secondLevelPath, atomically: true, encoding: .utf8) secondLevelPath = String(format: "%@/config.bak.xml", path) } try base64String.write(toFile: secondLevelPath, atomically: true, encoding: .utf8) }else { // 加密或解密失败! printLog(message: "路径为:\(secondLevelPath) 加密或解密失败!", type: .error) } } } } }catch { printLog(message: "加密或解密流程异常:\(error)", type: .error) } } }
apache-2.0
117466312847cdd11faad96470b24ae5
36.283019
163
0.447874
4.996207
false
false
false
false
TrondKjeldas/KnxBasics2
Source/KnxTelegramFactory.swift
1
7296
// // KnxTelegramFactory.swift // KnxBasics2 // // The KnxBasics2 framework provides basic interworking with a KNX installation. // Copyright © 2016 Trond Kjeldås ([email protected]). // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License Version 2.1 // as published by the Free Software Foundation. // // This library 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 Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // import Foundation /// Factory class to create KNX telegrams of various type. open class KnxTelegramFactory { // MARK: Public API /** Create a subscription request. - parameter groupAddress: The group address to subscribe to. - returns: A subscription request telegram, ready to be sent. */ public static func createSubscriptionRequest(groupAddress: KnxGroupAddress) -> KnxTelegram { let addrLow8 = UInt8(truncatingIfNeeded:(groupAddress.addressAsUInt16 & 0xFF)) let addrHigh8 = UInt8(truncatingIfNeeded:(groupAddress.addressAsUInt16 >> 8)) var bytes: [UInt8] = [UInt8](repeating: 0, count: 7) // Length... bytes[0] = 0 bytes[1] = 5 // Content bytes[2] = 0 bytes[3] = 34 bytes[4] = addrHigh8 bytes[5] = addrLow8 bytes[6] = 0x00 return KnxTelegram(bytes: bytes) } /** Create a read request. - returns: A read request telegram, ready to be sent. */ public static func createReadRequest(to: KnxGroupAddress) -> KnxTelegram { var bytes: [UInt8] switch KnxRouterInterface.connectionType { case .tcpDirect: bytes = [UInt8](repeating: 0, count: 6) // Length... bytes[0] = 0 bytes[1] = 4 // Content bytes[2] = 0 bytes[3] = 37 bytes[4] = 0 bytes[5] = 0 case .udpMulticast: bytes = [UInt8](repeating: 0, count: 11) bytes[0] = 0x29 bytes[1] = 0x00 bytes[2] = 0xBC bytes[3] = 0xD0 bytes[4] = UInt8((KnxRouterInterface.knxSourceAddr.addressAsUInt16 >> 8) & 0xFF) // src addr bytes[5] = UInt8(KnxRouterInterface.knxSourceAddr.addressAsUInt16 & 0xFF) // src addr bytes[6] = UInt8((to.addressAsUInt16 >> 8) & 0xFF) // dst addr bytes[7] = UInt8(to.addressAsUInt16 & 0xFF) // dst addr bytes[8] = 0x01 // NPDU len bytes[9] = 0x00 bytes[10] = 0x00 default: bytes = [UInt8](repeating: 0, count: 6) //log.warning("Connection not set") } return KnxTelegram(bytes: bytes) } /** Create a write request telegram. - parameter type: DPT type. - parameter value: The value to write, as an integer. - returns: A telegram, ready to be sent. - throws: UnknownTelegramType */ public static func createWriteRequest(to: KnxGroupAddress, type: KnxTelegramType, value: Int) throws -> KnxTelegram { switch type { case .dpt1_xxx: return createDpt1_xxxWriteRequest(to: to, value: value) case .dpt5_001: return createDpt5_001WriteRequest(to: to, value: value) default: throw KnxException.unknownTelegramType } } /** Create a write request telegram for DPT5_001. - parameter to: Group address to write to. - parameter value: The value to write, as an integer. - returns: A telegram, ready to be sent. */ private static func createDpt5_001WriteRequest(to: KnxGroupAddress, value: Int) -> KnxTelegram { var bytes: [UInt8] switch KnxRouterInterface.connectionType { case .tcpDirect: bytes = [UInt8](repeating: 0, count: 7) // Length... bytes[0] = 0 bytes[1] = 5 // Content bytes[2] = 0 bytes[3] = 37 bytes[4] = 0 bytes[5] = 0x80 bytes[6] = UInt8(truncatingIfNeeded:((value * 255) / 100)) /* Convert range from 0-100 to 8bit */ case .udpMulticast: bytes = [UInt8](repeating: 0, count: 12) bytes[0] = 0x29 bytes[1] = 0x00 bytes[2] = 0xBC bytes[3] = 0xD0 bytes[4] = UInt8((KnxRouterInterface.knxSourceAddr.addressAsUInt16 >> 8) & 0xFF) // src addr bytes[5] = UInt8(KnxRouterInterface.knxSourceAddr.addressAsUInt16 & 0xFF) // src addr bytes[6] = UInt8((to.addressAsUInt16 >> 8) & 0xFF) // dst addr bytes[7] = UInt8(to.addressAsUInt16 & 0xFF) // dst addr bytes[8] = 0x02 // NPDU len bytes[9] = 0x00 bytes[10] = 0x80 bytes[11] = UInt8(truncatingIfNeeded:((value * 255) / 100)) /* Convert range from 0-100 to 8bit */ default: bytes = [UInt8](repeating: 0, count: 6) //log.warning("Connection not set") } return KnxTelegram(bytes: bytes) } /** Create a write request telegram for DPT1_xxx. - parameter to: Group address to write to. - parameter value: The value to write, as an integer. - returns: A telegram, ready to be sent. */ private static func createDpt1_xxxWriteRequest(to: KnxGroupAddress, value: Int) -> KnxTelegram { var bytes: [UInt8] switch KnxRouterInterface.connectionType { case .tcpDirect: bytes = [UInt8](repeating: 0, count: 6) // Length... bytes[0] = 0 bytes[1] = 4 // Content bytes[2] = 0 bytes[3] = 37 bytes[4] = 0 bytes[5] = UInt8(truncatingIfNeeded:value) | 0x80 case .udpMulticast: bytes = [UInt8](repeating: 0, count: 11) bytes[0] = 0x29 bytes[1] = 0x00 bytes[2] = 0xBC bytes[3] = 0xD0 bytes[4] = UInt8((KnxRouterInterface.knxSourceAddr.addressAsUInt16 >> 8) & 0xFF) // src addr bytes[5] = UInt8(KnxRouterInterface.knxSourceAddr.addressAsUInt16 & 0xFF) // src addr bytes[6] = UInt8((to.addressAsUInt16 >> 8) & 0xFF) // dst addr bytes[7] = UInt8(to.addressAsUInt16 & 0xFF) // dst addr bytes[8] = 0x01 // NPDU len bytes[9] = 0x00 bytes[10] = UInt8(truncatingIfNeeded:value) | 0x80 default: bytes = [UInt8](repeating: 0, count: 6) //log.warning("Connection not set") } return KnxTelegram(bytes: bytes) } }
lgpl-2.1
112d39011dfc62af3e68c919055ae404
31.132159
110
0.559501
3.851109
false
false
false
false
aidangomez/RandKit
Tests/UniformTests.swift
1
696
// Copyright © 2016 Aidan Gomez. // // This file is part of RandKit. The full RandKit copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. import XCTest import RandKit class UniformTests: XCTestCase { func testUniform() { let n = 10000 let samples: [Double] = (0..<n).map({ _ in random() }) for i in 0..<n { let sample = samples[i] XCTAssert(0 <= sample && sample < 1) } let mean = samples.reduce(0.0, combine: +) / ContinuousValue(n) XCTAssertEqualWithAccuracy(mean, 0.5, accuracy: 0.007) } }
mit
9ab87e8e6d636e5a3b4aa4673be7ecd8
26.84
77
0.631655
3.971429
false
true
false
false
tomasharkema/HoelangTotTrein2.iOS
HoelangTotTrein2/Observable.swift
1
3737
// // Observable.swift // HoelangTotTrein2 // // Created by Tomas Harkema on 27-09-15. // Copyright © 2015 Tomas Harkema. All rights reserved. // import Foundation import Promissum struct ObservableSubject<ValueType>: Equatable { let guid = NSUUID().UUIDString let observeOn: dispatch_queue_t let observable: (ValueType) -> Void let once: Bool } func == <ValueType>(lhs: ObservableSubject<ValueType>, rhs: ObservableSubject<ValueType>) -> Bool { lhs.guid == rhs.guid } class Observable<ValueType where ValueType: Equatable> { private let queue = dispatch_queue_create("nl.tomasharkema.Observable", DISPATCH_QUEUE_SERIAL) private var value: ValueType? { didSet { notifiy() } } private var subjects = [ObservableSubject<ValueType>]() private func notifiy() { if let value = value { for subject in subjects { dispatch_async(subject.observeOn) { subject.observable(value) } if subject.once { unsubscribe(subject) } } } else { print("Notifying without value?!") } } func subscribe(subject: (ValueType) -> Void) -> ObservableSubject<ValueType> { subscribe(dispatch_get_main_queue(), subject: subject) } func subscribe(observeOn: dispatch_queue_t, subject: (ValueType) -> Void) -> ObservableSubject<ValueType> { var subscription: ObservableSubject<ValueType>! dispatch_sync(queue) { [weak self] in subscription = ObservableSubject(observeOn: observeOn, observable: subject, once: false) self?.subjects.append(subscription) if let value = self?.value { dispatch_async(observeOn) { subject(value) } } } return subscription } func unsubscribe(subject: ObservableSubject<ValueType>) { dispatch_async(queue) { [weak self] in if let index = self?.subjects.indexOf(subject) { self?.subjects.removeAtIndex(index) } } } func next(value: ValueType) { dispatch_sync(queue) { [weak self] in if value != self?.value { self?.value = value } } } init() {} init(initialValue: ValueType) { value = initialValue } } // MARK: Once Trigger extension Observable { func once(observeOn: dispatch_queue_t = dispatch_get_main_queue(), subject: (ValueType) -> Void) -> ObservableSubject<ValueType> { var subscription: ObservableSubject<ValueType>! dispatch_sync(queue) { [weak self] in subscription = ObservableSubject(observeOn: observeOn, observable: subject, once: true) self?.subjects.append(subscription) } return subscription } } // MARK: Monad 🤓 extension Observable { func map<NewValueType>(transform: ValueType -> NewValueType) -> (mapSubscription: ObservableSubject<ValueType>, newObservable: Observable<NewValueType>) { let newObservable = Observable<NewValueType>() let subscription = subscribe { newObservable.next(transform($0)) } return (subscription, newObservable) } func mapOnce<NewValueType>(transform: ValueType -> NewValueType) -> (mapSubscription: ObservableSubject<ValueType>, newPromise: Promise<NewValueType, NoError>) { let promise = PromiseSource<NewValueType, NoError>() let subscription = once { promise.resolve(transform($0)) } return (subscription, promise.promise) } func flatMap<NewValueType>(transfrom: ValueType -> Observable<NewValueType>) -> (flatMapSubscription: ObservableSubject<ValueType>, newObservable: Observable<NewValueType>) { let newObservable = Observable<NewValueType>() let subscription = subscribe { transfrom($0).once { newObservable.next($0) } } return (subscription, newObservable) } }
mit
ae49c010b5f7e62be06b8212ff63a6fc
25.856115
176
0.674792
4.242045
false
false
false
false
King-Wizard/Swift-Spotify-Like-Carousel
PagesTest/PagesTest/ContentViewController.swift
1
1901
// The MIT License (MIT) // // Copyright (c) 2015 // King-Wizard // // 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 class ContentViewController: UIViewController { @IBOutlet weak var labelOutlet: UILabel! @IBOutlet weak var textViewOutlet: UITextView! var index: Int = 0 var titleText: String! var descriptionText: String! override func viewDidLoad() { super.viewDidLoad() self.labelOutlet.text = self.titleText self.labelOutlet.layer.shadowColor = UIColor.blackColor().CGColor self.labelOutlet.layer.shadowOffset = CGSizeMake(0, 0.5) self.labelOutlet.layer.shadowOpacity = 2.0 self.labelOutlet.layer.shadowRadius = 0.5 self.textViewOutlet.text = self.descriptionText // Do any additional setup after loading the view. } }
mit
eded43bc4fb323dcf253399247717998
37.795918
81
0.718043
4.647922
false
false
false
false
Darren-chenchen/yiyiTuYa
testDemoSwift/Controller/EditorViewController.swift
1
11431
// // EditorViewController.swift // testDemoSwift // // Created by 陈亮陈亮 on 2017/5/22. // Copyright © 2017年 陈亮陈亮. All rights reserved. // import UIKit class EditorViewController: UIViewController { // 模式 @IBOutlet weak var typeLable: UILabel! // 画笔 @IBOutlet weak var pencilBtn: UIButton! // 橡皮擦 @IBOutlet weak var eraserBtn: UIButton! // 设置view @IBOutlet weak var settingView: UIView! // 需要编辑的图片 var editorImage: UIImage! var scrollView: UIScrollView! // 画板 var drawBoardImageView: DrawBoard! // 涂鸦的背景样式 @IBOutlet weak var pencilImage: UIImageView! // 控制画笔的粗细 @IBOutlet weak var slideView: UISlider! // 撤回 @IBOutlet weak var backBtn: UIButton! // 前进 @IBOutlet weak var forwardBtn: UIButton! // 还原 @IBOutlet weak var returnBtn: UIButton! var lastScaleFactor : CGFloat! = 1 //放大、缩小 lazy var choosePencilView: PencilChooseView = { let chooseView = PencilChooseView.init(frame: CGRect(x: 0, y: KScreenHeight, width: KScreenWidth, height: 40)) chooseView.clickPencilImage = {[weak self] (img:UIImage) in self?.drawBoardImageView.strokeColor = UIColor(patternImage: img) self?.pencilImage.image = img self?.choosePencilViewDismiss() // 先判断是不是文本,如果是文本,直接设置文本的颜色 if self?.drawBoardImageView.brush?.classForKeyedArchiver == InputBrush.classForCoder() { return } // 马赛克 if img == UIImage(named: "11") { self?.drawBoardImageView?.brush = RectangleBrush() } else if img == UIImage(named: "12") { // 高斯模糊 self?.drawBoardImageView?.brush = GaussianBlurBrush() } else { self?.drawBoardImageView?.brush = PencilBrush() } self?.pencilBtn.isSelected = true self?.eraserBtn.isSelected = false } return chooseView }() override func viewDidLoad() { super.viewDidLoad() self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false initView() } func initView() { pencilBtn.setTitleColor(UIColor.red, for: .selected) pencilBtn.setTitleColor(UIColor.black, for: .normal) eraserBtn.setTitleColor(UIColor.red, for: .selected) eraserBtn.setTitleColor(UIColor.black, for: .normal) backBtn.isEnabled = false forwardBtn.isEnabled = false slideView.setThumbImage(UIImage(named:"dian"), for: .normal) slideView.value = 0.3 pencilImage.layer.cornerRadius = 4 pencilImage.layer.masksToBounds = true pencilImage.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(EditorViewController.clickPencilImageView))) let btnDownLoad = UIBarButtonItem.init(image: UIImage(named:"downLoad"), style: .done, target: self, action: #selector(EditorViewController.clickLoadBtn)) let btnShare = UIBarButtonItem.init(image: UIImage(named:"share"), style: .done, target: self, action: #selector(EditorViewController.clickShareBtn)) let btnEditor = UIBarButtonItem.init(image: UIImage(named:"editor"), style: .done, target: self, action: #selector(EditorViewController.clickEditorBtn)) self.navigationItem.rightBarButtonItems = [btnDownLoad,btnShare,btnEditor] scrollView = UIScrollView() scrollView.frame = CGRect(x: 0, y: 64, width: KScreenWidth, height: KScreenHeight-50-40-64) scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.delegate = self scrollView.minimumZoomScale = 1 scrollView.maximumZoomScale = 10 self.view.addSubview(scrollView!) drawBoardImageView = DrawBoard.init(frame:scrollView.bounds) drawBoardImageView.isUserInteractionEnabled = true // 对长图压缩处理 let scaleImage = UIImage.scaleImage(image: self.editorImage) drawBoardImageView.backgroundColor = UIColor(patternImage: scaleImage) drawBoardImageView.currentImage = scaleImage drawBoardImageView.masicImage = UIImage.trans(toMosaicImage: self.editorImage, blockLevel: 20) scrollView?.addSubview(drawBoardImageView) drawBoardImageView.beginDraw = {[weak self]() in self?.backBtn.isEnabled = true } drawBoardImageView.unableDraw = {[weak self]() in self?.backBtn.isEnabled = false } drawBoardImageView.reableDraw = {[weak self]() in self?.forwardBtn.isEnabled = false } // 默认的画笔 self.drawBoardImageView.strokeColor = UIColor(patternImage: UIImage(named: "clr_black")!) self.pencilImage.image = UIImage(named: "clr_black")! } //MARK: - 编辑,文本输入 func clickEditorBtn() { self.typeLable.text = "编辑模式" self.scrollView.isScrollEnabled = false self.pencilBtn.isSelected = false self.eraserBtn.isSelected = false self.drawBoardImageView.brush = InputBrush() } //MARK: - 分享 func clickShareBtn() { let win = UIApplication.shared.keyWindow let shareView = CLShareView() shareView.shareTitle = "" shareView.shareUrlStr = "" shareView.shareContent = "" shareView.shareImage = self.drawBoardImageView.takeImage() win?.addSubview(shareView) } //MARK: - 选择画笔颜色 func clickPencilImageView(){ self.view.addSubview(self.choosePencilView) self.view.bringSubview(toFront: self.settingView) self.choosePencilView.cl_y = self.settingView.cl_y UIView.animate(withDuration: 0.3) { self.choosePencilView.cl_y = self.settingView.cl_y-40 } } //MARK: - 选择画笔结束 func choosePencilViewDismiss() { UIView.animate(withDuration: 0.3, animations: { self.choosePencilView.cl_y = self.settingView.cl_y }) { (true) in self.choosePencilView.removeFromSuperview() } } //MARK: - 下载图片 func clickLoadBtn(){ let alertController = UIAlertController(title: "提示", message: "您确定要保存整个图片到相册吗?", preferredStyle: .alert) let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil) let okAction = UIAlertAction(title: "确定", style: .default, handler: { action in UIImageWriteToSavedPhotosAlbum(self.drawBoardImageView.takeImage(), self, #selector(EditorViewController.image(_:didFinishSavingWithError:contextInfo:)), nil) }) alertController.addAction(cancelAction) alertController.addAction(okAction) self.present(alertController, animated: true, completion: nil) } // 保存图片的结果 func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafeRawPointer) { if let err = error { UIAlertView(title: "错误", message: err.localizedDescription, delegate: nil, cancelButtonTitle: "确定").show() } else { UIAlertView(title: "提示", message: "保存成功", delegate: nil, cancelButtonTitle: "确定").show() } } //MARK: - 改变画笔大小 @IBAction func clickSlide(_ sender: Any) { // 先判断是不是文本,如果是文本,直接设置文本的颜色 if self.drawBoardImageView.brush?.classForKeyedArchiver == InputBrush.classForCoder() { drawBoardImageView.textFont = UIFont.systemFont(ofSize: CGFloat(self.slideView.value*50)) return } drawBoardImageView.strokeWidth = CGFloat(self.slideView.value*15) } //MARK: - 点击了画笔 @IBAction func clickPencilBtn(_ sender: Any) { self.pencilBtn?.isSelected = !(self.pencilBtn?.isSelected)! if (self.pencilBtn?.isSelected)! { self.scrollView.isScrollEnabled = false self.pencilBtn?.isSelected = true self.eraserBtn?.isSelected = false self.typeLable.text = "画笔模式" // 先判断是不是模糊矩形 if self.pencilImage.image == UIImage(named: "11") { drawBoardImageView?.brush = RectangleBrush() } else if self.pencilImage.image == UIImage(named: "12") { // 高斯模糊 drawBoardImageView?.brush = GaussianBlurBrush() } else { drawBoardImageView?.brush = PencilBrush() } } else { self.scrollView.isScrollEnabled = true self.pencilBtn?.isSelected = false drawBoardImageView?.brush = nil } } //MARK: - 点击了橡皮擦 @IBAction func clickEraserBtn(_ sender: Any) { self.eraserBtn?.isSelected = !(self.eraserBtn?.isSelected)! if (self.eraserBtn?.isSelected)! { self.typeLable.text = "橡皮擦模式" self.scrollView.isScrollEnabled = false self.pencilBtn?.isSelected = false self.eraserBtn?.isSelected = true drawBoardImageView?.brush = EraserBrush() } else { self.scrollView.isScrollEnabled = true self.pencilBtn?.isSelected = false drawBoardImageView?.brush = nil } } //MARK: - 撤回 @IBAction func clickBackBtn(_ sender: Any) { if self.drawBoardImageView.canBack() { self.backBtn.isEnabled = true self.forwardBtn.isEnabled = true drawBoardImageView?.undo() } else { self.backBtn.isEnabled = false } } //MARK: - 向前 @IBAction func clickForWardBtn(_ sender: Any) { if self.drawBoardImageView.canForward() { self.forwardBtn.isEnabled = true self.backBtn.isEnabled = true drawBoardImageView?.redo() } else { self.forwardBtn.isEnabled = false } } //MARK: - 还原 @IBAction func ClickReturnBtn(_ sender: Any) { let alertController = UIAlertController(title: "提示",message: "您确定要还原图片吗?", preferredStyle: .alert) let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil) let okAction = UIAlertAction(title: "确定", style: .default, handler: { action in self.drawBoardImageView?.retureAction() }) alertController.addAction(cancelAction) alertController.addAction(okAction) self.present(alertController, animated: true, completion: nil) } } extension EditorViewController:UIScrollViewDelegate{ func viewForZooming(in scrollView: UIScrollView) -> UIView? { return drawBoardImageView } func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { drawBoardImageView?.brush = nil self.pencilBtn?.isSelected = false self.eraserBtn?.isSelected = false self.scrollView.isScrollEnabled = true } }
apache-2.0
32dbbf384ea553c6a671f55f267e44db
37.628975
170
0.629254
4.509901
false
false
false
false
cuzv/ExtensionKit
Sources/Extension/Array+Extension.swift
1
3575
// // Array+Extension.swift // Copyright (c) 2015-2016 Red Rain (http://mochxiao.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 // MARK: - Array public extension Array { public mutating func exchange(lhs index: Int, rhs otherIndex: Int) { if count <= index || count <= otherIndex { fatalError("Index beyond boundary.") } if index >= otherIndex { fatalError("lhs must less than rhs.") } let firstItemData = self[index] let firstRange = Range(index ..< index + 1) let secondaryItemData = self[otherIndex] let secondaryRange = Range(otherIndex ..< otherIndex + 1) replaceSubrange(firstRange, with: [secondaryItemData]) replaceSubrange(secondaryRange, with: [firstItemData]) } public mutating func replace(at index: Int, with element: Element) { if count <= index { fatalError("Index beyond boundary.") } let range = Range(index ..< index + 1) replaceSubrange(range, with: [element]) } public mutating func replaceLast(_ element: Element) { replace(at: count - 1, with: element) } public mutating func replaceFirst(_ element: Element) { replace(at: 0, with: element) } public var prettyDebugDescription: String { var output: [String] = [] var index = 0 for item in self { output.append("\(index): \(item)") index += 1 } return output.joined(separator: "\n") } public var second: Element? { if count > 1 { return self[1] } return nil } public var third: Element? { if count > 2 { return self[2] } return nil } public var fourth: Element? { if count > 3 { return self[3] } return nil } public var fifthly: Element? { if count > 4 { return self[4] } return nil } public var sixth: Element? { if count > 5 { return self[5] } return nil } public var seventh: Element? { if count > 6 { return self[6] } return nil } public var eighth: Element? { if count > 7 { return self[7] } return nil } public var ninth: Element? { if count > 8 { return self[8] } return nil } public var tenth: Element? { if count > 9 { return self[9] } return nil } }
mit
c48e0d1d12ff6e89e46cd50cee2c731a
29.555556
81
0.606154
4.381127
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Stores/UserPersistentRepositoryUtility.swift
1
6838
import Foundation private enum UPRUConstants { static let promptKey = "onboarding_notifications_prompt_displayed" static let questionKey = "onboarding_question_selection" static let notificationPrimerAlertWasDisplayed = "NotificationPrimerAlertWasDisplayed" static let notificationsTabAccessCount = "NotificationsTabAccessCount" static let notificationPrimerInlineWasAcknowledged = "notificationPrimerInlineWasAcknowledged" static let secondNotificationsAlertCount = "secondNotificationsAlertCount" static let hasShownCustomAppIconUpgradeAlert = "custom-app-icon-upgrade-alert-shown" static let createButtonTooltipWasDisplayed = "CreateButtonTooltipWasDisplayed" static let createButtonTooltipDisplayCount = "CreateButtonTooltipDisplayCount" static let savedPostsPromoWasDisplayed = "SavedPostsV1PromoWasDisplayed" static let storiesIntroWasAcknowledged = "storiesIntroWasAcknowledged" static let currentAnnouncementsKey = "currentAnnouncements" static let currentAnnouncementsDateKey = "currentAnnouncementsDate" static let announcementsVersionDisplayedKey = "announcementsVersionDisplayed" } protocol UserPersistentRepositoryUtility: AnyObject { var onboardingNotificationsPromptDisplayed: Bool { get set } var onboardingQuestionSelected: OnboardingOption? { get set } var notificationPrimerAlertWasDisplayed: Bool { get set } } extension UserPersistentRepositoryUtility { var onboardingNotificationsPromptDisplayed: Bool { get { UserPersistentStoreFactory.instance().bool(forKey: UPRUConstants.promptKey) } set { UserPersistentStoreFactory.instance().set(newValue, forKey: UPRUConstants.promptKey) } } var onboardingQuestionSelected: OnboardingOption? { get { if let str = UserPersistentStoreFactory.instance().string(forKey: UPRUConstants.questionKey) { return OnboardingOption(rawValue: str) } return nil } set { UserPersistentStoreFactory.instance().set(newValue?.rawValue, forKey: UPRUConstants.questionKey) } } var notificationPrimerAlertWasDisplayed: Bool { get { UserPersistentStoreFactory.instance().bool(forKey: UPRUConstants.notificationPrimerAlertWasDisplayed) } set { UserPersistentStoreFactory.instance().set(newValue, forKey: UPRUConstants.notificationPrimerAlertWasDisplayed) } } var notificationsTabAccessCount: Int { get { UserPersistentStoreFactory.instance().integer(forKey: UPRUConstants.notificationsTabAccessCount) } set { UserPersistentStoreFactory.instance().set(newValue, forKey: UPRUConstants.notificationsTabAccessCount) } } var welcomeNotificationSeenKey: String { return "welcomeNotificationSeen" } var notificationPrimerInlineWasAcknowledged: Bool { get { UserPersistentStoreFactory.instance().bool(forKey: UPRUConstants.notificationPrimerInlineWasAcknowledged) } set { UserPersistentStoreFactory.instance().set(newValue, forKey: UPRUConstants.notificationPrimerInlineWasAcknowledged) } } var secondNotificationsAlertCount: Int { get { UserPersistentStoreFactory.instance().integer(forKey: UPRUConstants.secondNotificationsAlertCount) } set { UserPersistentStoreFactory.instance().set(newValue, forKey: UPRUConstants.secondNotificationsAlertCount) } } var hasShownCustomAppIconUpgradeAlert: Bool { get { UserPersistentStoreFactory.instance().bool(forKey: UPRUConstants.hasShownCustomAppIconUpgradeAlert) } set { UserPersistentStoreFactory.instance().set(newValue, forKey: UPRUConstants.hasShownCustomAppIconUpgradeAlert) } } var createButtonTooltipDisplayCount: Int { get { UserPersistentStoreFactory.instance().integer(forKey: UPRUConstants.createButtonTooltipDisplayCount) } set { UserPersistentStoreFactory.instance().set(newValue, forKey: UPRUConstants.createButtonTooltipDisplayCount) } } var createButtonTooltipWasDisplayed: Bool { get { UserPersistentStoreFactory.instance().bool(forKey: UPRUConstants.createButtonTooltipWasDisplayed) } set { UserPersistentStoreFactory.instance().set(newValue, forKey: UPRUConstants.createButtonTooltipWasDisplayed) } } var savedPostsPromoWasDisplayed: Bool { get { return UserPersistentStoreFactory.instance().bool(forKey: UPRUConstants.savedPostsPromoWasDisplayed) } set { UserPersistentStoreFactory.instance().set(newValue, forKey: UPRUConstants.savedPostsPromoWasDisplayed) } } var storiesIntroWasAcknowledged: Bool { get { return UserPersistentStoreFactory.instance().bool(forKey: UPRUConstants.storiesIntroWasAcknowledged) } set { UserPersistentStoreFactory.instance().set(newValue, forKey: UPRUConstants.storiesIntroWasAcknowledged) } } var announcements: [Announcement]? { get { guard let encodedAnnouncements = UserPersistentStoreFactory.instance().object(forKey: UPRUConstants.currentAnnouncementsKey) as? Data, let announcements = try? PropertyListDecoder().decode([Announcement].self, from: encodedAnnouncements) else { return nil } return announcements } set { guard let announcements = newValue, let encodedAnnouncements = try? PropertyListEncoder().encode(announcements) else { UserPersistentStoreFactory.instance().removeObject(forKey: UPRUConstants.currentAnnouncementsKey) UserPersistentStoreFactory.instance().removeObject(forKey: UPRUConstants.currentAnnouncementsDateKey) return } UserPersistentStoreFactory.instance().set(encodedAnnouncements, forKey: UPRUConstants.currentAnnouncementsKey) UserPersistentStoreFactory.instance().set(Date(), forKey: UPRUConstants.currentAnnouncementsDateKey) } } var announcementsDate: Date? { UserPersistentStoreFactory.instance().object(forKey: UPRUConstants.currentAnnouncementsDateKey) as? Date } var announcementsVersionDisplayed: String? { get { UserPersistentStoreFactory.instance().string(forKey: UPRUConstants.announcementsVersionDisplayedKey) } set { UserPersistentStoreFactory.instance().set(newValue, forKey: UPRUConstants.announcementsVersionDisplayedKey) } } }
gpl-2.0
0e63ec3619797c61c41baa2a32f96bbd
39.946108
146
0.709564
5.168556
false
false
false
false
danielallsopp/Charts
Source/Charts/Data/Implementations/Standard/BarLineScatterCandleBubbleChartDataSet.swift
15
1254
// // BarLineScatterCandleBubbleChartDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 26/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/Charts // import Foundation import CoreGraphics public class BarLineScatterCandleBubbleChartDataSet: ChartDataSet, IBarLineScatterCandleBubbleChartDataSet { // MARK: - Data functions and accessors // MARK: - Styling functions and accessors public var highlightColor = NSUIColor(red: 255.0/255.0, green: 187.0/255.0, blue: 115.0/255.0, alpha: 1.0) public var highlightLineWidth = CGFloat(0.5) public var highlightLineDashPhase = CGFloat(0.0) public var highlightLineDashLengths: [CGFloat]? // MARK: - NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! BarLineScatterCandleBubbleChartDataSet copy.highlightColor = highlightColor copy.highlightLineWidth = highlightLineWidth copy.highlightLineDashPhase = highlightLineDashPhase copy.highlightLineDashLengths = highlightLineDashLengths return copy } }
apache-2.0
381d0397acee48b5fd50876659c5c97c
30.35
110
0.723285
4.879377
false
false
false
false
narner/AudioKit
AudioKit/Common/Nodes/AKConnection.swift
1
8930
// // AKConnection.swift // AudioKit // // Created by David O'Neill on 8/12/17. // Copyright © 2017 AudioKit. All rights reserved. // /// A transitory used to pass connection information. open class AKInputConnection: NSObject { open var node: AKInput open var bus: Int public init(node: AKInput, bus: Int) { self.node = node self.bus = bus super.init() } open var avConnection: AVAudioConnectionPoint { return AVAudioConnectionPoint(node: self.node.inputNode, bus: bus) } } /// Simplify making connections from a node. @objc public protocol AKOutput: class { /// The output of this node can be connected to the inputNode of an AKInput. var outputNode: AVAudioNode { get } } extension AKOutput { /// Output connection points of outputNode. public var connectionPoints: [AVAudioConnectionPoint] { get { return outputNode.engine?.outputConnectionPoints(for: outputNode, outputBus: 0) ?? [] } set { AudioKit.connect(outputNode, to: newValue, fromBus: 0, format: AudioKit.format) } } /// Disconnects all outputNode's output connections. public func disconnectOutput() { AudioKit.engine.disconnectNodeOutput(outputNode) } /// Breaks connection from outputNode to an input's node if exists. /// - Parameter from: The node that output will disconnect from. public func disconnectOutput(from: AKInput) { connectionPoints = connectionPoints.filter({ $0.node != from.inputNode }) } /// Add a connection to an input using the input's nextInput for the bus. @discardableResult public func connect(to node: AKInput) -> AKInput { return connect(to: node, bus: node.nextInput.bus) } /// Add a connection to input.node on input.bus. /// - Parameter input: Contains node and input bus used to make a connection. @discardableResult public func connect(to input: AKInputConnection) -> AKInput { return connect(to: input.node, bus: input.bus) } /// Add a connection to node on a specific bus. @discardableResult public func connect(to node: AKInput, bus: Int) -> AKInput { connectionPoints.append(AVAudioConnectionPoint(node: node.inputNode, bus: bus)) return node } /// Add an output connection to each input in inputs. /// - Parameter nodes: Inputs that will be connected to. @discardableResult public func connect(to nodes: [AKInput]) -> [AKInput] { connectionPoints += nodes.map { $0.nextInput }.map { $0.avConnection } return nodes } /// Add an output connection to each connectionPoint in toInputs. /// - Parameter toInputs: Inputs that will be connected to. @discardableResult public func connect(toInputs: [AKInputConnection]) -> [AKInput] { connectionPoints += toInputs.map { $0.avConnection } return toInputs.map { $0.node } } /// Add an output connectionPoint. /// - Parameter connectionPoint: Input that will be connected to. public func connect(to connectionPoint: AVAudioConnectionPoint) { connectionPoints.append(connectionPoint) } /// Sets output connection, removes existing output connections. /// - Parameter node: Input that output will be connected to. @discardableResult public func setOutput(to node: AKInput) -> AKInput { return setOutput(to: node, bus: node.nextInput.bus, format: AudioKit.format) } /// Sets output connection, removes previously existing output connections. /// - Parameter node: Input that output will be connected to. /// - Parameter bus: The bus on the input that the output will connect to. /// - Parameter format: The format of the connection. @discardableResult public func setOutput(to node: AKInput, bus: Int, format: AVAudioFormat?) -> AKInput { AudioKit.connect(outputNode, to: node.inputNode, fromBus: 0, toBus: bus, format: format) return node } /// Sets output connections to an array of inputs, removes previously existing output connections. /// - Parameter nodes: Inputs that output will be connected to. /// - Parameter format: The format of the connections. @discardableResult public func setOutput(to nodes: [AKInput], format: AVAudioFormat?) -> [AKInput] { setOutput(to: nodes.map { $0.nextInput.avConnection }, format: format) return nodes } /// Sets output connections to an array of inputConnectios, removes previously existing output connections. /// - Parameter toInputs: Inputs that output will be connected to. @discardableResult public func setOutput(toInputs: [AKInputConnection]) -> [AKInput] { return setOutput(toInputs: toInputs, format: AudioKit.format) } /// Sets output connections to an array of inputConnectios, removes previously existing output connections. /// - Parameter toInputs: Inputs that output will be connected to. /// - Parameter format: The format of the connections. @discardableResult public func setOutput(toInputs: [AKInputConnection], format: AVAudioFormat?) -> [AKInput] { setOutput(to: toInputs.map { $0.avConnection }, format: format) return toInputs.map { $0.node } } /// Sets output connections to a single connectionPoint, removes previously existing output connections. /// - Parameter connectionPoint: Input that output will be connected to. public func setOutput(to connectionPoint: AVAudioConnectionPoint) { setOutput(to: connectionPoint, format: AudioKit.format) } /// Sets output connections to a single connectionPoint, removes previously existing output connections. /// - Parameter connectionPoint: Input that output will be connected to. /// - Parameter format: The format of the connections. public func setOutput(to connectionPoint: AVAudioConnectionPoint, format: AVAudioFormat?) { setOutput(to: [connectionPoint], format: format) } /// Sets output connections to an array of connectionPoints, removes previously existing output connections. /// - Parameter connectionPoints: Inputs that output will be connected to. /// - Parameter format: The format of the connections. public func setOutput(to connectionPoints: [AVAudioConnectionPoint], format: AVAudioFormat?) { AudioKit.connect(outputNode, to: connectionPoints, fromBus: 0, format: format) } } /// Manages connections to inputNode. public protocol AKInput: AKOutput { /// The node that an output's node can connect to. Default implementation will return outputNode. var inputNode: AVAudioNode { get } /// The input bus that should be used for an input connection. Default implementation is 0. Multi-input nodes /// should return an open bus. /// /// - Return: An inputConnection object conatining self and the input bus to use for an input connection. var nextInput: AKInputConnection { get } /// Disconnects all inputs func disconnectInput() /// Disconnects input on a bus. func disconnectInput(bus: Int) /// Creates an input connection object with a bus number. /// - Return: An inputConnection object conatining self and the input bus to use for an input connection. func input(_ bus: Int) -> AKInputConnection } extension AKInput { public var inputNode: AVAudioNode { return outputNode } public func disconnectInput() { AudioKit.engine.disconnectNodeInput(inputNode) } public func disconnectInput(bus: Int) { AudioKit.engine.disconnectNodeInput(inputNode, bus: bus ) } public var nextInput: AKInputConnection { if let mixer = inputNode as? AVAudioMixerNode { return input(mixer.nextAvailableInputBus) } return input(0) } public func input(_ bus: Int) -> AKInputConnection { return AKInputConnection(node: self, bus: bus) } } @objc extension AVAudioNode: AKInput { public var outputNode: AVAudioNode { return self } } // Set output connection(s) infix operator >>>: AdditionPrecedence @discardableResult public func >>>(left: AKOutput, right: AKInput) -> AKInput { return left.connect(to: right) } @discardableResult public func >>>(left: AKOutput, right: [AKInput]) -> [AKInput] { return left.connect(to: right) } @discardableResult public func >>>(left: [AKOutput], right: AKInput) -> AKInput { for node in left { node.connect(to: right) } return right } @discardableResult public func >>>(left: AKOutput, right: AKInputConnection) -> AKInput { return left.connect(to: right.node, bus: right.bus) } @discardableResult public func >>>(left: AKOutput, right: [AKInputConnection]) -> [AKInput] { return left.connect(toInputs: right) } public func >>>(left: AKOutput, right: AVAudioConnectionPoint) { return left.connect(to: right) }
mit
3c29475a0d0da886df7adfb56772db50
39.402715
115
0.692127
4.40069
false
false
false
false
tutao/tutanota
app-ios/tutanota/Sources/Alarms/AlarmModel.swift
1
4022
import Foundation typealias AlarmIterationCallback = (Int, Date) -> Void class AlarmModel { static func iterateRepeatingAlarm( eventStart: Date, eventEnd: Date, repeatRule: RepeatRule, now: Date, localTimeZone: TimeZone, scheduleAhead: Int, block:AlarmIterationCallback ) { var cal = Calendar.current let calendarUnit = Self.calendarUnit(for: repeatRule.frequency) let isAllDayEvent = Self.isAllDayEvent(startTime: eventStart, endTime: eventEnd) let calcEventStart = isAllDayEvent ? Self.allDayDateLocal(dateUTC: eventStart) : eventStart let endDate: Date? switch repeatRule.endCondition { case let .untilDate(valueDate): if isAllDayEvent { endDate = allDayDateLocal(dateUTC: valueDate) } else { endDate = valueDate } default: endDate = nil } cal.timeZone = isAllDayEvent ? localTimeZone : TimeZone(identifier: repeatRule.timeZone) ?? localTimeZone var ocurrences = 0 var ocurrencesAfterNow = 0 while ocurrencesAfterNow < scheduleAhead { if case let .count(n) = repeatRule.endCondition, ocurrences >= n { break } let ocurrenceDate = cal.date( byAdding: calendarUnit, value: repeatRule.interval * ocurrences, to: calcEventStart )! if let endDate = endDate, ocurrenceDate >= endDate { break } else if ocurrenceDate >= now { block(ocurrences, ocurrenceDate) ocurrencesAfterNow += 1 } ocurrences += 1 } } static func alarmTime(trigger: String, eventTime: Date) -> Date { let cal = Calendar.current switch trigger { case "5M": return cal.date(byAdding: .minute, value: -5, to: eventTime)! case "10M": return cal.date(byAdding: .minute, value: -10, to: eventTime)! case "30M": return cal.date(byAdding: .minute, value: -30, to: eventTime)! case "1H": return cal.date(byAdding: .hour, value: -1, to: eventTime)! case "1D": return cal.date(byAdding: .day, value: -1, to: eventTime)! case "2D": return cal.date(byAdding: .day, value: -2, to: eventTime)! case "3D": return cal.date(byAdding: .day, value: -3, to: eventTime)! case "1W": return cal.date(byAdding: .weekOfYear, value: -1, to: eventTime)! default: return cal.date(byAdding: .minute, value: -5, to: eventTime)! } } static func allDayDateUTC(date: Date) -> Date { let calendar = Calendar.current var localComponents = calendar.dateComponents([.year, .month, .day], from: date) let timeZone = TimeZone(identifier: "UTC")! localComponents.timeZone = timeZone return calendar.date(from: localComponents)! } static func allDayDateLocal(dateUTC: Date) -> Date { var calendar = Calendar.current let timeZone = TimeZone(identifier: "UTC")! calendar.timeZone = timeZone let components = calendar.dateComponents([.year, .month, .day], from: dateUTC) calendar.timeZone = TimeZone.current return calendar.date(from: components)! } private static func calendarUnit(for repeatPeriod: RepeatPeriod) -> Calendar.Component { switch (repeatPeriod) { case .daily: return .day case .weekly: return .weekOfYear case .monthly: return .month case .annually: return .year } } private static func isAllDayEvent(startTime: Date, endTime: Date) -> Bool { var calendar = Calendar.current calendar.timeZone = TimeZone(abbreviation: "UTC")! let startComponents = calendar.dateComponents([.hour, .minute, .second], from: startTime) let startsOnZero = startComponents.hour == 0 && startComponents.minute == 0 && startComponents.second == 0 let endComponents = calendar.dateComponents([.hour, .minute,.second], from: endTime) let endsOnZero = endComponents.hour == 0 && endComponents.minute == 0 && endComponents.second == 0 return startsOnZero && endsOnZero } }
gpl-3.0
fb7c849e9c15b3af2beb827065344a5b
31.176
109
0.654152
4.026026
false
false
false
false
drinkapoint/DrinkPoint-iOS
DrinkPoint/Pods/FacebookShare/Sources/Share/Content/OpenGraph/OpenGraphObject.swift
1
3932
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright 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 FBSDKShareKit @testable import FacebookCore /** An Open Graph Object for sharing. The property keys MUST have namespaces specified on them, such as `og:image`, and `og:type` is required. See https://developers.facebook.com/docs/sharing/opengraph/object-properties for other properties. You can specify nested namespaces inline to define complex properties. For example, the following code will generate a fitness.course object with a location: ``` let course: OpenGraphObject = [ "og:type": "fitness.course", "og:title": "Sample course", "fitness:metrics:location:latitude": "41.40338", "fitness:metrics:location:longitude": "2.17403", ] ``` */ public struct OpenGraphObject: Equatable { private var properties: [OpenGraphPropertyName : OpenGraphPropertyValue] /** Create a new `OpenGraphObject`. */ public init() { properties = [:] } } extension OpenGraphObject: OpenGraphPropertyContaining { /// Get the property names contained in this container. public var propertyNames: Set<OpenGraphPropertyName> { return Set(properties.keys) } public subscript(key: OpenGraphPropertyName) -> OpenGraphPropertyValue? { get { return properties[key] } set { properties[key] = newValue } } } extension OpenGraphObject: DictionaryLiteralConvertible { /** Convenience method to build a new object from a dictinary literal. - parameter elements: The elements of the dictionary literal to initialize from. - example: ``` let object: OpenGraphObject = [ "og:type": "foo", "og:title": "bar", .... ] ``` */ public init(dictionaryLiteral elements: (OpenGraphPropertyName, OpenGraphPropertyValue)...) { properties = [:] for (key, value) in elements { properties[key] = value } } } extension OpenGraphObject { internal var sdkGraphObjectRepresentation: FBSDKShareOpenGraphObject { let sdkObject = FBSDKShareOpenGraphObject() sdkObject.parseProperties(properties.keyValueMap { key, value in (key.rawValue, value.openGraphPropertyValue) }) return sdkObject } internal init(sdkGraphObject: FBSDKShareOpenGraphObject) { self.properties = [:] sdkGraphObject.enumerateKeysAndObjectsUsingBlock { (key: String?, value: AnyObject?, stop) in guard let key = key.map(OpenGraphPropertyName.init(rawValue:)), let value = value.map(OpenGraphPropertyValueConverter.valueFrom) else { return } self.properties[key] = value } } } /** Compare two `OpenGraphObject`s for equality. - parameter lhs: The first `OpenGraphObject` to compare. - parameter rhs: The second `OpenGraphObject` to compare. - returns: Whether or not the objects are equal. */ public func == (lhs: OpenGraphObject, rhs: OpenGraphObject) -> Bool { return false }
mit
711e69db927de7ea55e579d2ef482263
31.229508
119
0.723296
4.413019
false
false
false
false
TheSoftwareFactory/pushpenguins-ios
PushPenguins/ViewController.swift
1
4378
// // ViewController.swift // PushPenguins // // Created by Software Factory iOS on 3/24/17. // Copyright © 2017 Software Factory. All rights reserved. // test22 import UIKit class ViewController: UIViewController { @IBOutlet var leftBall: UIButton! @IBOutlet var rightBall: UIButton! @IBOutlet var centerBall: UIButton! var currBall : UIButton! var restartGame = false var winLabel : UILabel! override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if restartGame == false { let touch = touches.first let loc = touch?.location(in: self.view) var displacement = 0 switch ( (loc?.x)! / self.view.frame.width ) { //Sets ball to be one of the three options based on x touch location case 0..<1/3: currBall = leftBall case 1/3..<2/3: currBall = centerBall case 2/3...1.0: currBall = rightBall default: print(self.view.frame.width / (loc?.x)!) currBall = centerBall } if (loc?.y)! > self.view.frame.height / 2.0 { displacement = -70 if self.currBall.transform != CGAffineTransform(rotationAngle: 0) { //rotate penguin image if on opposite direction self.currBall.transform = self.currBall.transform.rotated(by: CGFloat(Double.pi)) } } else{ displacement = 70 if self.currBall.transform == CGAffineTransform(rotationAngle: 0) { //rotate penguin image if on opposite direction self.currBall.transform = self.currBall.transform.rotated(by: -CGFloat(Double.pi)) } } UIView.animate(withDuration: 0.05, animations: { self.currBall.center = CGPoint(x: self.currBall.center.x, y: self.currBall.center.y + CGFloat(displacement)) }, completion: nil) if currBall.frame.minY < 0 || currBall.frame.maxY > self.view.frame.height { winLabel = UILabel() winLabel.font = UIFont(name: "HelveticaNeue", size: 50) winLabel.textAlignment = .center winLabel.textColor = UIColor.white winLabel.frame = self.view.frame winLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6) self.view.addSubview(winLabel) restartGame = true currBall.alpha = 0 if currBall.frame.minY < 0 { winLabel.text = "Player 1 won!" } else{ winLabel.text = "Player 2 won!" } } } else{ restartGame = false leftBall.alpha = 1 leftBall.center = CGPoint(x: leftBall.center.x, y: self.view.center.y) leftBall.transform = CGAffineTransform() centerBall.alpha = 1 centerBall.center = CGPoint(x: centerBall.center.x, y: self.view.center.y) centerBall.transform = CGAffineTransform() rightBall.alpha = 1 rightBall.center = CGPoint(x: rightBall.center.x, y: self.view.center.y) rightBall.transform = CGAffineTransform() winLabel.removeFromSuperview() } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. currBall = centerBall } override func viewDidLayoutSubviews() { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } /* extension UIView { func startRotate() { let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z") rotation.fromValue = 0 rotation.toValue = NSNumber(value: M_PI * 2) rotation.duration = 2 rotation.isCumulative = true rotation.repeatCount = FLT_MAX self.layer.add(rotation, forKey: "rotationAnimation") } func stopRotate() { self.layer.removeAnimation(forKey: "rotationAnimation") } } */
mit
7197f021a1b70c2b77ee788d503132db
35.475
131
0.562257
4.646497
false
false
false
false
mluedke2/ultra-motivator
ios/UltraMotivator/UltraMotivator/ViewControllers/UltraMotivatorViewController.swift
2
2465
// // UltraMotivatorViewController.swift // UltraMotivator // // Created by Matt Luedke on 11/26/14. // Copyright (c) 2014 Matt Luedke. All rights reserved. // import UIKit class UltraMotivatorViewController: UIViewController { var keyboardDismisser : UITapGestureRecognizer! override func viewDidLoad() { super.viewDidLoad() keyboardDismisser = UITapGestureRecognizer(target: self, action:Selector("handleTap:")) view.addGestureRecognizer(keyboardDismisser) } func handleTap(recognizer: UITapGestureRecognizer) { for view in self.view.subviews as! [UIView] { if let textField = view as? UITextField { textField.resignFirstResponder() } } } func fillInFieldsReminder() { let alertController = UIAlertController(title: "Error", message: "More than 5 characters in all fields, please!", preferredStyle: .Alert) let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in } alertController.addAction(OKAction) self.presentViewController(alertController, animated: true) {} } func fieldMatchReminder() { let alertController = UIAlertController(title: "Error", message: "Textfield entries do not match!", preferredStyle: .Alert) let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in } alertController.addAction(OKAction) self.presentViewController(alertController, animated: true) {} } func showAlert(title: String, message: String, completion: (() -> Void)?) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in } alertController.addAction(OKAction) self.presentViewController(alertController, animated: true, completion: completion) } func showPasswordGenerationDialog(success: (() -> Void)) { let alertController = UIAlertController(title: "Generate Password?", message: "iOS can generate an absurdly secure password for you and store it in your keychain.", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in } alertController.addAction(cancelAction) let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in success() } alertController.addAction(OKAction) self.presentViewController(alertController, animated: true) {} } }
mit
098c0857ad8af5b287cfd3dd4ba98fc9
34.214286
192
0.705882
4.607477
false
false
false
false
RxSwiftCommunity/RxSwiftExt
Playground/RxSwiftExtPlayground.playground/Pages/UIViewPropertyAnimator.fractionComplete.xcplaygroundpage/Contents.swift
2
3050
/*: > # IMPORTANT: To use `RxSwiftExtPlayground.playground`, please: 1. Make sure you have [Carthage](https://github.com/Carthage/Carthage) installed 1. Fetch Carthage dependencies from shell: `carthage bootstrap --platform ios` 1. Build scheme `RxSwiftExtPlayground` scheme for a simulator target 1. Choose `View > Show Debug Area` */ //: [Previous](@previous) import RxSwift import RxCocoa import RxSwiftExt import PlaygroundSupport import UIKit /*: ## fractionComplete The `fractionComplete` binder provides a reactive way to bind to `UIViewPropertyAnimator.fractionComplete`. Please open the Assistant Editor (⌘⌥⏎) to see the Interactive Live View example. */ class FractionCompleteViewController: UIViewController { let disposeBag = DisposeBag() lazy var box: UIView = { let view = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100)) view.backgroundColor = .purple return view }() lazy var slider: UISlider = { let slider = UISlider(frame: .zero) slider.translatesAutoresizingMaskIntoConstraints = false return slider }() lazy var animator: UIViewPropertyAnimator = { UIViewPropertyAnimator(duration: 1, curve: .linear, animations: { let transform = CGAffineTransform(translationX: 100, y: 0) .concatenating(CGAffineTransform(rotationAngle: 360)) self.box.transform = transform }) }() lazy var fractionCompleteLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false return label }() override func viewDidLoad() { super.viewDidLoad() // construct the main view view.backgroundColor = .white setupViewHierarchy() setupConstraints() slider.rx.value.map(CGFloat.init) .bind(to: animator.rx.fractionComplete) .disposed(by: disposeBag) slider.rx.value .map { value in String(format: "fractionComplete: %.2lf", value) } .bind(to: fractionCompleteLabel.rx.text) .disposed(by: disposeBag) } private func setupViewHierarchy() { [box, slider, fractionCompleteLabel] .forEach(view.addSubview) } private func setupConstraints() { slider.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true slider.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true slider.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.8).isActive = true fractionCompleteLabel.topAnchor.constraint(equalTo: slider.bottomAnchor).isActive = true fractionCompleteLabel.centerXAnchor.constraint(equalTo: slider.centerXAnchor).isActive = true } } // Present the view controller in the Live View window PlaygroundPage.current.liveView = FractionCompleteViewController() //: [Next](@next)
mit
5a234459178eee580854cf2258a6b83f
31.042105
108
0.659658
5.006579
false
false
false
false
skyfe79/TIL
about.iOS/about.Concurrency/08_DispatchGroup/GCDGroups.playground/Contents.swift
1
2787
import UIKit import XCPlayground XCPlaygroundPage.currentPage.needsIndefiniteExecution = true //: # GCD Groups //: It's often useful to get notifications when a set of tasks has been completed—and that's precisely what GCD groups are for let workerQueue = dispatch_queue_create("com.raywenderlich.worker", DISPATCH_QUEUE_CONCURRENT) let numberArray = [(0,1), (2,3), (4,5), (6,7), (8,9)] //: ## Creating a group let slowSumGroup = dispatch_group_create() //: ## Dispatching to a group //: Very much like traditional `dispatch_async()` for inValue in numberArray { dispatch_group_async(slowSumGroup, workerQueue) { let result = slowSum(inValue) dispatch_group_async(slowSumGroup, dispatch_get_main_queue()) { print("Result = \(result)") } } } //: ## Notification of group completion //: Will be called only when everything in that dispatch group is completed dispatch_group_notify(slowSumGroup, dispatch_get_main_queue()) { print("SLOW SUM: Completed all operations") } //: ## Waiting for a group to complete //: __DANGER__ This is synchronous and can block //: This is a synchronous call on the current queue, so will block it. You cannot have anything in the group that wants to use the current queue otherwise you'll block. //17라인에서 main-queue를 얻어서 결과를 print하고 있다. //아래의 문장은 slowSumGroup이 끝나길 기다리는데 //내부에서 main-queue를 사용하므로 main-queue가 끝나길 기다리는 것과 같다 //그러나 main-queue는 끝나지 않고 계속해서 이벤트 등을 처리하므로 끝나는 큐가 아니다. //그래서 아래의 문장은 main-queue를 블럭 시킨다. DEAD-LOCK //17라인에서 print출력을 main-queue 없이 하면 블럭되지 않는다. //dispatch_group_wait(slowSumGroup, DISPATCH_TIME_FOREVER) //: ## Wrapping an existing Async API //: All well and good for new APIs, but there are lots of async APIs that don't have group parameters. What can you do with them? print("\n=== Wrapping an existing Async API ===\n") let wrappedGroup = dispatch_group_create() //: Wrap the original function func asyncSum(input: (Int, Int), completionQueue: dispatch_queue_t, group: dispatch_group_t, completion: (Int)->()) { dispatch_group_enter(group) asyncSum(input, completionQueue: completionQueue) { completion($0) dispatch_group_leave(group) } } for pair in numberArray { // TODO: use the new function here to calculate the sums of the array asyncSum(pair, completionQueue: workerQueue, group: wrappedGroup) { print("Result : \($0)") } } // TODO: Notify of completion dispatch_group_notify(wrappedGroup, dispatch_get_main_queue()) { print("Wrapped API: Completed all operations") }
mit
15f4f5cd13aef242f3425afe6cd27726
31.730769
168
0.710928
3.264706
false
false
false
false
GitTennis/SuccessFramework
Templates/_BusinessAppSwift_/_BusinessAppSwift_/Modules/Home/HomeCell.swift
2
2888
// // HomeCell.swift // _BusinessAppSwift_ // // Created by Gytenis Mikulenas on 12/11/16. // Copyright © 2016 Gytenis Mikulėnas // https://github.com/GitTennis/SuccessFramework // // 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. All rights reserved. // import UIKit protocol HomeCellDelegate: AnyObject { func didPressedWithImage(image: ImageEntityProtocol) } class HomeCell: UICollectionViewCell, GenericCellProtocol { //class var ReuseIdentifier: String { return "org.alamofire.identifier.\(type(of: self))" } class var reuseIdentifier: String { get { return "HomeCell" } } weak var delegate:HomeCellDelegate? @IBOutlet weak var titleLabel: NormalLabel! @IBOutlet weak var authorLabel: NormalLabel! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var activityIndicatorView: UIActivityIndicatorView! override func prepareForReuse() { super.prepareForReuse() imageView.af_cancelImageRequest() imageView.layer.removeAllAnimations() imageView.image = nil } func render<T>(withEntity: T) { // Store object _image = withEntity as! ImageEntityProtocol // Render UI self.titleLabel.text = _image.title //self.authorLabel.text = object.author if let imageUrl = _image.urlString { downloadImage(imageView: self.imageView, activityIndicator: self.activityIndicatorView, urlString: imageUrl) } } // MARK: IBActions @IBAction func cellPressed(_ sender: AnyObject) { self.delegate?.didPressedWithImage(image: self._image) } // MARK: // MARK: Internal // MARK: internal var _image:ImageEntityProtocol! }
mit
2920591b21c8414fd3729d7a249e9d91
32.172414
120
0.679487
4.78607
false
false
false
false
codergaolf/DouYuTV
DouYuTV/DouYuTV/Classes/Home/Controller/AmuseViewController.swift
1
1531
// // AmuseViewController.swift // DouYuTV // // Created by 高立发 on 2016/11/19. // Copyright © 2016年 GG. All rights reserved. // import UIKit private let kMenuViewH : CGFloat = 200 class AmuseViewController: BaseAnchorViewController { // MARK:- 懒加载属性 fileprivate lazy var amuseVM : AmuseViewModel = AmuseViewModel() fileprivate lazy var menuView : AmuseMenuView = { let menuView = AmuseMenuView.amuseMenuView() menuView.frame = CGRect(x: 0, y: -kMenuViewH, width: kScreenW, height: kMenuViewH) return menuView }() } // MARK:- 设置UI界面 extension AmuseViewController { override func setupUI() { super.setupUI() //将菜单View添加到控制器的veiw中 collectionView.addSubview(menuView) collectionView.contentInset = UIEdgeInsets(top: kMenuViewH, left: 0, bottom: 0, right: 0) } } // MARK:- 请求数据 extension AmuseViewController { override func loadData() { //1,给父类的viewModel进行赋值 baseVM = amuseVM //2,请求数据 self.amuseVM.loadAmuseData { //2.1,刷新表格 self.collectionView.reloadData() //2.2,调整数据 var tempGroups = self.amuseVM.anchorGroups tempGroups.removeFirst() self.menuView.groups = tempGroups //3,数据请求完成 self.loadDataFinished() } } }
mit
b7ac4b05307c23c9b1c62ce6539686c3
22.7
97
0.594233
4.647059
false
false
false
false
phimage/Erik
ErikAppTest/TestErikOSX/ViewController.swift
1
2302
// // ViewController.swift // TestErikOSX // // Created by phimage on 13/12/15. // Copyright © 2015 phimage. All rights reserved. // import Cocoa import Erik import Kanna import WebKit class ViewController: NSViewController { var browser: Erik! var webView: WKWebView! @IBOutlet weak var mainView: NSView! override func viewDidLoad() { super.viewDidLoad() webView = WKWebView(frame: self.mainView.bounds, configuration: WKWebViewConfiguration()) self.webView.frame = self.mainView.bounds self.webView.translatesAutoresizingMaskIntoConstraints = false self.mainView.addSubview(self.webView) self.mainView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-0-[view]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view":self.webView])) self.mainView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view":self.webView])) browser = Erik(webView: webView) browser.visit(url: googleURL) { object, error in if let e = error { print(String(describing: e)) } else if let doc = object { print(String(describing: doc)) } } } @IBAction func testAction(_ sender: AnyObject) { browser.currentContent { (d, r) in if let error = r { NSAlert(error: error).runModal() } else if let doc = d { if let input = doc.querySelector("input[name='q']") { print(input) input["value"] = "Erik swift" } if let form = doc.querySelector("form") as? Form { print(form) form.submit() } } } } @IBAction func reload(_ sender: AnyObject) { browser.visit(url: browser.url ?? googleURL) { (object, error) in if let e = error { print(String(describing: e)) } else if let doc = object { print(String(describing: doc)) } } } }
mit
62dd38b851cbdd4d429024b176f5f7c4
30.520548
195
0.55628
4.734568
false
false
false
false
apple/swift-tools-support-core
Sources/TSCUtility/Versioning.swift
1
2946
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2020 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 */ @_implementationOnly import TSCclibc // FIXME: deprecate 2/2021, remove once clients transitioned @available(*, deprecated, message: "moved to SwiftPM") public struct SwiftVersion { /// The version number. public var version: (major: Int, minor: Int, patch: Int) /// Whether or not this is a development version. public var isDevelopment: Bool /// Build information, as an unstructured string. public var buildIdentifier: String? /// The major component of the version number. public var major: Int { return version.major } /// The minor component of the version number. public var minor: Int { return version.minor } /// The patch component of the version number. public var patch: Int { return version.patch } /// The version as a readable string. public var displayString: String { var result = "\(major).\(minor).\(patch)" if isDevelopment { result += "-dev" } if let buildIdentifier = self.buildIdentifier { result += " (" + buildIdentifier + ")" } return result } /// The complete product version display string (including the name). public var completeDisplayString: String { var vendorPrefix = String(cString: SPM_VendorNameString()) if !vendorPrefix.isEmpty { vendorPrefix += " " } return vendorPrefix + "Swift Package Manager - Swift " + displayString } /// The list of version specific identifiers to search when attempting to /// load version specific package or version information, in order of /// preference. public var versionSpecificKeys: [String] { return [ "@swift-\(major).\(minor).\(patch)", "@swift-\(major).\(minor)", "@swift-\(major)", ] } } private func getBuildIdentifier() -> String? { let buildIdentifier = String(cString: SPM_BuildIdentifierString()) return buildIdentifier.isEmpty ? nil : buildIdentifier } // FIXME: deprecate 2/2021, remove once clients transitioned @available(*, deprecated, message: "moved to SwiftPM") public struct Versioning { /// The current version of the package manager. public static let currentVersion = SwiftVersion( version: (5, 4, 0), isDevelopment: true, buildIdentifier: getBuildIdentifier()) /// The list of version specific "keys" to search when attempting to load /// version specific package or version information, in order of preference. public static let currentVersionSpecificKeys = currentVersion.versionSpecificKeys }
apache-2.0
32ac082f4ee8f25eb9fdbc28a4a03599
34.071429
85
0.671758
4.76699
false
false
false
false
bryanrezende/Audiobook-Player
Audiobook Player/ListBooksViewController.swift
1
16911
// // ListBooksViewController.swift // Audiobook Player // // Created by Gianni Carlo on 7/7/16. // Copyright © 2016 Tortuga Power. All rights reserved. // import UIKit import MediaPlayer import Chameleon import MBProgressHUD class ListBooksViewController: UIViewController, UIGestureRecognizerDelegate { @IBOutlet weak var emptyListContainerView: UIView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var footerView: UIView! @IBOutlet weak var footerImageView: UIImageView! @IBOutlet weak var footerTitleLabel: UILabel! @IBOutlet weak var footerHeightConstraint: NSLayoutConstraint! @IBOutlet weak var footerPlayButton: UIButton! //keep in memory images to toggle play/pause let miniPlayImage = UIImage(named: "miniPlayButton") let miniPauseButton = UIImage(named: "miniPauseButton") //TableView's datasource var bookArray = [Book]() //keep in memory current Documents folder let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let refreshControl = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() //pull-down-to-refresh support self.refreshControl.attributedTitle = NSAttributedString(string: "Pull down to reload books") self.refreshControl.addTarget(self, action: #selector(loadFiles), for: .valueChanged) self.tableView.addSubview(self.refreshControl) //enables pop gesture on pushed controller self.navigationController!.interactivePopGestureRecognizer!.delegate = self //fixed tableview having strange offset self.edgesForExtendedLayout = UIRectEdge() //set colors self.navigationController?.navigationBar.barTintColor = UIColor.flatSkyBlue() self.footerView.backgroundColor = UIColor.flatSkyBlue() self.footerView.isHidden = true self.tableView.tableFooterView = UIView() //set external control listeners let skipForward = MPRemoteCommandCenter.shared().skipForwardCommand skipForward.isEnabled = true skipForward.addTarget(self, action: #selector(self.forwardPressed(_:))) skipForward.preferredIntervals = [30] let skipRewind = MPRemoteCommandCenter.shared().skipBackwardCommand skipRewind.isEnabled = true skipRewind.addTarget(self, action: #selector(self.rewindPressed(_:))) skipRewind.preferredIntervals = [30] let playCommand = MPRemoteCommandCenter.shared().playCommand playCommand.isEnabled = true playCommand.addTarget(self, action: #selector(self.didPressPlay(_:))) let pauseCommand = MPRemoteCommandCenter.shared().pauseCommand pauseCommand.isEnabled = true pauseCommand.addTarget(self, action: #selector(self.didPressPlay(_:))) //set tap handler to show detail on tap on footer view let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.didPressShowDetail(_:))) self.footerView.addGestureRecognizer(tapRecognizer) //register to audio-interruption notifications NotificationCenter.default.addObserver(self, selector: #selector(self.handleAudioInterruptions(_:)), name: NSNotification.Name.AVAudioSessionInterruption, object: nil) //register for appDelegate openUrl notifications NotificationCenter.default.addObserver(self, selector: #selector(self.loadFiles), name: Notification.Name.AudiobookPlayer.openURL, object: nil) //register for percentage change notifications NotificationCenter.default.addObserver(self, selector: #selector(self.updatePercentage(_:)), name: Notification.Name.AudiobookPlayer.updatePercentage, object: nil) //register for book end notifications NotificationCenter.default.addObserver(self, selector: #selector(self.bookEnd(_:)), name: Notification.Name.AudiobookPlayer.bookEnd, object: nil) //register for remote events UIApplication.shared.beginReceivingRemoteControlEvents() self.loadFiles() self.footerHeightConstraint.constant = 0 } //no longer need to deregister observers for iOS 9+! //https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11NotificationCenter deinit { //for iOS 8 NotificationCenter.default.removeObserver(self) UIApplication.shared.endReceivingRemoteControlEvents() } //Playback may be interrupted by calls. Handle pause @objc func handleAudioInterruptions(_ notification:Notification){ guard let audioPlayer = PlayerManager.sharedInstance.audioPlayer else { return } if audioPlayer.isPlaying { self.didPressPlay(self.footerPlayButton) } } /** * Load local files and process them (rename them if necessary) * Spaces in file names can cause side effects when trying to load the data */ @objc func loadFiles() { //load local files let loadingWheel = MBProgressHUD.showAdded(to: self.view, animated: true) loadingWheel?.labelText = "Loading Books" DataManager.loadBooks { (books) in self.bookArray = books self.refreshControl.endRefreshing() MBProgressHUD.hideAllHUDs(for: self.view, animated: true) //show/hide instructions view self.emptyListContainerView.isHidden = !self.bookArray.isEmpty self.tableView.reloadData() } } /** * Set play or pause image on button */ func setPlayImage(){ if PlayerManager.sharedInstance.isPlaying() { self.footerPlayButton.setImage(self.miniPauseButton, for: UIControlState()) }else{ self.footerPlayButton.setImage(self.miniPlayImage, for: UIControlState()) } } func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if(navigationController!.viewControllers.count > 1){ return true } return false } @IBAction func didPressReload(_ sender: UIBarButtonItem) { self.loadFiles() } @IBAction func didPressPlay(_ sender: UIButton) { PlayerManager.sharedInstance.playPressed() self.setPlayImage() } @objc func forwardPressed(_ sender: UIButton) { PlayerManager.sharedInstance.forwardPressed() } @objc func rewindPressed(_ sender: UIButton) { PlayerManager.sharedInstance.rewindPressed() } @IBAction func didPressShowDetail(_ sender: UIButton) { guard let indexPath = self.tableView.indexPathForSelectedRow else { return } self.tableView(self.tableView, didSelectRowAt: indexPath) } //percentage callback @objc func updatePercentage(_ notification:Notification) { guard let userInfo = notification.userInfo, let fileURL = userInfo["fileURL"] as? URL, let percentageString = userInfo["percentageString"] as? String else { return } guard let index = (self.bookArray.index { (book) -> Bool in return book.fileURL == fileURL }), let cell = self.tableView.cellForRow(at: IndexPath(row: index, section: 0)) as? BookCellView else { return } cell.completionLabel.text = percentageString } @objc func bookEnd(_ notification:Notification) { self.setPlayImage() } } extension ListBooksViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.bookArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "BookCellView", for: indexPath) as! BookCellView let book = self.bookArray[indexPath.row] cell.titleLabel.text = book.title cell.titleLabel.highlightedTextColor = UIColor.black cell.authorLabel.text = book.author //NOTE: we should have a default image for artwork cell.artworkImageView.image = book.artwork //load stored percentage value cell.completionLabel.text = UserDefaults.standard.string(forKey: self.bookArray[indexPath.row].identifier + "_percentage") ?? "0%" cell.completionLabel.textColor = UIColor.flatGreenColorDark() return cell } } extension ListBooksViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, canFocusRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let deleteAction = UITableViewRowAction(style: .default, title: "Delete") { (action, indexPath) in let alert = UIAlertController(title: "Confirmation", message: "Are you sure you would like to remove this audiobook?", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: { action in tableView.setEditing(false, animated: true) })) alert.addAction(UIAlertAction(title: "Yes", style: .destructive, handler: { action in let book = self.bookArray.remove(at: indexPath.row) try! FileManager.default.removeItem(at: book.fileURL) tableView.beginUpdates() tableView.deleteRows(at: [indexPath], with: .none) tableView.endUpdates() self.emptyListContainerView.isHidden = !self.bookArray.isEmpty })) alert.popoverPresentationController?.sourceView = self.view alert.popoverPresentationController?.sourceRect = CGRect(x: Double(self.view.bounds.size.width / 2.0), y: Double(self.view.bounds.size.height-45), width: 1.0, height: 1.0) self.present(alert, animated: true, completion: nil) } deleteAction.backgroundColor = UIColor.red return [deleteAction] } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 86 } func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { guard let index = tableView.indexPathForSelectedRow else { return indexPath } tableView.deselectRow(at: index, animated: true) return indexPath } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let book = self.bookArray[indexPath.row] let cell = tableView.cellForRow(at: indexPath) as! BookCellView let title = cell.titleLabel.text ?? book.fileURL.lastPathComponent let author = cell.authorLabel.text ?? "Unknown Author" let storyboard = UIStoryboard(name: "Main", bundle: nil) let playerVC = storyboard.instantiateViewController(withIdentifier: "PlayerViewController") as! PlayerViewController playerVC.currentBook = book //show the current player self.presentModal(playerVC, animated: true) { self.footerView.isHidden = false self.footerTitleLabel.text = title + " - " + author self.footerImageView.image = cell.artworkImageView.image self.footerHeightConstraint.constant = 55 self.setPlayImage() } } } extension ListBooksViewController:UIDocumentMenuDelegate { @IBAction func didPressImportOptions(_ sender: UIBarButtonItem) { let sheet = UIAlertController(title: "Import Books", message: nil, preferredStyle: .actionSheet) let cancelButton = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) let localButton = UIAlertAction(title: "From Local Apps", style: .default) { (action) in let providerList = UIDocumentMenuViewController(documentTypes: ["public.audio"], in: .import) providerList.delegate = self; providerList.popoverPresentationController?.sourceView = self.view providerList.popoverPresentationController?.sourceRect = CGRect(x: Double(self.view.bounds.size.width / 2.0), y: Double(self.view.bounds.size.height-45), width: 1.0, height: 1.0) self.present(providerList, animated: true, completion: nil) } let airdropButton = UIAlertAction(title: "AirDrop", style: .default) { (action) in self.showAlert("AirDrop", message: "Make sure AirDrop is enabled.\n\nOnce you transfer the file to your device via AirDrop, choose 'BookPlayer' from the app list that will appear", style: .alert) } sheet.addAction(localButton) sheet.addAction(airdropButton) sheet.addAction(cancelButton) sheet.popoverPresentationController?.sourceView = self.view sheet.popoverPresentationController?.sourceRect = CGRect(x: Double(self.view.bounds.size.width / 2.0), y: Double(self.view.bounds.size.height-45), width: 1.0, height: 1.0) self.present(sheet, animated: true, completion: nil) } func documentMenu(_ documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) { //show document picker documentPicker.delegate = self; documentPicker.popoverPresentationController?.sourceView = self.view documentPicker.popoverPresentationController?.sourceRect = CGRect(x: Double(self.view.bounds.size.width / 2.0), y: Double(self.view.bounds.size.height-45), width: 1.0, height: 1.0) self.present(documentPicker, animated: true, completion: nil) } } extension ListBooksViewController:UIDocumentPickerDelegate { func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) { //Documentation states that the file might not be imported due to being accessed from somewhere else do { try FileManager.default.attributesOfItem(atPath: url.path) }catch{ self.showAlert("Error", message: "File import fail, try again later", style: .alert) return } let trueName = url.lastPathComponent var finalPath = self.documentsPath+"/"+(trueName) if trueName.contains(" ") { finalPath = finalPath.replacingOccurrences(of: " ", with: "_") } let fileURL = URL(fileURLWithPath: finalPath.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!) do { try FileManager.default.moveItem(at: url, to: fileURL) }catch{ self.showAlert("Error", message: "File import fail, try again later", style: .alert) return } self.loadFiles() } } extension ListBooksViewController { override func remoteControlReceived(with event: UIEvent?) { guard let event = event else { return } //TODO: after decoupling AVAudioPlayer from the PlayerViewController switch event.subtype { case .remoteControlTogglePlayPause: print("toggle play/pause") case .remoteControlBeginSeekingBackward: print("seeking backward") case .remoteControlEndSeekingBackward: print("end seeking backward") case .remoteControlBeginSeekingForward: print("seeking forward") case .remoteControlEndSeekingForward: print("end seeking forward") case .remoteControlPause: print("control pause") case .remoteControlPlay: print("control play") case .remoteControlStop: print("stop") case .remoteControlNextTrack: print("next track") case .remoteControlPreviousTrack: print("previous track") default: print(event.description) } } } class BookCellView: UITableViewCell { @IBOutlet weak var artworkImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var authorLabel: UILabel! @IBOutlet weak var completionLabel: UILabel! }
gpl-3.0
42399b5ecbdfe6434918116bf7dc3dc2
40.043689
207
0.658013
5.235294
false
false
false
false
nathawes/swift
test/Syntax/round_trip_parse_gen.swift
2
11190
// RUN: rm -rf %t // RUN: %swift-syntax-test -input-source-filename %s -parse-gen > %t // RUN: diff -u %s %t // RUN: %swift-syntax-test -input-source-filename %s -parse-gen -print-node-kind > %t.withkinds // RUN: diff -u %S/Outputs/round_trip_parse_gen.swift.withkinds %t.withkinds // RUN: %swift-syntax-test -input-source-filename %s -eof > %t // RUN: diff -u %s %t // RUN: %swift-syntax-test -serialize-raw-tree -input-source-filename %s > %t.dump // RUN: %swift-syntax-test -deserialize-raw-tree -input-source-filename %t.dump -output-filename %t // RUN: diff -u %s %t import ABC import A.B.C @objc import A.B @objc import typealias A.B import struct A.B #warning("test warning") #error("test error") #if Blah class C { func bar(_ a: Int) {} func bar1(_ a: Float) -> Float { return -0.6 + 0.1 - 0.3 } func bar2(a: Int, b: Int, c:Int) -> Int { return 1 } func bar3(a: Int) -> Int { return 1 } func bar4(_ a: Int) -> Int { return 1 } func foo() { var a = /*comment*/"ab\(x)c"/*comment*/ var b = /*comment*/+2/*comment*/ bar(1) bar(+10) bar(-10) bar1(-1.1) bar1(1.1) var f = /*comments*/+0.1/*comments*/ foo() _ = "🙂🤗🤩🤔🤨" } func foo1() { _ = bar2(a:1, b:2, c:2) _ = bar2(a:1 + 1, b:2 * 2 + 2, c:2 + 2) _ = bar2(a : bar2(a: 1, b: 2, c: 3), b: 2, c: 3) _ = bar3(a : bar3(a: bar3(a: 1))) _ = bar4(bar4(bar4(1))) _ = [:] _ = [] _ = [1, 2, 3, 4] _ = [1:1, 2:2, 3:3, 4:4] _ = [bar3(a:1), bar3(a:1), bar3(a:1), bar3(a:1)] _ = ["a": bar3(a:1), "b": bar3(a:1), "c": bar3(a:1), "d": bar3(a:1)] foo(nil, nil, nil) _ = type(of: a).self _ = a.`self` _ = A -> B.C<Int> _ = [(A) throws -> B]() } func boolAnd() -> Bool { return true && false } func boolOr() -> Bool { return true || false } func foo2() { _ = true ? 1 : 0 _ = (true ? 1 : 0) ? (true ? 1 : 0) : (true ? 1 : 0) _ = (1, 2) _ = (first: 1, second: 2) _ = (1) _ = (first: 1) if !true { return } } func foo3() { _ = [Any]() _ = a.a.a _ = a.b _ = 1.a (1 + 1).a.b.foo _ = a as Bool || a as! Bool || a as? Bool _ = a is Bool _ = self _ = Self } func superExpr() { _ = super.foo super.bar() super[12] = 1 super.init() } func implictMember() { _ = .foo _ = .foo(x: 12) _ = .foo() { 12 } _ = .foo[12] _ = .foo.bar } init() {} @objc private init(a: Int) init!(a: Int) {} init?(a: Int) {} public init(a: Int) throws {} init(a: Int..., b: Double...) {} @objc deinit {} private deinit {} internal subscript(x: Int) -> Int { get {} set {} } subscript() -> Int { return 1 } subscript(x: Int..., y y: String...) -> Int { return 1 } var x: Int { address { fatalError() } unsafeMutableAddress { fatalError() } } } protocol PP { associatedtype A associatedtype B: Sequence associatedtype C = Int associatedtype D: Sequence = [Int] associatedtype E: Sequence = [[Int]] where A.Element : Sequence private associatedtype F @objc associatedtype G } #endif #if blah typealias A = Any #elseif blahblah typealias B = (Array<Array<Any>>.Element, x: Int) #else typealias C = [Int] #endif typealias D = [Int: String] typealias E = Int?.Protocol typealias F = [Int]!.Type typealias G = (a x: Int, _ y: Int ... = 1) throw -> () -> () typealias H = () rethrows -> () typealias I = (A & B<C>) -> C & D typealias J = inout @autoclosure () -> Int typealias K = (@invalidAttr Int, inout Int, __shared Int, __owned Int) -> () @objc private typealias T<a,b> = Int @objc private typealias T<a,b> class Foo { let bar: Int } class Bar: Foo { var foo: Int = 42 } class C<A, B> where A: Foo, B == Bar {} @available(*, unavailable) private class C {} struct foo { struct foo { struct foo { func foo() { } } } struct foo {} } struct foo { @available(*, unavailable) struct foo {} public class foo { @available(*, unavailable) @objc(fooObjc) private static func foo() {} @objc(fooObjcBar:baz:) private static func foo(bar: String, baz: Int) } } struct S<A, B, C, @objc D> where A:B, B==C, A : C, B.C == D.A, A.B: C.D {} private struct S<A, B>: Base where A: B { private struct S: A, B {} } protocol P: class {} func foo(_ _: Int, a b: Int = 3 + 2, _ c: Int = 2, d _: Int = true ? 2: 3, @objc e: X = true, f: inout Int, g: Int..., h: Bool...) throws -> [Int: String] {} func foo(_ a: Int) throws -> Int {} func foo( a: Int) rethrows -> Int {} struct C { @objc @available(*, unavailable) private static override func foo<a, b, c>(a b: Int, c: Int) throws -> [Int] where a==p1, b:p2 { ddd } func rootView() -> Label {} static func ==() -> bool {} static func !=<a, b, c>() -> bool {} } @objc private protocol foo : bar where A==B {} protocol foo { func foo() } private protocol foo{} @objc public protocol foo where A:B {} #if blah func tryfoo() { try foo() try! foo() try? foo() try! foo().bar().foo().bar() } #else func closure() { _ = {[weak a, unowned(safe) self, b = 3, unowned(unsafe) c = foo().bar] in } _ = {[] in } _ = { [] a, b, _ -> Int in return 2 } _ = { [] (a: Int, b: Int, _: Int) -> Int in return 2 } _ = { [] a, b, _ throws -> Int in return 2 } _ = { [] (a: Int, _ b: Int) throws -> Int in return 2 } _ = { a, b in } _ = { (a, b) in } _ = {} _ = { s1, s2 in s1 > s2 } _ = { $0 > $1 } } #endif func postfix() { foo() foo() {} foo {} foo { } arg2: {} foo {} foo.bar() foo.bar() {} foo.bar() {} arg2: {} in: {} foo.bar {} foo[] foo[1] foo[] {} foo[1] {} foo[1] {} arg2: {} foo[1][2,x:3] foo?++.bar!(baz).self foo().0 foo<Int>.bar foo<Int>() foo.bar<Int>() foo(x:y:)() foo(x:)<Int> { } _ = .foo(x:y:) _ = x.foo(x:y:) _ = foo(&d) _ = <#Placeholder#> + <#T##(Int) -> Int#> } #if blah #else #endif class C { var a: Int { @objc mutating set(value) {} mutating get { return 3 } @objc didSet {} willSet(newValue){ } } var a : Int { return 3 } } protocol P { var a: Int { get set } var a: Int {} } private final class D { @objc static private var a: Int = 3 { return 3 }, b: Int, c = 4, d : Int { get {} get {}}, (a, b): (Int, Int) let (a, b) = (1,2), _ = 4 {} func patternTests() { for let (x, _) in foo {} for var x: Int in foo {} } } do { switch foo { case let a: break case let a as Int: break case let (a, b): break case (let a, var b): break case is Int: break case let .bar(x): break case MyEnum.foo: break case let a as Int: break case let a?: break } } func statementTests() { do { } catch (var x, let y) { } catch where false { } catch let e where e.foo == bar { } catch .a(let a), .b(let b) where b == "" { } catch { } repeat { } while true LABEL: repeat { } while false while true { } LABEL: while true { } LABEL: do {} LABEL: switch foo { case 1: fallthrough case 2: break LABEL case 3: break } for a in b { defer { () } if c { throw MyError() continue } else { continue LABEL } } if foo, let a = foo, let b: Int = foo, var c = foo, case (let v, _) = foo, case (let v, _): (Int, Int) = foo { } else if foo { } else { } guard let a = b else {} guard let self = self else {} for var i in foo where i.foo {} for case is Int in foo {} switch Foo { case n1: break case n2, n3l: break #if FOO case let (x, y) where !x, n3l where false: break #elseif BAR case let y: break #else case .foo(let x): break #endif default: break } switch foo { case 1, 2, 3: break default: break } switch foo { case 1, 2, 3: break @unknown default: break } switch foo { case 1, 2, 3: break @unknown case _: break } switch foo { case 1, 2, 3: break // This is rejected in Sema, but should be preserved by Syntax. @unknown case (42, -42) where 1 == 2: break @garbage case 0: break @garbage(foobar) case -1: break } } // MARK: - ExtensionDecl extension ext { var s: Int { return 42 } } @available(*, unavailable) fileprivate extension ext {} extension ext : extProtocol {} extension ext where A == Int, B: Numeric {} extension ext.a.b {} func foo() { var a = "abc \(foo()) def \(a + b + "a \(3)") gh \(bar, default: 1)" var a = """ abc \( foo() + bar() ) de \(3 + 3 + "abc \(foo()) def") fg \(bar, default: 1) """ } func keypath() { _ = \a.?.b _ = \a.b.c _ = \a.b[1] _ = \.a.b _ = \Array<Int>.[] _ = #keyPath(a.b.c) } func objcSelector() { _ = [ #selector(getter: Foo.bar), #selector(setter: Foo.Bar.baz), #selector(Foo.method(x:y:)), #selector(foo[42].bar(x)), #selector({ [x] in return nil }) ] } func objectLiterals() { #fileLiteral(a) #colorLiteral(a, b) #imageLiteral(a, b, c) #column #file #function #dsohandle } enum E1 : String { case foo = 1 case bar = "test", baz(x: Int, String) = 12 indirect case qux(E1) indirect private enum E2<T>: String where T: SomeProtocol { case foo, bar, baz } } precedencegroup FooPrecedence { higherThan: DefaultPrecedence, UnknownPrecedence assignment: false associativity: none } precedencegroup BarPrecedence {} precedencegroup BazPrecedence { associativity: left assignment: true associativity: right lowerThan: DefaultPrecedence } infix operator<++>:FooPrecedence prefix operator..<< postfix operator <- func higherOrderFunc() { let x = [1,2,3] x.reduce(0, +) } if #available(iOS 11, macOS 10.11.2, *) {} @_specialize(where T == Int) @_specialize(exported: true, where T == String) public func specializedGenericFunc<T>(_ t: T) -> T { return t } protocol Q { func g() var x: String { get } func f(x:Int, y:Int) -> Int #if FOO_BAR var conditionalVar: String #endif } struct S : Q, Equatable { @_implements(Q, f(x:y:)) func h(x:Int, y:Int) -> Int { return 6 } @_implements(Equatable, ==(_:_:)) public static func isEqual(_ lhs: S, _ rhs: S) -> Bool { return false } @_implements(P, x) var y: String @_implements(P, g()) func h() { _ = \.self } @available(*, deprecated: 1.2, message: "ABC") fileprivate(set) var x: String } struct ReadModify { var st0 = ("a", "b") var rm0: (String, String) { _read { yield (("a", "b")) } _modify { yield &st0 } } var rm1: (String, String) { _read { yield (st0) } } } @custom @_alignment(16) public struct float3 { public var x, y, z: Float } #sourceLocation(file: "otherFile.swift", line: 5) func foo() {} #sourceLocation() "abc \( } ) def" #assert(true) #assert(false) #assert(true, "hello world") public func anyFoo() -> some Foo {} public func qoo() -> some O & O2 {} func zlop() -> some C & AnyObject & P {} @custom(a, b,c) func foo() {} @custom_attr @custom(A: a, B: b, C:c) func foo() {} "abc" "abc \(foo)" #"abc"# #"abc \#(foo)"# ##"abc"## ##"abc \##(foo)"##
apache-2.0
90279c43263e3dd08ea774b0eb2e5cf2
17.687291
105
0.534318
2.830547
false
false
false
false
arkdan/ARKExtensions
Extensions-macOS/String+.swift
1
1809
// // String+.swift // ARKExtensions // // Created by mac on 1/3/18. // Copyright © 2018 arkdan. All rights reserved. // import Foundation extension String { public var nsRange: NSRange { return NSRange(location: 0, length: count) } public func index(at offset: Int) -> Index { return self.index(startIndex, offsetBy: offset) } public func substring(from: Int) -> String { return String(self[from...]) } public func substring(to: Int) -> String { return String(self[..<to]) } public func substring(with range: Range<Int>) -> String { return String(self[range]) } public subscript(from: CountablePartialRangeFrom<Int>) -> Substring { let fromIndex = index(at: from.lowerBound) return self[fromIndex...] } public subscript(to: PartialRangeUpTo<Int>) -> Substring { let toIndex = index(at: to.upperBound) return self[..<toIndex] } public subscript(range: Range<Int>) -> Substring { let startIndex = index(at: range.lowerBound) let endIndex = index(at: range.upperBound) return self[startIndex..<endIndex] } } extension String { public func isValidEmail() -> Bool { let pattern = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" return isPassingRegex(pattern) } public func isPassingRegex(_ pattern: String, options: NSRegularExpression.Options = []) -> Bool { guard let regex = try? NSRegularExpression(pattern: pattern, options: options) else { return false } return regex.firstMatch(in: self, options: [], range: self.nsRange) != nil } } extension String { public func trimming(_ string: String) -> String { return replacingOccurrences(of: string, with: "") } }
mit
386dd96ffc400858283cd5b4e7621f12
25.202899
108
0.620022
4.072072
false
false
false
false
jengelsma/ios-bootcamp-codeexamples
Lecture11/TopTracksDemo/TopTracksDemo/AppDelegate.swift
4
2765
// // AppDelegate.swift // TopTracksDemo // // Created by Jonathan Engelsma on 5/26/15. // Copyright (c) 2015 Jonathan Engelsma. All rights reserved. // import UIKit @UIApplicationMain @objc class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var count: Int? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. self.count = 0 return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func incrementNetworkActivity() { self.count!++ UIApplication.sharedApplication().networkActivityIndicatorVisible = true } func decrementNetworkActivity() { if self.count! > 0 { self.count!-- } if self.count! == 0 { UIApplication.sharedApplication().networkActivityIndicatorVisible = false } } func resetNetworkActivity() { self.count! = 0 UIApplication.sharedApplication().networkActivityIndicatorVisible = false } }
gpl-2.0
3a86baa658b3d7fe0c03a2e7f3968d1c
38.5
285
0.718264
5.597166
false
false
false
false
AynurGaliev/Books-Shop
Sources/App/Controllers/AuthController.swift
1
1884
import Vapor import HTTP import Fluent import Foundation import Routing import HTTPRouting final class AuthController: BaseController { override class var resource: String { return "auth" } override func addRoutes(routeGroup: Route) { let group = routeGroup.grouped(type(of: self).resource) group.post("signin", handler: self.signin) group.post("login", handler: self.login) } func signin(request: Request) throws -> ResponseRepresentable { guard let password = request.data["password"]?.string else { throw Abort.badRequest } guard let login = request.data["login"]?.string else { throw Abort.badRequest } guard var credential = try Credential.query() .filter("password", password) .filter("login", login) .first() else { throw Abort.badRequest } try Credential.renewToken(credential: &credential) try credential.save() return credential } func login(request: Request) throws -> ResponseRepresentable { guard let password = request.data["password"]?.string else { throw Abort.badRequest } guard let login = request.data["login"]?.string else { throw Abort.badRequest } let existingCredential = try Credential.query().filter("password", password).filter("login", login).first() guard existingCredential == nil else { throw Abort.badRequest } var credential = Credential(password: password, login: login) var user = User() try user.save() credential.userId = user.id try Credential.renewToken(credential: &credential) try credential.save() return credential } }
mit
e321358a0cf5ff9f6de1b66e000f109c
34.54717
115
0.598195
5.322034
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Repeater.swift
1
3233
// // Repeater.swift // lottie-swift // // Created by Brandon Withrow on 1/8/19. // import Foundation /// An item that define an ellipse shape final class Repeater: ShapeItem { /// The number of copies to repeat let copies: KeyframeGroup<Vector1D> /// The offset of each copy let offset: KeyframeGroup<Vector1D> /// Start Opacity let startOpacity: KeyframeGroup<Vector1D> /// End opacity let endOpacity: KeyframeGroup<Vector1D> /// The rotation let rotation: KeyframeGroup<Vector1D> /// Anchor Point let anchorPoint: KeyframeGroup<Vector3D> /// Position let position: KeyframeGroup<Vector3D> /// Scale let scale: KeyframeGroup<Vector3D> private enum CodingKeys : String, CodingKey { case copies = "c" case offset = "o" case transform = "tr" } private enum TransformKeys : String, CodingKey { case rotation = "r" case startOpacity = "so" case endOpacity = "eo" case anchorPoint = "a" case position = "p" case scale = "s" } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: Repeater.CodingKeys.self) self.copies = try container.decodeIfPresent(KeyframeGroup<Vector1D>.self, forKey: .copies) ?? KeyframeGroup(Vector1D(0)) self.offset = try container.decodeIfPresent(KeyframeGroup<Vector1D>.self, forKey: .offset) ?? KeyframeGroup(Vector1D(0)) let transformContainer = try container.nestedContainer(keyedBy: TransformKeys.self, forKey: .transform) self.startOpacity = try transformContainer.decodeIfPresent(KeyframeGroup<Vector1D>.self, forKey: .startOpacity) ?? KeyframeGroup(Vector1D(100)) self.endOpacity = try transformContainer.decodeIfPresent(KeyframeGroup<Vector1D>.self, forKey: .endOpacity) ?? KeyframeGroup(Vector1D(100)) self.rotation = try transformContainer.decodeIfPresent(KeyframeGroup<Vector1D>.self, forKey: .rotation) ?? KeyframeGroup(Vector1D(0)) self.position = try transformContainer.decodeIfPresent(KeyframeGroup<Vector3D>.self, forKey: .position) ?? KeyframeGroup(Vector3D(x: Double(0), y: 0, z: 0)) self.anchorPoint = try transformContainer.decodeIfPresent(KeyframeGroup<Vector3D>.self, forKey: .anchorPoint) ?? KeyframeGroup(Vector3D(x: Double(0), y: 0, z: 0)) self.scale = try transformContainer.decodeIfPresent(KeyframeGroup<Vector3D>.self, forKey: .scale) ?? KeyframeGroup(Vector3D(x: Double(100), y: 100, z: 100)) try super.init(from: decoder) } override func encode(to encoder: Encoder) throws { try super.encode(to: encoder) var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(copies, forKey: .copies) try container.encode(offset, forKey: .offset) var transformContainer = container.nestedContainer(keyedBy: TransformKeys.self, forKey: .transform) try transformContainer.encode(startOpacity, forKey: .startOpacity) try transformContainer.encode(endOpacity, forKey: .endOpacity) try transformContainer.encode(rotation, forKey: .rotation) try transformContainer.encode(position, forKey: .position) try transformContainer.encode(anchorPoint, forKey: .anchorPoint) try transformContainer.encode(scale, forKey: .scale) } }
mit
44d852d1f172e3eb5653e20d9f19ec57
39.4125
166
0.731209
3.918788
false
false
false
false
eofster/Telephone
UseCases/SimpleCall.swift
1
1186
// // SimpleCall.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2021 64 Characters // // Telephone 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. // // Telephone 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 Foundation public final class SimpleCall: NSObject, Call { public let account: Account public let remote: URI public let date: Date public let duration: Int public let isIncoming: Bool public let isMissed: Bool public init(account: Account, remote: URI, date: Date, duration: Int, isIncoming: Bool, isMissed: Bool) { self.account = account self.remote = remote self.date = date self.duration = duration self.isIncoming = isIncoming self.isMissed = isMissed } }
gpl-3.0
52856261b3b915498b643e7847b1cb1b
31
109
0.699324
4.274368
false
false
false
false
Lagovas/themis
docs/examples/Themis-server/swift/SwiftThemisServerExample/SwiftThemisServerExample/SSessionClient.swift
2
10945
// // SSessionClient.swift // SwiftThemisServerExample // // Created by Anastasi Voitova on 19.04.16. // Copyright © 2016 CossackLabs. All rights reserved. // import Foundation final class Transport: TSSessionTransportInterface { fileprivate var serverId: String? fileprivate var serverPublicKeyData: Data? func setupKeys(_ serverId: String, serverPublicKey: String) { self.serverId = serverId self.serverPublicKeyData = Data(base64Encoded: serverPublicKey, options: .ignoreUnknownCharacters) } override func publicKey(for binaryId: Data!) throws -> Data { let error: Error = NSError(domain: "com.themisserver.example", code: -1, userInfo: nil) let stringFromData = String(data: binaryId, encoding: String.Encoding.utf8) if stringFromData == nil { throw error } if stringFromData == serverId { guard let resultData: Data = serverPublicKeyData else { throw error } return resultData } // it should be nil, but swift ¯\_(ツ)_/¯ return Data() } } final class SSessionClient { var transport: Transport? var session: TSSession? // Read how Themis Server works: // https://github.com/cossacklabs/themis/wiki/Using-Themis-Server // you may want to re-generate all keys // user id and server public key are copied from server setup // https://themis.cossacklabs.com/interactive-simulator/setup/ let kClientId: String = "hAxNatMbDDbNUge" let kServerId: String = "ongViVgndBkyYlX" let kServerPublicKey: String = "VUVDMgAAAC0g5PxhAohzuMQqMORmE6hYiNk6Yn7fo52tkQyc9FJT4vsivVhV" // these two should generated by running `generateClientKeys()` let kClientPrivateKey: String = "UkVDMgAAAC0TXvcoAGxwWV3QQ9fgds+4pqAWmDqQAfkb0r/+gAi89sggGLpV" let kClientPublicKey: String = "VUVDMgAAAC3mmD1pAuXBcr8k+1rLNYkmw+MwTJMofuDaOTXLf75HW8BIG/5l" fileprivate func postRequestTo(_ stringURL: String, message: Data, completion: @escaping (_ data: Data?, _ error: Error?) -> Void) { let url: URL = URL(string: stringURL)! let config: URLSessionConfiguration = URLSessionConfiguration.default let session: URLSession = URLSession(configuration: config) let request: NSMutableURLRequest = NSMutableURLRequest(url: url) request.httpMethod = "POST" request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-type") let base64URLEncodedMessage: String = message.base64EncodedString(options: .endLineWithLineFeed) .addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics)! let base64Body: String = "\("message=")\(base64URLEncodedMessage)" let body: Data = base64Body.data(using: String.Encoding.utf8)! let uploadTask: URLSessionDataTask = session.uploadTask(with: request as URLRequest, from: body, completionHandler: {(data: Data?, response: URLResponse?, error: Error?) -> Void in guard let data = data else { print("Oops, response = \(response)\n error = \(error)") completion(nil, error) return } if let response = response as? HTTPURLResponse, response.statusCode != 200 { print("Oops, response = \(response)\n error = \(error)") completion(nil, error) return } completion(data, nil) return }) uploadTask.resume() } fileprivate func startSessionTo(_ stringURL: String, message: Data, completion: @escaping (_ error: Error?) -> Void) { postRequestTo(stringURL, message: message, completion: {(data: Data?, error: Error?) -> Void in guard let data = data else { print("Error occurred while starting session \(error)") return } do { guard let decryptedMessage = try self.session?.unwrapData(data) else { throw NSError(domain: "com.themisserver.example", code: -4, userInfo: nil) } if let session = self.session, session.isSessionEstablished() == true { print("Session established!") completion(nil) } else { self.startSessionTo(stringURL, message: decryptedMessage, completion: completion) } } catch let error { // frustrating, but 'unwrapData' can return nil without error (and it's okay) // Swift returns error "Foundation._GenericObjCError" if let session = self.session, session.isSessionEstablished() == true { print("Session established!") completion(nil) } else { print("Error occurred while decrypting session start message \(error)", #function) completion(error) } return } }) } fileprivate func sendMessageTo(_ stringURL: String, message: String, completion: @escaping (_ data: String?, _ error: Error?) -> Void) { var encryptedMessage: Data do { guard let wrappedMessage: Data = try self.session?.wrap(message.data(using: String.Encoding.utf8)) else { print("Error occurred during wrapping message ", #function) return } encryptedMessage = wrappedMessage } catch let error { print("Error occurred while wrapping message \(error)", #function) completion(nil, error) return } postRequestTo(stringURL, message: encryptedMessage, completion: {(data: Data?, error: Error?) -> Void in guard let data = data else { print("Error occurred while sending message \(error)") return } do { guard let decryptedMessage: Data = try self.session?.unwrapData(data), let resultString: String = String(data: decryptedMessage, encoding: String.Encoding.utf8) else { throw NSError(domain: "com.themisserver.example", code: -3, userInfo: nil) } completion(resultString, nil) } catch let error { print("Error occurred while decrypting message \(error)", #function) completion(nil, error) return } }) } func runSecureSessionCITest() { // uncomment to generate keys firste // generateClientKeys() // return; checkKeysNotEmpty() guard let clientIdData: Data = kClientId.data(using: String.Encoding.utf8), let clientPrivateKey: Data = Data(base64Encoded: kClientPrivateKey, options: .ignoreUnknownCharacters) else { print("Error occurred during base64 encoding", #function) return } self.transport = Transport() self.transport?.setupKeys(kServerId, serverPublicKey: kServerPublicKey) self.session = TSSession(userId: clientIdData, privateKey: clientPrivateKey, callbacks: self.transport) var connectionMessage: Data do { guard let resultOfConnectionRequest = try session?.connectRequest() else { throw NSError(domain: "com.themisserver.example", code: -2, userInfo: nil) } connectionMessage = resultOfConnectionRequest } catch let error { print("Error occurred while connecting to session \(error)", #function) return } let stringURL: String = "\("https://themis.cossacklabs.com/api/")\(kClientId)/" self.startSessionTo(stringURL, message: connectionMessage, completion: {(error: Error?) -> Void in if error != nil { print("Error occurred while session initialization \(error)", #function) return } self.sendMessageTo(stringURL, message: "This is test message from Swift", completion: {(data: String?, messageError: Error?) -> Void in guard let data = data else { print("Error occurred while sending message \(messageError)", #function) return } print("Response success:\n\(data)") }) }) } fileprivate func generateClientKeys() { // use client public key to run server // https://themis.cossacklabs.com/interactive-simulator/setup/ // // use client private key to encrypt your message guard let keyGeneratorEC: TSKeyGen = TSKeyGen(algorithm: .EC) else { print("Error occurred while initializing object keyGeneratorEC", #function) return } let privateKeyEC: Data = keyGeneratorEC.privateKey as Data let publicKeyEC: Data = keyGeneratorEC.publicKey as Data let privateKeyECString = privateKeyEC.base64EncodedString(options: .lineLength64Characters) let publicKeyECString = publicKeyEC.base64EncodedString(options: .lineLength64Characters) print("EC privateKey = \(privateKeyECString)") print("EC publicKey = \(publicKeyECString)") } fileprivate func checkKeysNotEmpty() { // Read how Themis Server works: // https://github.com/cossacklabs/themis/wiki/Using-Themis-Server assert(!(kClientId == "<client id>"), "Get client id from https://themis.cossacklabs.com/interactive-simulator/setup/") assert(!(kServerId == "<server id>"), "Get server id from https://themis.cossacklabs.com/interactive-simulator/setup/") assert(!(kServerPublicKey == "<server public key>"), "Get server key from https://themis.cossacklabs.com/interactive-simulator/setup/") assert(!(kClientPrivateKey == "<generated client private key>"), "Generate client keys by running `generateClientKeys()` or obtain from server https://themis.cossacklabs.com/interactive-simulator/setup/") assert(!(kClientPublicKey == "<generated client public key>"), "Generate client keys by running `generateClientKeys()` or obtain from server https://themis.cossacklabs.com/interactive-simulator/setup/") } }
apache-2.0
f5c8a5d6793fb03d1c003d8e93bd286a
41.568093
212
0.588208
4.908031
false
false
false
false
KIPPapp/KIPPapp
ParseApi.swift
1
2988
// // ParseApi.swift // kippapp // // Created by Monika Gorkani on 10/12/14. // Copyright (c) 2014 kippgroup. All rights reserved. // import Foundation class ParseAPI { init() { } var students: [Student] = [] var groups: [String] = [] func getStudentData(teacher:String,grade:String,completion: (students: [Student]?, groups:[String]?,error: NSError?) -> ()) { var query = PFQuery(className:"StudentStats") query.whereKey("Teacher", equalTo:teacher) query.whereKey("Grade", equalTo:grade) if (!students.isEmpty) { completion(students: students, groups: groups,error: nil) } else { var query = PFQuery(className:"StudentStats") query.whereKey("Teacher", equalTo:teacher) query.whereKey("Grade", equalTo:grade) query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in if error == nil { // The find succeeded. NSLog("Successfully retrieved \(objects.count) Student Stats.") // Do something with the found objects var index:Int = 1 for object in objects { var student:Student = Student() student.name = object["Student"] as String student.id = object["studentId"] as String student.groupName = object["currentObjective"] as String student.homeLogins = (object["homeLogins"] as String).toInt()! student.labLogins = (object["labLogins"] as String).toInt()! student.mastery = (object["Mastery"] as NSString).floatValue student.progress = (object["Progress"] as NSString).floatValue student.grade = object["Grade"] as String student.teacher = object["Teacher"] as String student.currentNumTries = (object["currentNumTries"] as String).toInt()! student.imagePath = "\(index.description).png" index=index+1 student.minLastWeek = (object["minLastWeek"] as String).toInt()! self.students.append(student) if (!contains(self.groups,student.groupName)) { self.groups.append(student.groupName) } } completion(students: self.students,groups: self.groups, error:nil) } else { // Log details of the failure NSLog("Error: %@ %@", error, error.userInfo!) completion(students:nil, groups: nil, error:error) } } } } }
mit
deb06da281e45e70152c6e814b864a46
38.84
129
0.501339
5.242105
false
false
false
false
OpenKitten/BSON
Sources/BSON/Types/Null.swift
2
877
/// The BSON Null type public struct Null: Primitive { /// Creates a new `Null` public init() {} public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() if var container = container as? AnySingleValueBSONEncodingContainer { try container.encode(primitive: self) } else { try container.encodeNil() } } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if let container = container as? AnySingleValueBSONDecodingContainer { self = try container.decodeNull() } else { guard container.decodeNil() else { throw BSONValueNotFound(type: Null.self, path: container.codingPath.map { $0.stringValue }) } } } }
mit
05c175ea53636039461ffc8c49eb862f
31.481481
107
0.596351
5.189349
false
false
false
false
chrisjmendez/swift-exercises
GUI/ShowHidePassword/ShowHidePassword/TextField.swift
1
1366
// // TextField.swift // Beacons // // Created by Tommy Trojan on 1/2/16. // Copyright © 2016 Chris Mendez. All rights reserved. // import Foundation // // TextField.swift // CustomForm // // Created by Tommy Trojan on 12/21/15. // Copyright © 2015 Chris Mendez. All rights reserved. // import UIKit @IBDesignable class TextField: UITextField { @IBInspectable var insetX: CGFloat = 0 @IBInspectable var insetY: CGFloat = 0 @IBInspectable var borderColor: UIColor = UIColor.clearColor() { didSet { layer.borderColor = borderColor.CGColor } } @IBInspectable var borderWidth:CGFloat = 0 { didSet{ layer.borderWidth = borderWidth } } @IBInspectable var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius layer.masksToBounds = cornerRadius > 0 } } // placeholder position override func textRectForBounds(bounds: CGRect) -> CGRect { return CGRectInset(bounds , insetX , insetY) } // text position override func editingRectForBounds(bounds: CGRect) -> CGRect { return CGRectInset(bounds , insetX , insetY) } override func placeholderRectForBounds(bounds: CGRect) -> CGRect { return CGRectInset(bounds, insetX, insetY) } }
mit
1f7f2dbe0b13a5052586854beab4cc45
22.947368
70
0.625367
4.592593
false
false
false
false
nguyenngocnhan90/Restful-Swift
Restful-Swift/AppDelegate.swift
2
2965
// // AppDelegate.swift // N3Restful-Swift // // Created by Nhan Nguyen on 2/18/16. // Copyright © 2016 Nhan Nguyen. All rights reserved. // import UIKit import SwiftyJSON @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. self.signIn() return true } func getListProvinces() { let addressInvoker = AddressInvoker() addressInvoker.getListAddress { (listProvinces, error) -> Void in print(listProvinces?.provinces?[0].name as Any) } } func signIn() { let sessionInvoker = SessionInvoker() let param = SignInParam() param.email = "[email protected]" param.password = "password" sessionInvoker.signIn(param) { (result, error) -> Void in print((result?.user)!) } } func uploadAvatar() { let userInvoker = UserInvoker() userInvoker.uploadAvatar { (success, error) -> Void in } } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
8ff7d2c2ba73d392b769bcd6dec2f6a9
37
285
0.69197
5.21831
false
false
false
false
ashokgelal/AlgorithmsPlayground
EfficientStock.playground/Contents.swift
1
646
func getMaxProfit(stockPrices: [Int]) -> Int? { if stockPrices.count < 2 { return nil } var minPrice = stockPrices[0] var maxProfit = stockPrices[1] - minPrice for (index, currentPrice) in enumerate(stockPrices) { if index == 0 { continue } var potentialProfit = currentPrice - minPrice maxProfit = max(maxProfit, potentialProfit) minPrice = min(minPrice, currentPrice) } return maxProfit } var profit = getMaxProfit([502, 521, 511, 510, 520, 515, 545, 530, 450, 530, 563, 343]) // Answer profit == 113 // Time O(n) // Space O(1)
mit
fd4b11186d8891ba21cf58d3e7fa14e6
22.071429
87
0.586687
3.712644
false
false
false
false
ello/ello-ios
Sources/Controllers/Editorials/EditorialsScreen.swift
1
1018
//// /// EditorialsScreen.swift // class EditorialsScreen: HomeSubviewScreen, EditorialsScreenProtocol { weak var delegate: EditorialsScreenDelegate? private var usage: EditorialsViewController.Usage init(usage: EditorialsViewController.Usage) { self.usage = usage super.init(frame: .zero) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(frame: CGRect) { self.usage = .loggedOut super.init(frame: frame) } override func style() { styleHomeScreenNavBar(navigationBar: navigationBar) navigationBar.sizeClass = .large } override func arrange() { super.arrange() arrangeHomeScreenNavBar( type: .editorials(loggedIn: usage == .loggedIn), navigationBar: navigationBar ) } } extension EditorialsScreen: HomeScreenNavBar { @objc func homeScreenScrollToTop() { delegate?.scrollToTop() } }
mit
ab0251e269066c5aab1577337acbbe0b
21.622222
69
0.643418
4.669725
false
false
false
false
esttorhe/RxSwift
RxDataSourceStarterKit/DataSources/RxCollectionViewSectionedAnimatedDataSource.swift
1
1485
// // RxCollectionViewSectionedAnimatedDataSource.swift // RxExample // // Created by Krunoslav Zaher on 7/2/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import UIKit import RxSwift import RxCocoa class RxCollectionViewSectionedAnimatedDataSource<S: SectionModelType> : RxCollectionViewSectionedDataSource<S> , RxCollectionViewDataSourceType { typealias Element = [Changeset<S>] // For some inexplicable reason, when doing animated updates first time // it crashes. Still need to figure out that one. var set = false func collectionView(collectionView: UICollectionView, observedEvent: Event<Element>) { switch observedEvent { case .Next(let boxedSections): for c in boxedSections.value { //print("Animating ==============================\n\(c)\n===============================\n") if !set { setSections(c.finalSections) collectionView.reloadData() set = true return } setSections(c.finalSections) collectionView.performBatchUpdates(c) } case .Error(let error): #if DEBUG fatalError("Binding error to UI") #endif case .Completed: break } } }
mit
6af0aca9581addec0851c68e4692f4bb
32.022222
111
0.540741
5.77821
false
false
false
false
Sorix/CloudCore
Source/Classes/CloudCore.swift
1
7834
// // CloudCore.swift // CloudCore // // Created by Vasily Ulianov on 06.02.17. // Copyright © 2017 Vasily Ulianov. All rights reserved. // import CoreData import CloudKit /** Main framework class, in most cases you will use only methods from this class, all methods and properties are `static`. ## Save to cloud On application inialization call `CloudCore.enable(persistentContainer:)` method, so framework will automatically monitor changes at Core Data and upload it to iCloud. ### Example ```swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Register for push notifications about changes application.registerForRemoteNotifications() // Enable CloudCore syncing CloudCore.delegate = someDelegate // it is recommended to set delegate to track errors CloudCore.enable(persistentContainer: persistentContainer) return true } ``` ## Fetch from cloud When CloudKit data is changed **push notification** is posted to an application. You need to handle it and fetch changed data from CloudKit with `CloudCore.fetchAndSave(using:to:error:completion:)` method. ### Example ```swift func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { // Check if it CloudKit's and CloudCore notification if CloudCore.isCloudCoreNotification(withUserInfo: userInfo) { // Fetch changed data from iCloud CloudCore.fetchAndSave(using: userInfo, to: persistentContainer, error: nil, completion: { (fetchResult) in completionHandler(fetchResult.uiBackgroundFetchResult) }) } } ``` You can also check for updated data at CloudKit **manually** (e.g. push notifications are not working). Use for that `CloudCore.fetchAndSave(to:error:completion:)` */ open class CloudCore { // MARK: - Properties private(set) static var coreDataListener: CoreDataListener? /// CloudCore configuration, it's recommended to set up before calling any of CloudCore methods. You can read more at `CloudCoreConfig` struct description public static var config = CloudCoreConfig() /// `Tokens` object, read more at class description. By default variable is loaded from User Defaults. public static var tokens = Tokens.loadFromUserDefaults() /// Error and sync actions are reported to that delegate public static weak var delegate: CloudCoreDelegate? { didSet { coreDataListener?.delegate = delegate } } public typealias NotificationUserInfo = [AnyHashable : Any] static private let queue = OperationQueue() // MARK: - Methods /// Enable CloudKit and Core Data synchronization /// /// - Parameters: /// - container: `NSPersistentContainer` that will be used to save data public static func enable(persistentContainer container: NSPersistentContainer) { // Listen for local changes let listener = CoreDataListener(container: container) listener.delegate = self.delegate listener.observe() self.coreDataListener = listener // Subscribe (subscription may be outdated/removed) #if !os(watchOS) let subscribeOperation = SubscribeOperation() subscribeOperation.errorBlock = { handle(subscriptionError: $0, container: container) } queue.addOperation(subscribeOperation) #endif // Fetch updated data (e.g. push notifications weren't received) let updateFromCloudOperation = FetchAndSaveOperation(persistentContainer: container) updateFromCloudOperation.errorBlock = { self.delegate?.error(error: $0, module: .some(.fetchFromCloud)) } #if !os(watchOS) updateFromCloudOperation.addDependency(subscribeOperation) #endif queue.addOperation(updateFromCloudOperation) } /// Disables synchronization (push notifications won't be sent also) public static func disable() { queue.cancelAllOperations() coreDataListener?.stopObserving() coreDataListener = nil // FIXME: unsubscribe } // MARK: Fetchers /** Fetch changes from one CloudKit database and save it to CoreData from `didReceiveRemoteNotification` method. Don't forget to check notification's UserInfo by calling `isCloudCoreNotification(withUserInfo:)`. If incorrect user info is provided `FetchResult.noData` will be returned at completion block. - Parameters: - userInfo: notification's user info, CloudKit database will be extraced from that notification - container: `NSPersistentContainer` that will be used to save fetched data - error: block will be called every time when error occurs during process - completion: `FetchResult` enumeration with results of operation */ public static func fetchAndSave(using userInfo: NotificationUserInfo, to container: NSPersistentContainer, error: ErrorBlock?, completion: @escaping (_ fetchResult: FetchResult) -> Void) { guard let cloudDatabase = self.database(for: userInfo) else { completion(.noData) return } DispatchQueue.global(qos: .utility).async { let errorProxy = ErrorBlockProxy(destination: error) let operation = FetchAndSaveOperation(from: [cloudDatabase], persistentContainer: container) operation.errorBlock = { errorProxy.send(error: $0) } operation.start() if errorProxy.wasError { completion(FetchResult.failed) } else { completion(FetchResult.newData) } } } /** Fetch changes from all CloudKit databases and save it to Core Data - Parameters: - container: `NSPersistentContainer` that will be used to save fetched data - error: block will be called every time when error occurs during process - completion: `FetchResult` enumeration with results of operation */ public static func fetchAndSave(to container: NSPersistentContainer, error: ErrorBlock?, completion: (() -> Void)?) { let operation = FetchAndSaveOperation(persistentContainer: container) operation.errorBlock = error operation.completionBlock = completion queue.addOperation(operation) } /** Check if notification is CloudKit notification containing CloudCore data - Parameter userInfo: userInfo of notification - Returns: `true` if notification contains CloudCore data */ public static func isCloudCoreNotification(withUserInfo userInfo: NotificationUserInfo) -> Bool { return (database(for: userInfo) != nil) } static func database(for notificationUserInfo: NotificationUserInfo) -> CKDatabase? { guard let notificationDictionary = notificationUserInfo as? [String: NSObject] else { return nil } let notification = CKNotification(fromRemoteNotificationDictionary: notificationDictionary) guard let id = notification.subscriptionID else { return nil } switch id { case config.subscriptionIDForPrivateDB: return config.container.privateCloudDatabase case config.subscriptionIDForSharedDB: return config.container.sharedCloudDatabase case _ where id.hasPrefix(config.publicSubscriptionIDPrefix): return config.container.publicCloudDatabase default: return nil } } static private func handle(subscriptionError: Error, container: NSPersistentContainer) { guard let cloudError = subscriptionError as? CKError, let partialErrorValues = cloudError.partialErrorsByItemID?.values else { delegate?.error(error: subscriptionError, module: nil) return } // Try to find "Zone Not Found" in partial errors for subError in partialErrorValues { guard let subError = subError as? CKError else { continue } if case .zoneNotFound = subError.code { // Zone wasn't found, we need to create it self.queue.cancelAllOperations() let setupOperation = SetupOperation(container: container, parentContext: nil) self.queue.addOperation(setupOperation) return } } delegate?.error(error: subscriptionError, module: nil) } }
mit
000a006c44af0bd41527e0f3915fa215
36.478469
206
0.761139
4.448041
false
false
false
false
ijoshsmith/swift-deep-linking
DeepLinking/DemoApp/DeepLinks.swift
1
959
// // DeepLinks.swift // DeepLinking // // Created by Joshua Smith on 5/18/17. // Copyright © 2017 iJoshSmith. All rights reserved. // /// Represents selecting a tab in the tab bar controller. /// Example - demoapp://select/tab/1 struct SelectTabDeepLink: DeepLink { static let template = DeepLinkTemplate() .term("select") .term("tab") .int(named: "index") init(values: DeepLinkValues) { tabIndex = values.path["index"] as! Int } let tabIndex: Int } /// Represents presenting an image to the user. /// Example - demoapp://show/photo?name=cat struct ShowPhotoDeepLink: DeepLink { static let template = DeepLinkTemplate() .term("show") .term("photo") .queryStringParameters([ .requiredString(named: "name") ]) init(values: DeepLinkValues) { imageName = values.query["name"] as! String } let imageName: String }
mit
0e200d83780c57376bb9f341ba2c3643
22.365854
57
0.610647
4.12931
false
false
false
false
kaojohnny/CoreStore
Sources/Migrating/MigrationType.swift
1
5200
// // MigrationType.swift // CoreStore // // Copyright © 2015 John Rommel Estropia // // 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 // MARK: - MigrationType /** The `MigrationType` specifies the type of migration required for a store. */ public enum MigrationType: BooleanType, Hashable { /** Indicates that the persistent store matches the latest model version and no migration is needed */ case None(version: String) /** Indicates that the persistent store does not match the latest model version but Core Data can infer the mapping model, so a lightweight migration is needed */ case Lightweight(sourceVersion: String, destinationVersion: String) /** Indicates that the persistent store does not match the latest model version and Core Data could not infer a mapping model, so a custom migration is needed */ case Heavyweight(sourceVersion: String, destinationVersion: String) /** Returns the source model version for the migration type. If no migration is required, `sourceVersion` will be equal to the `destinationVersion`. */ public var sourceVersion: String { switch self { case .None(let version): return version case .Lightweight(let sourceVersion, _): return sourceVersion case .Heavyweight(let sourceVersion, _): return sourceVersion } } /** Returns the destination model version for the migration type. If no migration is required, `destinationVersion` will be equal to the `sourceVersion`. */ public var destinationVersion: String { switch self { case .None(let version): return version case .Lightweight(_, let destinationVersion): return destinationVersion case .Heavyweight(_, let destinationVersion): return destinationVersion } } /** Returns `true` if the `MigrationType` is a lightweight migration. Used as syntactic sugar. */ public var isLightweightMigration: Bool { if case .Lightweight = self { return true } return false } /** Returns `true` if the `MigrationType` is a heavyweight migration. Used as syntactic sugar. */ public var isHeavyweightMigration: Bool { if case .Heavyweight = self { return true } return false } // MARK: BooleanType public var boolValue: Bool { switch self { case .None: return false case .Lightweight: return true case .Heavyweight: return true } } // MARK: Hashable public var hashValue: Int { let preHash = self.boolValue.hashValue ^ self.isHeavyweightMigration.hashValue switch self { case .None(let version): return preHash ^ version.hashValue case .Lightweight(let sourceVersion, let destinationVersion): return preHash ^ sourceVersion.hashValue ^ destinationVersion.hashValue case .Heavyweight(let sourceVersion, let destinationVersion): return preHash ^ sourceVersion.hashValue ^ destinationVersion.hashValue } } } // MARK: - MigrationType: Equatable @warn_unused_result public func == (lhs: MigrationType, rhs: MigrationType) -> Bool { switch (lhs, rhs) { case (.None(let version1), .None(let version2)): return version1 == version2 case (.Lightweight(let source1, let destination1), .Lightweight(let source2, let destination2)): return source1 == source2 && destination1 == destination2 case (.Heavyweight(let source1, let destination1), .Heavyweight(let source2, let destination2)): return source1 == source2 && destination1 == destination2 default: return false } }
mit
c1676443182717b49f1c045274f335ca
30.70122
160
0.636276
5.173134
false
false
false
false
A-Kod/vkrypt
Pods/SwiftyVK/Library/Sources/Presentation/Captcha/CapthcaPresenter.swift
2
3133
import Foundation protocol CaptchaPresenter { func present(rawCaptchaUrl: String, dismissOnFinish: Bool) throws -> String func dismiss() } final class CaptchaPresenterImpl: CaptchaPresenter { private let uiSyncQueue: DispatchQueue private let controllerMaker: CaptchaControllerMaker private weak var currentController: CaptchaController? private let timeout: TimeInterval private let urlSession: VKURLSession init( uiSyncQueue: DispatchQueue, controllerMaker: CaptchaControllerMaker, timeout: TimeInterval, urlSession: VKURLSession ) { self.uiSyncQueue = uiSyncQueue self.controllerMaker = controllerMaker self.timeout = timeout self.urlSession = urlSession } func present(rawCaptchaUrl: String, dismissOnFinish: Bool) throws -> String { let semaphore = DispatchSemaphore(value: 0) return try uiSyncQueue.sync { var result: String? var dismissed = false guard let controller = currentController ?? controllerMaker.captchaController() else { throw VKError.cantMakeCaptchaController } currentController = controller controller.prepareForPresent() let imageData = try downloadCaptchaImageData(rawUrl: rawCaptchaUrl) controller.present( imageData: imageData, onResult: { [weak currentController] givenResult in result = givenResult if dismissOnFinish { currentController?.dismiss() } else { semaphore.signal() } }, onDismiss: { dismissed = true semaphore.signal() } ) switch semaphore.wait(timeout: .now() + timeout) { case .timedOut: throw VKError.captchaPresenterTimedOut case .success: break } guard !dismissed else { throw VKError.captchaWasDismissed } guard let unwrappedResult = result else { throw VKError.captchaResultIsNil } return unwrappedResult } } func dismiss() { currentController?.dismiss() } private func downloadCaptchaImageData(rawUrl: String) throws -> Data { guard let url = URL(string: rawUrl) else { throw VKError.cantMakeCapthaImageUrl(rawUrl) } let result = urlSession.synchronousDataTaskWithURL(url: url) if let error = result.error { throw VKError.cantLoadCaptchaImage(error) } else if let data = result.data { return data } throw VKError.cantLoadCaptchaImageWithUnknownReason } }
apache-2.0
ff0ea1f0f3da9ea41e4d9f4406a79e70
29.715686
98
0.544207
6.071705
false
false
false
false
dunkelstern/unchained
Unchained/responseClasses/redirect_response.swift
1
963
// // redirect_response.swift // unchained // // Created by Johannes Schriewer on 17/12/15. // Copyright © 2015 Johannes Schriewer. All rights reserved. // import TwoHundred /// Redirect response, redirects the user to another URL public class RedirectResponse: HTTPResponseBase { /// Init with URL /// /// - parameter url: URL to redirect to /// - parameter permanent: (optional) set to true to send a permanent redirect (defaults to false) /// - parameter headers: (optional) additional headers to send public init(_ url: String, permanent: Bool = false, headers: [HTTPHeader]? = nil) { super.init() if permanent { self.statusCode = .MovedPermanently } else { self.statusCode = .SeeOther } if let headers = headers { self.headers.appendContentsOf(headers) } self.headers.append(HTTPHeader("Location", url)) } }
bsd-3-clause
62548518c52d62fcfb5512b1000daffe
27.323529
102
0.620582
4.495327
false
false
false
false
ccrama/Slide-iOS
Slide for Apple Watch Extension/CommentRepliesController.swift
1
3157
// // CommentRepliesController.swift // Slide for Apple Watch Extension // // Created by Carlos Crane on 3/1/20. // Copyright © 2020 Haptic Apps. All rights reserved. // import Foundation import WatchConnectivity import WatchKit class CommentRepliesController: Votable { public var modelContext: CommentsRowController? @IBOutlet var originalBody: WKInterfaceLabel! @IBOutlet var commentsTable: WKInterfaceTable! @IBOutlet var originalTitle: WKInterfaceLabel! @IBOutlet var upvoteButton: WKInterfaceButton! @IBOutlet var downvoteButton: WKInterfaceButton! override init() { super.init() self.setTitle("Back") } @IBAction func didUpvote() { (WKExtension.shared().visibleInterfaceController as? Votable)?.sharedUp = upvoteButton (WKExtension.shared().visibleInterfaceController as? Votable)?.sharedDown = downvoteButton (WKExtension.shared().visibleInterfaceController as? Votable)?.doVote(id: modelContext!.fullname!, upvote: true, downvote: false) } @IBAction func didDownvote() { (WKExtension.shared().visibleInterfaceController as? Votable)?.sharedUp = upvoteButton (WKExtension.shared().visibleInterfaceController as? Votable)?.sharedDown = downvoteButton (WKExtension.shared().visibleInterfaceController as? Votable)?.doVote(id: modelContext!.fullname!, upvote: false, downvote: true) } override func contextForSegue(withIdentifier segueIdentifier: String, in table: WKInterfaceTable, rowIndex: Int) -> Any? { return table.rowController(at: rowIndex) } override func awake(withContext context: Any?) { super.awake(withContext: context) let myModel = context as! CommentsRowController //make the model self.modelContext = myModel self.originalTitle.setAttributedText(myModel.attributedTitle) self.originalBody.setAttributedText(myModel.attributedBody) upvoteButton.setBackgroundColor((myModel.dictionary["upvoted"] ?? false) as! Bool ? UIColor.init(hexString: "#FF5700") : UIColor.gray) downvoteButton.setBackgroundColor((myModel.dictionary["downvoted"] ?? false) as! Bool ? UIColor.init(hexString: "#9494FF") : UIColor.gray) WCSession.default.sendMessage(["comments": myModel.submissionId!, "context": myModel.id!], replyHandler: { (message) in self.comments = message["comments"] as? [NSDictionary] ?? [] self.beginLoadingTable() }, errorHandler: { (error) in print(error) }) } var comments = [NSDictionary]() func beginLoadingTable() { WKInterfaceDevice.current().play(.success) commentsTable.insertRows(at: IndexSet(integersIn: 0 ..< comments.count), withRowType: "CommentsRowController") if comments.count > 0 { for index in 0...(comments.count - 1) { let item = comments[index] if let rowController = commentsTable.rowController(at: index) as? CommentsRowController { rowController.setData(dictionary: item) } } } } }
apache-2.0
4e77995a99196b4e36145af70778d8be
42.232877
146
0.680608
4.753012
false
false
false
false
cossacklabs/themis
docs/examples/swift/iOS-SPM/ThemisTest/AppDelegate.swift
1
15179
// Copyright (c) 2021 Cossack Labs Limited // // 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 import themis @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // // We don't do UI. Please look into debug console to see the results. // runExampleSecureCellSealMode() runExampleSecureCellTokenProtectMode() runExampleSecureCellImprint() runExampleGeneratingKeys() runExampleReadingKeysFromFile() runExampleSecureMessageEncryptionDecryption() runExampleSecureMessageSignVerify() runExampleSecureComparator() return true } // MARK: - Secure Cell func generateMasterKey() -> Data { let masterKeyString: String = "UkVDMgAAAC13PCVZAKOczZXUpvkhsC+xvwWnv3CLmlG0Wzy8ZBMnT+2yx/dg" let masterKeyData: Data = Data(base64Encoded: masterKeyString, options: .ignoreUnknownCharacters)! return masterKeyData } func runExampleSecureCellSealMode() { print("----------------------------------", #function) let masterKeyData: Data = self.generateMasterKey() guard let cellSeal: TSCellSeal = TSCellSeal(key: masterKeyData) else { print("Error occurred while initializing object cellSeal", #function) return } let message: String = "All your base are belong to us!" let context: String = "For great justice" var encryptedMessage: Data = Data() do { // context is optional parameter and may be ignored encryptedMessage = try cellSeal.encrypt(message.data(using: .utf8)!, context: context.data(using: .utf8)!) print("decryptedMessagez = \(encryptedMessage)") } catch let error as NSError { print("Error occurred while encrypting \(error)", #function) return } do { let decryptedMessage: Data = try cellSeal.decrypt(encryptedMessage, context: context.data(using: .utf8)!) let resultString: String = String(data: decryptedMessage, encoding: .utf8)! print("decryptedMessage = \(resultString)") } catch let error as NSError { print("Error occurred while decrypting \(error)", #function) return } } func runExampleSecureCellTokenProtectMode() { print("----------------------------------", #function) let masterKeyData: Data = self.generateMasterKey() guard let cellToken: TSCellToken = TSCellToken(key: masterKeyData) else { print("Error occurred while initializing object cellToken", #function) return } let message: String = "Roses are grey. Violets are grey." let context: String = "I'm a dog" var encryptedMessage: TSCellTokenEncryptedResult = TSCellTokenEncryptedResult() do { // context is optional parameter and may be ignored encryptedMessage = try cellToken.encrypt(message.data(using: .utf8)!, context: context.data(using: .utf8)!) print("encryptedMessage.cipher = \(encryptedMessage.encrypted)") print("encryptedMessage.token = \(encryptedMessage.token)") } catch let error as NSError { print("Error occurred while encrypting \(error)", #function) return } do { let decryptedMessage: Data = try cellToken.decrypt(encryptedMessage.encrypted, token: encryptedMessage.token, context: context.data(using: .utf8)!) let resultString: String = String(data: decryptedMessage, encoding: .utf8)! print("decryptedMessage = \(resultString)") } catch let error as NSError { print("Error occurred while decrypting \(error)", #function) return } } func runExampleSecureCellImprint() { print("----------------------------------", #function) let masterKeyData: Data = self.generateMasterKey() guard let contextImprint: TSCellContextImprint = TSCellContextImprint(key: masterKeyData) else { print("Error occurred while initializing object contextImprint", #function) return } let message: String = "Roses are red. My name is Dave. This poem have no sense" let context: String = "Microwave" var encryptedMessage: Data = Data() do { // context is NOT optional parameter here encryptedMessage = try contextImprint.encrypt(message.data(using: .utf8)!, context: context.data(using: .utf8)!) print("encryptedMessage = \(encryptedMessage)") } catch let error as NSError { print("Error occurred while encrypting \(error)", #function) return } do { // context is NOT optional parameter here let decryptedMessage: Data = try contextImprint.decrypt(encryptedMessage, context: context.data(using: .utf8)!) let resultString: String = String(data: decryptedMessage, encoding: .utf8)! print("decryptedMessage = \(resultString)") } catch let error as NSError { print("Error occurred while decrypting \(error)", #function) return } } // MARK: - Key Generation and Loading func runExampleGeneratingKeys() { print("----------------------------------", #function) // Generating RSA keys guard let keyGeneratorRSA: TSKeyGen = TSKeyGen(algorithm: .RSA) else { print("Error occurred while initializing object keyGeneratorRSA", #function) return } let privateKeyRSA: Data = keyGeneratorRSA.privateKey as Data let publicKeyRSA: Data = keyGeneratorRSA.publicKey as Data print("RSA privateKey = \(privateKeyRSA)") print("RSA publicKey = \(publicKeyRSA)") // Generating EC keys guard let keyGeneratorEC: TSKeyGen = TSKeyGen(algorithm: .EC) else { print("Error occurred while initializing object keyGeneratorEC", #function) return } let privateKeyEC: Data = keyGeneratorEC.privateKey as Data let publicKeyEC: Data = keyGeneratorEC.publicKey as Data print("EC privateKey = \(privateKeyEC)") print("RSA publicKey = \(publicKeyEC)") } // Sometimes you will need to read keys from files func runExampleReadingKeysFromFile() { print("----------------------------------", #function) let fileManager: FileManager = FileManager.default let mainBundle: Bundle = Bundle.main // yes, app will crash if no keys. that's idea of our sample let serverPrivateKeyFromFile: Data = fileManager.contents(atPath: mainBundle.path(forResource: "server", ofType: "priv")!)! let serverPublicKeyFromFile: Data = fileManager.contents(atPath: mainBundle.path(forResource: "server", ofType: "pub")!)! let clientPrivateKeyOldFromFile: Data = fileManager.contents(atPath: mainBundle.path(forResource: "client", ofType: "priv")!)! let clientPublicKeyOldFromFile: Data = fileManager.contents(atPath: mainBundle.path(forResource: "client", ofType: "pub")!)! print("serverPrivateKeyFromFile = \(serverPrivateKeyFromFile)") print("serverPublicKeyFromFile = \(serverPublicKeyFromFile)") print("clientPrivateKeyOldFromFile = \(clientPrivateKeyOldFromFile)") print("clientPublicKeyOldFromFile = \(clientPublicKeyOldFromFile)") } // MARK: - Secure Message func runExampleSecureMessageEncryptionDecryption() { print("----------------------------------", #function) // ---------- encryption ---------------- // base64 encoded keys: // client private key // server public key let serverPublicKeyString: String = "VUVDMgAAAC2ELbj5Aue5xjiJWW3P2KNrBX+HkaeJAb+Z4MrK0cWZlAfpBUql" let clientPrivateKeyString: String = "UkVDMgAAAC13PCVZAKOczZXUpvkhsC+xvwWnv3CLmlG0Wzy8ZBMnT+2yx/dg" guard let serverPublicKey: Data = Data(base64Encoded: serverPublicKeyString, options: .ignoreUnknownCharacters), let clientPrivateKey: Data = Data(base64Encoded: clientPrivateKeyString, options: .ignoreUnknownCharacters) else { print("Error occurred during base64 encoding", #function) return } let encrypter: TSMessage = TSMessage.init(inEncryptModeWithPrivateKey: clientPrivateKey, peerPublicKey: serverPublicKey)! let message: String = "- Knock, knock.\n- Who’s there?\n*very long pause...*\n- Java." var encryptedMessage: Data = Data() do { encryptedMessage = try encrypter.wrap(message.data(using: .utf8)) print("encryptedMessage = \(encryptedMessage)") } catch let error as NSError { print("Error occurred while encrypting \(error)", #function) return } // ---------- decryption ---------------- let serverPrivateKeyString: String = "UkVDMgAAAC1FsVa6AMGljYqtNWQ+7r4RjXTabLZxZ/14EXmi6ec2e1vrCmyR" let clientPublicKeyString: String = "VUVDMgAAAC1SsL32Axjosnf2XXUwm/4WxPlZauQ+v+0eOOjpwMN/EO+Huh5d" guard let serverPrivateKey: Data = Data(base64Encoded: serverPrivateKeyString, options: .ignoreUnknownCharacters), let clientPublicKey: Data = Data(base64Encoded: clientPublicKeyString, options: .ignoreUnknownCharacters) else { print("Error occurred during base64 encoding", #function) return } let decrypter: TSMessage = TSMessage.init(inEncryptModeWithPrivateKey: serverPrivateKey, peerPublicKey: clientPublicKey)! do { let decryptedMessage: Data = try decrypter.unwrapData(encryptedMessage) let resultString: String = String(data: decryptedMessage, encoding: .utf8)! print("decryptedMessage->\n\(resultString)") } catch let error as NSError { print("Error occurred while decrypting \(error)", #function) return } } func runExampleSecureMessageSignVerify() { print("----------------------------------", #function) // base64 encoded keys: // private key // public key let publicKeyString: String = "VUVDMgAAAC2ELbj5Aue5xjiJWW3P2KNrBX+HkaeJAb+Z4MrK0cWZlAfpBUql" let privateKeyString: String = "UkVDMgAAAC1FsVa6AMGljYqtNWQ+7r4RjXTabLZxZ/14EXmi6ec2e1vrCmyR" guard let publicKey: Data = Data(base64Encoded: publicKeyString, options: .ignoreUnknownCharacters), let privateKey: Data = Data(base64Encoded: privateKeyString, options: .ignoreUnknownCharacters) else { print("Error occurred during base64 encoding", #function) return } // ---------- signing ---------------- // use private key let signer: TSMessage = TSMessage.init(inSignVerifyModeWithPrivateKey: privateKey, peerPublicKey: nil)! let message: String = "I had a problem so I though to use Java. Now I have a ProblemFactory." var signedMessage: Data = Data() do { signedMessage = try signer.wrap(message.data(using: .utf8)) print("signedMessage = \(signedMessage)") } catch let error as NSError { print("Error occurred while signing \(error)", #function) return } // ---------- verification ---------------- // use public key let verifier = TSMessage.init(inSignVerifyModeWithPrivateKey: nil, peerPublicKey: publicKey)! do { let verifiedMessage: Data = try verifier.unwrapData(signedMessage) let resultString: String = String(data: verifiedMessage, encoding: .utf8)! print("verifiedMessage ->\n\(resultString)") } catch let error as NSError { print("Error occurred while verifing \(error)", #function) return } } // MARK: - Secure Comparator func runExampleSecureComparator() { print("----------------------------------", #function) let sharedMessage = "shared secret" let client: TSComparator = TSComparator.init(messageToCompare: sharedMessage.data(using: .utf8)!)! let server: TSComparator = TSComparator.init(messageToCompare: sharedMessage.data(using: .utf8)!)! // send this message to server var data = try? client.beginCompare() while (client.status() == TSComparatorStateType.notReady || server.status() == TSComparatorStateType.notReady ) { // receive from server data = try? server.proceedCompare(data) // proceed and send again data = try? client.proceedCompare(data) } if (client.status() == TSComparatorStateType.match) { // secrets match print("SecureComparator secrets match") } else { // secrets don't match print("SecureComparator secrets do not match") } } }
apache-2.0
fa26f26605678b077a09ba5b3ccc249c
42.612069
145
0.572643
5.110101
false
false
false
false
PiasMasumKhan/Swift
iCloud/iCloud/ViewController.swift
32
8653
// // ViewController.swift // iCloud // // Created by Carlos Butron on 07/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 CloudKit class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UICollectionViewDelegate, UICollectionViewDataSource { var celdas: NSMutableArray = NSMutableArray() var container = NSFileManager.defaultManager().URLForUbiquityContainerIdentifier(nil) var metadataQuery : NSMetadataQuery! @IBOutlet weak var collectionView: UICollectionView! @IBAction func deletePhotos(sender: UIBarButtonItem) { removeImagesFromICloud() } @IBAction func choosePhotos(sender: UIBarButtonItem) { var action = UIAlertController (title: "Photos", message: "Select source", preferredStyle: UIAlertControllerStyle.ActionSheet) action.addAction(UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default, handler: { (action) -> Void in println("Choose camera") self.getPhoto(true) })) action.addAction(UIAlertAction(title: "Galery", style: UIAlertActionStyle.Default, handler: { (action) -> Void in println("Choose galery") self.getPhoto(false) })) self.presentViewController(action, animated: true, completion: nil) } func getPhoto (camera: Bool){ let picker = UIImagePickerController() picker.delegate = self if (camera){ picker.sourceType = UIImagePickerControllerSourceType.Camera }else{ picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary println("Choose from galery 2") } picker.allowsEditing = false self.presentViewController(picker, animated: true, completion: nil) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { self.dismissViewControllerAnimated(true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { self.dismissViewControllerAnimated(true, completion: nil) var fullImage = (info as NSDictionary)[UIImagePickerControllerOriginalImage] as! UIImage println("Choose from galery 3") savePhotoICloud(fullImage) } func savePhotoICloud (image: UIImage){ var date = NSDate() var df = NSDateFormatter() df.dateFormat = "dd_MM_yy_hh_mm_ss" var photoName = NSString (format: "PHOTO_%@", df.stringFromDate(date)) if (container != nil){ var fileURLiCloud = container!.URLByAppendingPathComponent("Documents").URLByAppendingPathComponent(photoName as String) var photo = DocumentPhoto (fileURL: fileURLiCloud) photo.image = image photo.saveToURL(fileURLiCloud, forSaveOperation: UIDocumentSaveOperation.ForCreating, completionHandler: { (success) -> Void in self.celdas.addObject(image) println("Choose from galery 4") self.collectionView.reloadData() }) } } func removeImagesFromICloud (){ if (container != nil){ self.metadataQuery = NSMetadataQuery() self.metadataQuery.searchScopes = NSArray (object: NSMetadataQueryUbiquitousDocumentsScope) as [AnyObject] var predicate = NSPredicate(format: "%K like 'PHOTO*'", NSMetadataItemFSNameKey) self.metadataQuery.predicate = predicate NSNotificationCenter.defaultCenter().addObserver(self, selector: "queryDeleted:", name: NSMetadataQueryDidFinishGatheringNotification, object: self.metadataQuery) self.metadataQuery.startQuery() } } func loadImagesFromICloud (){ if (container != nil){ self.metadataQuery = NSMetadataQuery() self.metadataQuery.searchScopes = NSArray (object: NSMetadataQueryUbiquitousDocumentsScope) as [AnyObject] var predicate = NSPredicate(format: "%K like 'PHOTO*'", NSMetadataItemFSNameKey) self.metadataQuery.predicate = predicate NSNotificationCenter.defaultCenter().addObserver(self, selector: "queryFinished:", name: NSMetadataQueryDidFinishGatheringNotification, object: self.metadataQuery) self.metadataQuery.startQuery() } } func queryFinished(notification: NSNotification){ var mq = notification.object as! NSMetadataQuery mq.disableUpdates() mq.stopQuery() celdas.removeAllObjects() for (var i = 0; i<mq.resultCount;i++){ var result = mq.resultAtIndex(i) as! NSMetadataItem var nombre = result.valueForAttribute(NSMetadataItemFSNameKey) as! NSString var url = result.valueForAttribute(NSMetadataItemURLKey) as! NSURL var document : DocumentPhoto! = DocumentPhoto(fileURL: url) document?.openWithCompletionHandler({ (success) -> Void in if (success == true){ self.celdas.addObject(document.image) println("addobject in queryfinished") self.collectionView.reloadData() } }) } } func queryDeleted(notification: NSNotification){ var mq = notification.object as! NSMetadataQuery mq.disableUpdates() mq.stopQuery() celdas.removeAllObjects() for (var i = 0; i<mq.resultCount;i++){ var result = mq.resultAtIndex(i) as! NSMetadataItem var nombre = result.valueForAttribute(NSMetadataItemFSNameKey) as! NSString var url = result.valueForAttribute(NSMetadataItemURLKey) as! NSURL var document : DocumentPhoto! = DocumentPhoto(fileURL: url) var fileManager = NSFileManager() fileManager.removeItemAtURL(document.fileURL, error: nil) self.collectionView.reloadData() document?.openWithCompletionHandler({ (success) -> Void in if (success == true){ self.collectionView.reloadData() } }) } } override func viewDidLoad() { super.viewDidLoad() // savePhotoICloud(UIImage(named: "fondo1.jpg")!) loadImagesFromICloud () // self.collectionView.reloadData() // var imagenView: UIImageView = UIImageView() // imagenView.image = UIImage(named: "imagen1.png") // self.celdas.addObject(imagenView) // 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 collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var identifier:NSString = "CollectionCell" var cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier as String, forIndexPath: indexPath) as! UICollectionViewCell var imageView:UIImageView = cell.viewWithTag(1) as! UIImageView imageView.image = celdas.objectAtIndex(indexPath.row) as? UIImage // imageView.image = UIImage(named: "imagen1.png") return cell } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return celdas.count } }
gpl-3.0
270c344ba591493871e4309739f6c78b
39.060185
159
0.639316
5.404747
false
false
false
false
chrishulbert/gondola-ios
gondola-ios/ViewControllers/TVShowSeasonsViewController.swift
1
7512
// // TVShowSeasonsViewController.swift // Gondola TVOS // // Created by Chris on 12/02/2017. // Copyright © 2017 Chris Hulbert. All rights reserved. // // This is the show details with a list of seasons. import UIKit class TVShowSeasonsViewController: UIViewController { let show: TVShowMetadata init(show: TVShowMetadata) { self.show = show super.init(nibName: nil, bundle: nil) title = show.name navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } lazy var rootView = TVShowSeasonsView() override func loadView() { view = rootView } override func viewDidLoad() { super.viewDidLoad() rootView.collection.register(PictureCell.self, forCellWithReuseIdentifier: "cell") rootView.collection.dataSource = self rootView.collection.delegate = self rootView.overview.text = show.overview // Load the backdrop. ServiceHelpers.imageRequest(path: show.backdrop) { result in switch result { case .success(let image): DispatchQueue.main.async { self.rootView.background.image = image UIView.animate(withDuration: 0.3) { self.rootView.background.alpha = 1 } } case .failure(let error): NSLog("Error loading backdrop: \(error)") } } } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } } extension TVShowSeasonsViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return show.seasons.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let season = show.seasons[indexPath.item] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! PictureCell cell.label.text = season.name cell.image.image = nil cell.imageAspectRatio = 1.5 // TODO use a reusable image view? Or some helper that checks for stale? cell.imagePath = season.image ServiceHelpers.imageRequest(path: season.image) { result in DispatchQueue.main.async { if cell.imagePath == season.image { // Cell hasn't been recycled? switch result { case .success(let image): cell.image.image = image case .failure(let error): NSLog("error: \(error)") // TODO show sad cloud image. } } } } return cell } } extension TVShowSeasonsViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let season = show.seasons[indexPath.item] let vc = TVSeasonEpisodesViewController(show: show, season: season, backdrop: rootView.background.image) navigationController?.pushViewController(vc, animated: true) } } class TVShowSeasonsView: UIView { let background = UIImageView() let dim = UIView() let overview = UILabel() let collection: UICollectionView let layout = UICollectionViewFlowLayout() init() { // TODO have a layout helper. layout.scrollDirection = .horizontal let itemWidth = PictureCell.width(forHeight: K.itemHeight, imageAspectRatio: 1.5) layout.itemSize = CGSize(width: itemWidth, height: K.itemHeight) layout.minimumLineSpacing = LayoutHelpers.paddingH layout.minimumInteritemSpacing = 0 layout.sectionInset = UIEdgeInsets(top: LayoutHelpers.paddingV, left: LayoutHelpers.sideMargins, bottom: LayoutHelpers.vertMargins, right: LayoutHelpers.sideMargins) collection = UICollectionView(frame: UIScreen.main.bounds, collectionViewLayout: layout) collection.backgroundColor = nil collection.backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .dark)) super.init(frame: CGRect.zero) backgroundColor = UIColor.black background.contentMode = .scaleAspectFill background.alpha = 0 background.clipsToBounds = true background.translatesAutoresizingMaskIntoConstraints = false addSubview(background) background.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true background.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true background.topAnchor.constraint(equalTo: topAnchor).isActive = true background.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true dim.backgroundColor = UIColor(white: 0, alpha: 0.6) dim.translatesAutoresizingMaskIntoConstraints = false addSubview(dim) dim.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true dim.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true dim.topAnchor.constraint(equalTo: topAnchor).isActive = true overview.textColor = UIColor.white overview.font = UIFont.systemFont(ofSize: 12, weight: .light) overview.numberOfLines = 0 overview.translatesAutoresizingMaskIntoConstraints = false addSubview(overview) overview.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor, constant: LayoutHelpers.sideMargins).isActive = true overview.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor, constant: -LayoutHelpers.sideMargins).isActive = true overview.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: LayoutHelpers.vertMargins).isActive = true collection.translatesAutoresizingMaskIntoConstraints = false addSubview(collection) collection.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true collection.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true collection.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor).isActive = true collection.heightAnchor.constraint(equalToConstant: K.itemHeight + layout.sectionInset.top + layout.sectionInset.bottom).isActive = true dim.bottomAnchor.constraint(equalTo: collection.topAnchor).isActive = true overview.bottomAnchor.constraint(lessThanOrEqualTo: collection.topAnchor, constant: -LayoutHelpers.vertMargins).isActive = true } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } struct K { static let itemUnfocusedHeightToScreenHeightRatio: CGFloat = 0.3 static let itemHeight: CGFloat = { return round(UIScreen.main.bounds.height * itemUnfocusedHeightToScreenHeightRatio) }() } }
mit
71be220b69cba426ab98fd397aa00fdd
38.740741
144
0.647983
5.547267
false
false
false
false
buscarini/miscel
Miscel/Classes/Extensions/String.swift
1
1925
// // String.swift // Miscel // // Created by Jose Manuel Sánchez Peñarroja on 11/11/15. // Copyright © 2015 vitaminew. All rights reserved. // import UIKit public extension String { public static func length(_ string: String) -> Int { return string.characters.count } public static func empty(_ string: String) -> Bool { return self.length(string) == 0 } public static func isBlank(_ string: String?) -> Bool { guard let string = string else { return true } return trimmed(string).characters.count == 0 } public static func trimmed(_ string: String) -> String { return string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } public static func joined(_ components: [String?], separator: String = "\n") -> String { return components.flatMap {$0} .filter(not(isBlank)) .joined(separator: separator) } public static func plainString(_ htmlString: String) -> String { return htmlString.withBRsAsNewLines().convertingHTMLToPlainText() } public static func localize(_ string: String) -> String { return string.localized() } public func localized() -> String { return NSLocalizedString(self, comment: "") } public static func wholeRange(_ string: String) -> Range<Index> { return string.characters.startIndex..<string.characters.endIndex } public static func words(_ string: String) -> [String] { var results : [String] = [] string.enumerateLinguisticTags(in: self.wholeRange(string), scheme: NSLinguisticTagScheme.lemma.rawValue, options: [], orthography: nil) { // string.enumerateLinguisticTagsInRange(self.wholeRange(string), scheme: NSLinguisticTagWord, options: [], orthography: nil) { (tag, tokenRange, sentenceRange,_) in results.append(String(string[tokenRange])) // results.append(string.substring(with: tokenRange)) // results.append(string.substringWithRange(tokenRange)) } return results } }
mit
c5728492cdbce5f41aaab720c768a0b4
26.855072
140
0.708117
3.805941
false
false
false
false
gregomni/swift
stdlib/public/core/PrefixWhile.swift
10
9370
//===-- PrefixWhile.swift - Lazy views for prefix(while:) -----*- 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 // //===----------------------------------------------------------------------===// /// A sequence whose elements consist of the initial consecutive elements of /// some base sequence that satisfy a given predicate. /// /// - Note: When `LazyPrefixWhileSequence` wraps a collection type, the /// performance of accessing `endIndex` depends on how many /// elements satisfy the predicate at the start of the collection, and might /// not offer the usual performance given by the `Collection` protocol. /// Accessing `endIndex`, the `last` property, or calling methods that /// depend on moving indices might not have the documented complexity. @frozen // lazy-performance public struct LazyPrefixWhileSequence<Base: Sequence> { public typealias Element = Base.Element @usableFromInline // lazy-performance internal var _base: Base @usableFromInline // lazy-performance internal let _predicate: (Element) -> Bool @inlinable // lazy-performance internal init(_base: Base, predicate: @escaping (Element) -> Bool) { self._base = _base self._predicate = predicate } } extension LazyPrefixWhileSequence { /// An iterator over the initial elements traversed by a base iterator that /// satisfy a given predicate. /// /// This is the associated iterator for the `LazyPrefixWhileSequence`, /// `LazyPrefixWhileCollection`, and `LazyPrefixWhileBidirectionalCollection` /// types. @frozen // lazy-performance public struct Iterator { public typealias Element = Base.Element @usableFromInline // lazy-performance internal var _predicateHasFailed = false @usableFromInline // lazy-performance internal var _base: Base.Iterator @usableFromInline // lazy-performance internal let _predicate: (Element) -> Bool @inlinable // lazy-performance internal init(_base: Base.Iterator, predicate: @escaping (Element) -> Bool) { self._base = _base self._predicate = predicate } } } extension LazyPrefixWhileSequence.Iterator: IteratorProtocol, Sequence { @inlinable // lazy-performance public mutating func next() -> Element? { // Return elements from the base iterator until one fails the predicate. if !_predicateHasFailed, let nextElement = _base.next() { if _predicate(nextElement) { return nextElement } else { _predicateHasFailed = true } } return nil } } extension LazyPrefixWhileSequence: Sequence { @inlinable // lazy-performance public __consuming func makeIterator() -> Iterator { return Iterator(_base: _base.makeIterator(), predicate: _predicate) } } extension LazyPrefixWhileSequence: LazySequenceProtocol { public typealias Elements = LazyPrefixWhileSequence } extension LazySequenceProtocol { /// Returns a lazy sequence of the initial consecutive elements that satisfy /// `predicate`. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns `true` if the element should be included or /// `false` otherwise. Once `predicate` returns `false` it will not be /// called again. @inlinable // lazy-performance public __consuming func prefix( while predicate: @escaping (Elements.Element) -> Bool ) -> LazyPrefixWhileSequence<Self.Elements> { return LazyPrefixWhileSequence(_base: self.elements, predicate: predicate) } } /// A lazy collection wrapper that includes the initial consecutive /// elements of an underlying collection that satisfy a predicate. /// /// - Note: The performance of accessing `endIndex` depends on how many /// elements satisfy the predicate at the start of the collection, and might /// not offer the usual performance given by the `Collection` protocol. /// Accessing `endIndex`, the `last` property, or calling methods that /// depend on moving indices might not have the documented complexity. public typealias LazyPrefixWhileCollection<T: Collection> = LazyPrefixWhileSequence<T> extension LazyPrefixWhileCollection { /// A position in the base collection of a `LazyPrefixWhileCollection` or the /// end of that collection. @frozen // lazy-performance @usableFromInline internal enum _IndexRepresentation { case index(Base.Index) case pastEnd } /// A position in a `LazyPrefixWhileCollection` or /// `LazyPrefixWhileBidirectionalCollection` instance. @frozen // lazy-performance public struct Index { /// The position corresponding to `self` in the underlying collection. @usableFromInline // lazy-performance internal let _value: _IndexRepresentation /// Creates a new index wrapper for `i`. @inlinable // lazy-performance internal init(_ i: Base.Index) { self._value = .index(i) } /// Creates a new index that can represent the `endIndex` of a /// `LazyPrefixWhileCollection<Base>`. This is not the same as a wrapper /// around `Base.endIndex`. @inlinable // lazy-performance internal init(endOf: Base) { self._value = .pastEnd } } } // FIXME: should work on the typealias extension LazyPrefixWhileSequence.Index: Comparable where Base: Collection { @inlinable // lazy-performance public static func == ( lhs: LazyPrefixWhileCollection<Base>.Index, rhs: LazyPrefixWhileCollection<Base>.Index ) -> Bool { switch (lhs._value, rhs._value) { case let (.index(l), .index(r)): return l == r case (.pastEnd, .pastEnd): return true case (.pastEnd, .index), (.index, .pastEnd): return false } } @inlinable // lazy-performance public static func < ( lhs: LazyPrefixWhileCollection<Base>.Index, rhs: LazyPrefixWhileCollection<Base>.Index ) -> Bool { switch (lhs._value, rhs._value) { case let (.index(l), .index(r)): return l < r case (.index, .pastEnd): return true case (.pastEnd, _): return false } } } // FIXME: should work on the typealias extension LazyPrefixWhileSequence.Index: Hashable where Base.Index: Hashable, Base: Collection { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { switch _value { case .index(let value): hasher.combine(value) case .pastEnd: hasher.combine(Int.max) } } } extension LazyPrefixWhileCollection: Collection { public typealias SubSequence = Slice<LazyPrefixWhileCollection<Base>> @inlinable // lazy-performance public var startIndex: Index { return Index(_base.startIndex) } @inlinable // lazy-performance public var endIndex: Index { // If the first element of `_base` satisfies the predicate, there is at // least one element in the lazy collection: Use the explicit `.pastEnd` index. if let first = _base.first, _predicate(first) { return Index(endOf: _base) } // `_base` is either empty or `_predicate(_base.first!) == false`. In either // case, the lazy collection is empty, so `endIndex == startIndex`. return startIndex } @inlinable // lazy-performance public func index(after i: Index) -> Index { _precondition(i != endIndex, "Can't advance past endIndex") guard case .index(let i) = i._value else { _preconditionFailure("Invalid index passed to index(after:)") } let nextIndex = _base.index(after: i) guard nextIndex != _base.endIndex && _predicate(_base[nextIndex]) else { return Index(endOf: _base) } return Index(nextIndex) } @inlinable // lazy-performance public subscript(position: Index) -> Element { switch position._value { case .index(let i): return _base[i] case .pastEnd: _preconditionFailure("Index out of range") } } } extension LazyPrefixWhileCollection: LazyCollectionProtocol { } extension LazyPrefixWhileCollection: BidirectionalCollection where Base: BidirectionalCollection { @inlinable // lazy-performance public func index(before i: Index) -> Index { switch i._value { case .index(let i): _precondition(i != _base.startIndex, "Can't move before startIndex") return Index(_base.index(before: i)) case .pastEnd: // Look for the position of the last element in a non-empty // prefix(while:) collection by searching forward for a predicate // failure. // Safe to assume that `_base.startIndex != _base.endIndex`; if they // were equal, `_base.startIndex` would be used as the `endIndex` of // this collection. _internalInvariant(!_base.isEmpty) var result = _base.startIndex while true { let next = _base.index(after: result) if next == _base.endIndex || !_predicate(_base[next]) { break } result = next } return Index(result) } } }
apache-2.0
b4089d79480b893dd41b81d1775d8462
32.705036
96
0.683138
4.417727
false
false
false
false
beckasaurus/skin-ios
skin/skin/ApplicationViewController.swift
1
7156
//// //// ApplicationTableViewController //// skin //// //// Created by Becky Henderson on 8/28/17. //// Copyright © 2017 Becky Henderson. All rights reserved. //// // //import UIKit //import RealmSwift // //let applicationProductCellIdentifier = "applicationProduct" ////FIXME: not used? //let noApplicationSelectedSegue = "noApplicationSelectedSegue" //let addProductToApplicationSegue = "addProductToApplicationSegue" //let applicationUnwindSegue = "applicationUnwindSegue" // //protocol ApplicationDelegate: class { // func didAdd(application: Application) //} // ////TODO: change name? //class ApplicationViewController: UIViewController { // // weak var delegate: ApplicationDelegate? // // @IBOutlet weak var nameTextField: UITextField! // @IBOutlet weak var timeTextField: UITextField! // @IBOutlet weak var notesTextView: UITextView! // @IBOutlet weak var tableView: UITableView! // @IBOutlet weak var editDoneButton: UIButton! // // var dateFormatter: DateFormatter? // // var application: Application? // // override func viewWillAppear(_ animated: Bool) { // super.viewWillAppear(animated) // setupNavigationButtons() // setupFields() // createApplicationIfNeeded() // } // // override func viewWillDisappear(_ animated: Bool) { // super.viewWillDisappear(animated) // //FIXME: this will be called twice if we're clicking done (once when we segue, once when our view goes away) // updateApplicationFromUI() // } //} // //// MARK: set up UI //extension ApplicationViewController { // /// This adds Add/Cancel buttons to the navigation bar if the user is adding a new application, or a Back button if the application already exists. // /// This must be called before setting up a new application model. // func setupNavigationButtons() { // //new application // if (application == nil) { // navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(done)) // navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancel)) // } // } // // func setupFields() { // title = application?.name // tableView.register(UITableViewCell.self, forCellReuseIdentifier: applicationProductCellIdentifier) // // setupTimeField() // // loadUIFromApplication() // } // // func setupDatePicker() { // let datePicker = UIDatePicker() // datePicker.datePickerMode = .time // datePicker.minuteInterval = 5 // datePicker.addTarget(self, action: #selector(timeChanged(_:)), for: .valueChanged) // timeTextField.inputView = datePicker // } // // func setupDateFormatter() { // dateFormatter = DateFormatter() // dateFormatter!.dateStyle = .none // dateFormatter!.timeStyle = .short // } // // func setupTimeField() { // setupDateFormatter() // setupDatePicker() // } //} // //// MARK: Create new application //extension ApplicationViewController { // func createApplicationIfNeeded() { // if application == nil { // try! realm?.write { // //FIXME: option to choose from existing routine before creating a new application // let newApplication = Application(value: ["id" : NSUUID().uuidString, // "name" : "", // "notes" : "", // "time" : dateFormatter!.date(from: timeTextField.text ?? "") ?? Date()]) // realm?.add(newApplication) // application = newApplication // } // } // } //} // //// MARK: Load fields from Application //extension ApplicationViewController { // func loadUIFromApplication() { // loadName() // loadNotes() // loadTime() // } // // func loadName() { // nameTextField?.text = application?.name ?? "" // } // // func loadNotes() { // notesTextView?.text = application?.notes ?? "" // } // // func loadTime() { // if let applicationTime = application?.time { // timeTextField.text = dateFormatter!.string(from: applicationTime) // (timeTextField.inputView as? UIDatePicker)?.setDate(applicationTime, animated: false) // } // } //} // //// MARK: Load Application from fields //extension ApplicationViewController { // /// Note: This product list is saved as it's changed/edited so it does not need to be handled here // func updateApplicationFromUI() { // try! realm?.write { // application?.name = nameTextField.text ?? "" // application?.notes = notesTextView.text ?? "" // // if let time = timeTextField.text, // let applicationDate = dateFormatter!.date(from: time) { // application?.time = applicationDate // } // } // } //} // //// MARK: User actions //extension ApplicationViewController { // @IBAction func editDoneButtonToggled(_ sender: UIButton) { // if tableView.isEditing { // tableView.setEditing(false, animated: true) // editDoneButton.setTitle("Edit", for: .normal) // } else { // tableView.setEditing(true, animated: true) // editDoneButton.setTitle("Done", for: .normal) // } // } // // func deleteProduct(at indexPath: IndexPath) { // try! realm?.write { // let item = application!.products[indexPath.row] // realm?.delete(item) // } // } // // func timeChanged(_ sender: Any) { // let datePicker = timeTextField.inputView! as! UIDatePicker // let date = datePicker.date // timeTextField.text = dateFormatter!.string(from: date) // } // // func done(sender: UIBarButtonItem) { // updateApplicationFromUI() // delegate?.didAdd(application: application!) // performSegue(withIdentifier: applicationUnwindSegue, sender: self) // } // // func cancel(sender: UIBarButtonItem) { // application = nil // performSegue(withIdentifier: applicationUnwindSegue, sender: self) // } //} // //// MARK: UITableViewDataSource //extension ApplicationViewController: UITableViewDataSource { // func numberOfSections(in tableView: UITableView) -> Int { // return 1 // } // // func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return application?.products.count ?? 0 // } // // func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // let cell = tableView.dequeueReusableCell(withIdentifier: applicationProductCellIdentifier, for: indexPath) // let item = application!.products[indexPath.row] // cell.textLabel?.text = item.name // return cell // } // // func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // return true // } // // func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { // realm?.beginWrite() // application!.products.move(from: sourceIndexPath.row, to: destinationIndexPath.row) // try! realm?.commitWrite() // } // // func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { // if editingStyle == .delete { // deleteProduct(at: indexPath) // } // } // // override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // if segue.identifier == addProductToApplicationSegue { // let applicationProductSelectionViewController = segue.destination as! ApplicationProductSelectionViewController // applicationProductSelectionViewController.applicationProductsList = application!.products // } // } //}
mit
2f36e452b1f8ab0e0ca0fe8c31d1e69a
30.659292
150
0.701468
3.736292
false
false
false
false
aichamorro/fitness-tracker
Clients/Apple/UIGraphView/UIGraphViewTests/FatalErrorReplacement.swift
1
1429
// // FatalErrorReplacement.swift // UIGraphView // // Created by Alberto Chamorro on 27/01/2017. // Copyright © 2017 OnsetBits. All rights reserved. // import Foundation // overrides Swift global `fatalError` public func fatalError(_ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Never { FatalErrorUtil.fatalErrorClosure(message(), file, line) unreachable() } /// This is a `noreturn` function that pauses forever public func unreachable() -> Never { repeat { RunLoop.current.run() } while (true) } /// Utility functions that can replace and restore the `fatalError` global function. public struct FatalErrorUtil { // Called by the custom implementation of `fatalError`. static var fatalErrorClosure: (String, StaticString, UInt) -> Never = defaultFatalErrorClosure // backup of the original Swift `fatalError` private static let defaultFatalErrorClosure = { Swift.fatalError($0, file: $1, line: $2) } /// Replace the `fatalError` global function with something else. public static func replaceFatalError(closure: @escaping (String, StaticString, UInt) -> Never) { fatalErrorClosure = closure } /// Restore the `fatalError` global function back to the original Swift implementation public static func restoreFatalError() { fatalErrorClosure = defaultFatalErrorClosure } }
gpl-3.0
98b95d7cf5225724e9603495e2808fdf
33
124
0.69958
4.547771
false
false
false
false
Breinify/brein-api-library-ios
BreinifyApi/api/BreinRequestManager.swift
1
7731
// // Created by Marco Recchioni // Copyright (c) 2020 Breinify. All rights reserved. // import Foundation open class BreinRequestManager { /// singleton static public let shared: BreinRequestManager = { let instance = BreinRequestManager() // setup code instance.configure() return instance }() // Can't init is singleton private init() { } deinit { updateTimer?.invalidate() updateTimer = nil } // dictionary of UUID to jsonRequest (unixTimestamp, fullUrl, jsonString) var missedRequests = [String: JsonRequest]() // contains the unixTimestamp when the failure was detected var failureTime = 0.0 // contains the expiration Duration (5 minutes in seconds) var expirationDuration = 5 * 60 * 60 /// instance for processing unsent requests var updateTimer: Timer? /// contains the background interval var interval = 120.0 /// contains the delimiter between each element of the structure let kDelimiter = "°" /// contains the filename for saved requests let kRequestFileName = "BreinifyMissedRequests" /// contains the full filename for save requests let kRequestFullFileName = "BreinifyMissedRequests.txt" public func configure() { updateTimer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(sendActivityRequests), userInfo: nil, repeats: true) } @objc public func sendActivityRequests() { BreinLogger.shared.log("Breinify sendActivityRequests invoked - number of missed requests are: \(missedRequests.count)") if missedRequests.count > 0 { BreinLogger.shared.log("Breinify invoking saved activity requests") Breinify.getConfig().getBreinEngine().getRestEngine().executeSavedRequests() } } public func addMissedRequest(timeStamp: Int, fullUrl: String?, json: String?) { let jsonRequest = JsonRequest() let uuid = UUID().uuidString jsonRequest.creationTime = timeStamp jsonRequest.fullUrl = fullUrl jsonRequest.jsonBody = json missedRequests[uuid] = jsonRequest BreinLogger.shared.log("Breinify adding to queue: \(uuid)") } public func getMissedRequests() -> [String: JsonRequest] { missedRequests } public func clearMissedRequests() { missedRequests = [String: JsonRequest]() } public func status() -> String { let numberOfRequests = "# :\(missedRequests.count)" return numberOfRequests } /** Removes an entry from the missed requests dictionary */ public func removeEntry(_ key: String) { BreinLogger.shared.log("Breinify size before removeEntry is: \(missedRequests.count)") missedRequests.removeValue(forKey: key) BreinLogger.shared.log("Breinify size after removeEntry is: \(missedRequests.count)") } /** Checks if currentEntry is in time range */ public func checkIfValid(currentEntry: JsonRequest) -> Bool { let creationTime = currentEntry.creationTime let nowTime = Int(NSDate().timeIntervalSince1970) let pastTime = nowTime - expirationDuration if creationTime! > pastTime { return true } return false } /** Save the missed requested if necessary */ public func shutdown() { // deactivated now // safeMissedRequests() } /** This method saves the missed requests to file with the following structure: value-creationtime; value-fullUrl; value-jsonBody The key can be ignored because when the missed requests will be loaded a new key will be generated. */ public func safeMissedRequests() { if missedRequests.count > 0 { let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) .appendingPathComponent(kRequestFullFileName) if let outputStream = OutputStream(url: fileURL, append: true) { outputStream.open() var output = "" for (_, jsonElement) in missedRequests { output = output + "\(jsonElement.creationTime!)" + kDelimiter + jsonElement.fullUrl + kDelimiter + jsonElement.jsonBody + "\n" let bytesWritten = outputStream.write(output, maxLength: output.lengthOfBytes(using: .utf8)) if bytesWritten < 0 { BreinLogger.shared.log("Breinify write failure in safeMissedRequests") } } outputStream.close() } else { BreinLogger.shared.log("Breinify unable to open file in safeMissedRequests") } } // delete file if no entries exists if missedRequests.count == 0 { let fileManager = FileManager.default let fileName = kRequestFileName let docDirectory = try? fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) if let fileURL = docDirectory?.appendingPathComponent(fileName).appendingPathExtension("txt") { let filePathName = fileURL.path do { try fileManager.removeItem(atPath: filePathName) } catch { BreinLogger.shared.log("Breinify safeMissedRequests - could not remove file: \(filePathName)") } } } } /** This method loads the saved requests from file. Assuming the following structure: value-creationtime; value-fullUrl; value-jsonBody For each loaded line a new key will be generated. */ public func loadMissedRequests() { if missedRequests.count == 0 { let fileName = kRequestFileName let docDirectory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) if let fileURL = docDirectory?.appendingPathComponent(fileName).appendingPathExtension("txt") { // Reading back from the file var inString = "" do { inString = try String(contentsOf: fileURL) BreinLogger.shared.log("Breinify loadMissedRequests - line is: \(inString)") let fileContent = inString.components(separatedBy: .newlines) for line in fileContent { let elements = line.components(separatedBy: kDelimiter) if elements.count >= 3 { let unixTimestampAsInt: String = elements[0] let unixTimestamp = Int(unixTimestampAsInt) let fullUrl = elements[1] let jsonBody = elements[2] addMissedRequest(timeStamp: unixTimestamp!, fullUrl: fullUrl, json: jsonBody) } } } catch { BreinLogger.shared.log("Breinify loadMissedRequests - failed reading from URL: \(fileURL), Error: " + error.localizedDescription) } } } } }
mit
9f3b2ba4de137b677046045512dd6e00
30.422764
149
0.580724
5.323691
false
false
false
false
LYM-mg/DemoTest
其他功能/CoreData练习/coreData04多表关联/coreData01/CoreDataHelper.swift
1
3741
// // CoreDataHelper.swift // coreData01 // // Created by i-Techsys.com on 17/1/15. // Copyright © 2017年 i-Techsys. All rights reserved. // 一般一个数据库对应一个上下文Context import UIKit import CoreData class CoreDataHelper: NSObject { // MARK: - 便利构造方法 var modelName: String = "" // 数据库的名称 默认是App的名称 override init() { super.init() var bundlePath = Bundle.main.bundlePath bundlePath = bundlePath.components(separatedBy: "/").last! bundlePath = bundlePath.components(separatedBy: ".").first! modelName = bundlePath } convenience init(modelName: String) { self.init() self.modelName = modelName } // 这个目录用来存放应用程序Core Data存储文件,在当前事例中,会在应用程序的Document目录下生成名为“FoodPin.Coredata”文件。 // MARK: - Core Data stack @available(iOS 10.0 , *) lazy var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "self.modelName") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() lazy var applicationDocumentsDirectory: URL = { let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() //iOS9下的 Core Data stack lazy var managedObjectModel: NSManagedObjectModel = { let modelURL = Bundle.main.url(forResource: self.modelName, withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.appendingPathComponent(self.modelName + ".sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject? dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject? dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() //iOS9下的 Core Data stack结束 // MARK: - Core Data Saving support @available(iOS 10.0 , *) func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
47cc614976b4f76191edcbea3a2f420c
37.042553
120
0.64821
5.235725
false
false
false
false
Onetaway/VPNOn
VPNOnKit/VPNManager.swift
2
7129
// // VPNManager.swift // VPNOn // // Created by Lex Tang on 12/5/14. // Copyright (c) 2014 LexTang.com. All rights reserved. // import Foundation import NetworkExtension import CoreData let kAppGroupIdentifier = "group.VPNOn" final public class VPNManager { lazy var _manager: NEVPNManager = { return NEVPNManager.sharedManager()! }() lazy var _defaults: NSUserDefaults = { return NSUserDefaults(suiteName: kAppGroupIdentifier)! }() public lazy var wormhole: MMWormhole = { return MMWormhole(applicationGroupIdentifier: kAppGroupIdentifier, optionalDirectory: "wormhole") }() public var status: NEVPNStatus { get { return _manager.connection.status } } private let kVPNOnDisplayFlags = "displayFlags" public var displayFlags: Bool { get { if let value = _defaults.objectForKey(kVPNOnDisplayFlags) as! Int? { return Bool(value) } return true } set { _defaults.setObject(Int(newValue), forKey: kVPNOnDisplayFlags) _defaults.synchronize() } } public class var sharedManager : VPNManager { struct Static { static let sharedInstance : VPNManager = { let instance = VPNManager() instance._manager.loadFromPreferencesWithCompletionHandler { (error: NSError!) -> Void in if let err = error { println("Failed to load preferences: \(err.localizedDescription)") } } instance._manager.localizedDescription = "VPN On" instance._manager.enabled = true return instance }() } return Static.sharedInstance } public func connectIPSec(title: String, server: String, account: String?, group: String?, alwaysOn: Bool = true, passwordRef: NSData?, secretRef: NSData?, certificate: NSData?) { let p = NEVPNProtocolIPSec() p.authenticationMethod = NEVPNIKEAuthenticationMethod.None p.useExtendedAuthentication = true p.serverAddress = server p.disconnectOnSleep = !alwaysOn _manager.localizedDescription = "VPN On - \(title)" if let grp = group { p.localIdentifier = grp } else { p.localIdentifier = "VPN" } if let username = account { p.username = username } if let password = passwordRef { p.passwordReference = password } if let secret = secretRef { p.authenticationMethod = NEVPNIKEAuthenticationMethod.SharedSecret p.sharedSecretReference = secret } if let certficiateData = certificate { p.authenticationMethod = NEVPNIKEAuthenticationMethod.Certificate p.identityData = certficiateData } _manager.enabled = true _manager.`protocol` = p configOnDemand() _manager.saveToPreferencesWithCompletionHandler { (error: NSError!) -> Void in if let err = error { println("Failed to save profile: \(err.localizedDescription)") } else { var connectError : NSError? self._manager.connection.startVPNTunnelAndReturnError(&connectError) if let connectErr = connectError { // println("Failed to start tunnel: \(connectErr.localizedDescription)") } else { // println("VPN tunnel started.") } } } } public func connectIKEv2(title: String, server: String, account: String?, group: String?, alwaysOn: Bool = true, passwordRef: NSData?, secretRef: NSData?, certificate: NSData?) { let p = NEVPNProtocolIKEv2() p.authenticationMethod = NEVPNIKEAuthenticationMethod.None p.useExtendedAuthentication = true p.serverAddress = server p.remoteIdentifier = server p.disconnectOnSleep = !alwaysOn p.deadPeerDetectionRate = NEVPNIKEv2DeadPeerDetectionRate.Medium // TODO: Add an option into config page _manager.localizedDescription = "VPN On - \(title)" if let grp = group { p.localIdentifier = grp } else { p.localIdentifier = "VPN" } if let username = account { p.username = username } if let password = passwordRef { p.passwordReference = password } if let secret = secretRef { p.authenticationMethod = NEVPNIKEAuthenticationMethod.SharedSecret p.sharedSecretReference = secret } if let certficiateData = certificate { p.authenticationMethod = NEVPNIKEAuthenticationMethod.Certificate p.serverCertificateCommonName = server p.serverCertificateIssuerCommonName = server p.identityData = certficiateData } _manager.enabled = true _manager.`protocol` = p configOnDemand() _manager.saveToPreferencesWithCompletionHandler { (error: NSError!) -> Void in if let err = error { println("Failed to save profile: \(err.localizedDescription)") } else { var connectError : NSError? if self._manager.connection.startVPNTunnelAndReturnError(&connectError) { if let connectErr = connectError { println("Failed to start IKEv2 tunnel: \(connectErr.localizedDescription)") } else { println("IKEv2 tunnel started.") } } else { println("Failed to connect: \(connectError?.localizedDescription)") } } } } public func configOnDemand() { if onDemandDomainsArray.count > 0 && onDemand { let connectionRule = NEEvaluateConnectionRule( matchDomains: onDemandDomainsArray, andAction: NEEvaluateConnectionRuleAction.ConnectIfNeeded ) let ruleEvaluateConnection = NEOnDemandRuleEvaluateConnection() ruleEvaluateConnection.connectionRules = [connectionRule] _manager.onDemandRules = [ruleEvaluateConnection] _manager.onDemandEnabled = true } else { _manager.onDemandRules = [AnyObject]() _manager.onDemandEnabled = false } } public func disconnect() { _manager.connection.stopVPNTunnel() } public func removeProfile() { _manager.removeFromPreferencesWithCompletionHandler { (error: NSError!) -> Void in } } }
mit
54f33d81fdcfaea22737b4e780d7a0bf
31.701835
182
0.562491
5.60456
false
false
false
false
netprotections/atonecon-ios
AtoneConDemo/Define/String.swift
1
931
// // String.swift // AtoneConDemo // // Created by Pham Ngoc Hanh on 6/29/17. // Copyright © 2017 AsianTech Inc. All rights reserved. // import Foundation extension Define.String { static let homeTitle = "Atone".localized() static let resetAuthen = "resetAuthen".localized() static let authenTokenTitle = "authenTokenTitle".localized() static let atoneButtonTitle = "atoneButtonTitle".localized() static let tokenKey = "userToken" static let serviceName = "AtoneConWebView" static let textFieldPlaceHolder = "textFieldPlaceHolder".localized() static let okay = "okay".localized() static let finished = "finished".localized() static let failed = "failed".localized() static let cancel = "cancel".localized() } extension String { internal func localized(_ comment: String = "") -> String { return NSLocalizedString(self, bundle: Bundle.main, comment: comment) } }
mit
d555bd71c5838e0a20e27a4c14f9756f
31.068966
77
0.702151
4.061135
false
false
false
false
practicalswift/swift
test/SILGen/keypaths_multi_file.swift
32
1180
// RUN: %empty-directory(%t) // RUN: %target-build-swift -module-name keypaths_resilient -emit-module %S/Inputs/keypaths_multi_file_c.swift -emit-module-path %t/keypaths_resilient.swiftmodule // RUN: %target-swift-emit-silgen -module-name keypaths -primary-file %s %S/Inputs/keypaths_multi_file_b.swift -I %t | %FileCheck %s // RUN: %target-swift-emit-silgen -module-name keypaths %s -primary-file %S/Inputs/keypaths_multi_file_b.swift -I %t | %FileCheck --check-prefix=DEFINITION %s import keypaths_resilient func foo(x: Int) -> KeyPath<A, Int> { switch x { case 0: return \A.x default: return \A.[0] } return \A.x } // A.x setter // CHECK-LABEL: sil hidden_external @$s8keypaths1AV1xSivs // DEFINITION-LABEL: sil hidden [ossa] @$s8keypaths1AV1xSivs // A.subscript setter // CHECK-LABEL: sil hidden_external @$s8keypaths1AVyS2icis // DEFINITION-LABEL: sil hidden [ossa] @$s8keypaths1AVyS2icis func bar<T>(_: T) { _ = \C<T>.b _ = \C<T>[0] _ = \D<T>.b _ = \D<T>[0] _ = \P.b // FIXME: crashes // _ = \P[0] } // https://bugs.swift.org/browse/SR-8643 class MM<T: P> : PP {} func foo<T3: BB, T4: MM<T3>>(t: T3, u: T4) { let _ = \CC<T4>.x }
apache-2.0
8286ec2559ece33c9ac9a5540274bcf4
25.222222
162
0.650847
2.582057
false
false
false
false
oskarpearson/rileylink_ios
MinimedKit/RFTools.swift
1
1691
// // RFTools.swift // RileyLink // // Created by Pete Schwamb on 2/27/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation private let codesRev:Dictionary<Int, UInt8> = [21: 0, 49: 1, 50: 2, 35: 3, 52: 4, 37: 5, 38: 6, 22: 7, 26: 8, 25: 9, 42: 10, 11: 11, 44: 12, 13: 13, 14: 14, 28: 15] private let codes = [21,49,50,35,52,37,38,22,26,25,42,11,44,13,14,28] public func decode4b6b(_ rawData: Data) -> Data? { var buffer = [UInt8]() var availBits = 0 var x = 0 for byte in rawData { x = (x << 8) + Int(byte) availBits += 8 if availBits >= 12 { guard let hiNibble = codesRev[x >> (availBits - 6)], let loNibble = codesRev[(x >> (availBits - 12)) & 0b111111] else { return nil } let decoded = UInt8((hiNibble << 4) + loNibble) buffer.append(decoded) availBits -= 12 x = x & (0xffff >> (16-availBits)) } } return Data(bytes: buffer) } public func encode4b6b(_ rawData: Data) -> Data { var buffer = [UInt8]() var acc = 0x0 var bitcount = 0 for byte in rawData { acc <<= 6 acc |= codes[Int(byte >> 4)] bitcount += 6 acc <<= 6 acc |= codes[Int(byte & 0x0f)] bitcount += 6 while bitcount >= 8 { buffer.append(UInt8(acc >> (bitcount-8)) & 0xff) bitcount -= 8 acc &= (0xffff >> (16-bitcount)) } } if bitcount > 0 { acc <<= (8-bitcount) buffer.append(UInt8(acc) & 0xff) } return Data(bytes: buffer) }
mit
1b9c98ec4077f53fd3444e581840cdbb
25.825397
164
0.495266
3.243762
false
false
false
false