repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
BeamNG/remotecontrol
refs/heads/master
iOS/BeamNG.SteeringDevice/BeamNG.SteeringDevice/PTUtil.swift
isc
1
// // PTUtil.swift // BeamNG.SteeringDevice // // Created by Pawel Sulik on 01.09.14. // Copyright (c) 2014 28Apps. All rights reserved. // import Foundation class PTUtil { class func lerp(_ t: Double, a: Double, b: Double) -> Double { return (b-a)*t + a; } class func clamp01(_ val: Double) -> Double { var retVal = val; if(val < 0.0) { retVal = 0.0; } else if(val > 1.0) { retVal = 1.0; } return retVal; } class func clamp(_ val: Double, min: Double, max: Double) -> Double { var retVal = val; if(val < min) { retVal = min; } else if(val > max) { retVal = max; } return retVal; } class func delay(_ delay:Double, closure:@escaping ()->()) { DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure) } class func dispatch(_ delay:Double, closure:@escaping ()->(), thread: DispatchQueue!) { var threadToRun = thread; if(threadToRun == nil) { threadToRun = DispatchQueue.main; } threadToRun?.asyncAfter( deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure); } class func saveToDocuments(_ filename: String, content: String)->Bool { let dirs : [String]? = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true) /*for(var i = 0; i < dirs!.count; i++) { println(dirs![i]); }*/ if (dirs != nil) { let directories:[String] = dirs!; let dir = directories[0]; //documents directory let path = (dir as NSString).appendingPathComponent(filename); do { //let text = "some text"; //writing try content.write(toFile: path, atomically: false, encoding: String.Encoding.utf8) } catch _ { }; //reading //let text2 = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil) //println(text2); return true; } return false; } class func loadFromDocuments(_ filename: String)->String? { let dirs : [String]? = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true) /*for(var i = 0; i < dirs!.count; i++) { println(dirs![i]); }*/ if (dirs != nil) { let directories:[String] = dirs!; let dir = directories[0]; //documents directory let path = (dir as NSString).appendingPathComponent(filename); //let text = "some text"; //writing //content.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil); //reading //let text2 = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil) let text2 = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue); //let text2 = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil) return text2 as? String; //println(text2); } return nil; } }
c4b8e9779a19e077f4bc26eb625f5c9b
30.846154
172
0.543478
false
false
false
false
codestergit/swift
refs/heads/master
test/SILGen/objc_bridging.swift
apache-2.0
2
// RUN: rm -rf %t && mkdir -p %t // RUN: %build-silgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-module -o %t -I %S/../Inputs/ObjCBridging %S/../Inputs/ObjCBridging/Appliances.swift // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -I %S/../Inputs/ObjCBridging -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-cpu --check-prefix=CHECK-%target-os-%target-cpu // REQUIRES: objc_interop import Foundation import Appliances func getDescription(_ o: NSObject) -> String { return o.description } // CHECK-LABEL: sil hidden @_T013objc_bridging14getDescription{{.*}}F // CHECK: bb0([[ARG:%.*]] : $NSObject): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[DESCRIPTION:%.*]] = class_method [volatile] [[BORROWED_ARG]] : $NSObject, #NSObject.description!getter.1.foreign // CHECK: [[OPT_BRIDGED:%.*]] = apply [[DESCRIPTION]]([[BORROWED_ARG]]) // CHECK: switch_enum [[OPT_BRIDGED]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[BRIDGED:%.*]] : $NSString): // CHECK-NOT: unchecked_enum_data // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]], // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]] // CHECK: br [[CONT_BB:bb[0-9]+]]([[OPT_NATIVE]] : $Optional<String>) // // CHECK: [[NONE_BB]]: // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.none!enumelt // CHECK: br [[CONT_BB]]([[OPT_NATIVE]] : $Optional<String>) // // CHECK: [[CONT_BB]]([[OPT_NATIVE:%.*]] : $Optional<String>): // CHECK: switch_enum [[OPT_NATIVE]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[NONE_BB]]: // CHECK: unreachable // // CHECK: [[SOME_BB]]([[NATIVE:%.*]] : $String): // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[NATIVE]] // CHECK:} func getUppercaseString(_ s: NSString) -> String { return s.uppercase() } // CHECK-LABEL: sil hidden @_T013objc_bridging18getUppercaseString{{.*}}F // CHECK: bb0([[ARG:%.*]] : $NSString): // -- The 'self' argument of NSString methods doesn't bridge. // CHECK-NOT: function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK-NOT: function_ref @swift_StringToNSString // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[UPPERCASE_STRING:%.*]] = class_method [volatile] [[BORROWED_ARG]] : $NSString, #NSString.uppercase!1.foreign // CHECK: [[OPT_BRIDGED:%.*]] = apply [[UPPERCASE_STRING]]([[BORROWED_ARG]]) : $@convention(objc_method) (NSString) -> @autoreleased Optional<NSString> // CHECK: switch_enum [[OPT_BRIDGED]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // // CHECK: [[SOME_BB]]([[BRIDGED:%.*]] : // CHECK-NOT: unchecked_enum_data // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]] // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]] // CHECK: br [[CONT_BB:bb[0-9]+]]([[OPT_NATIVE]] : $Optional<String>) // // CHECK: [[NONE_BB]]: // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.none!enumelt // CHECK: br [[CONT_BB]]([[OPT_NATIVE]] : $Optional<String>) // // CHECK: [[CONT_BB]]([[OPT_NATIVE:%.*]] : $Optional<String>): // CHECK: switch_enum [[OPT_NATIVE]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[NONE_BB]]: // CHECK: unreachable // // CHECK: [[SOME_BB]]([[NATIVE:%.*]] : $String): // CHECK: return [[NATIVE]] // CHECK: } // @interface Foo -(void) setFoo: (NSString*)s; @end func setFoo(_ f: Foo, s: String) { var s = s f.setFoo(s) } // CHECK-LABEL: sil hidden @_T013objc_bridging6setFoo{{.*}}F // CHECK: bb0([[ARG0:%.*]] : $Foo, {{%.*}} : $String): // CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK: [[SET_FOO:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setFoo!1.foreign // CHECK: [[NV:%.*]] = load // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NV]] // CHECK: switch_enum [[OPT_NATIVE]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[NATIVE:%.*]] : $String): // CHECK-NOT: unchecked_enum_data // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_NATIVE:%.*]] = begin_borrow [[NATIVE]] // CHECK: [[BRIDGED:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_NATIVE]]) // CHECK: [[OPT_BRIDGED:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: end_borrow [[BORROWED_NATIVE]] from [[NATIVE]] // CHECK: destroy_value [[NATIVE]] // CHECK: br [[CONT_BB:bb[0-9]+]]([[OPT_BRIDGED]] : $Optional<NSString>) // // CHECK: [[NONE_BB]]: // CHECK: [[OPT_BRIDGED:%.*]] = enum $Optional<NSString>, #Optional.none!enumelt // CHECK: br [[CONT_BB]]([[OPT_BRIDGED]] : $Optional<NSString>) // // CHECK: [[CONT_BB]]([[OPT_BRIDGED:%.*]] : $Optional<NSString>): // CHECK: apply [[SET_FOO]]([[OPT_BRIDGED]], [[BORROWED_ARG0]]) : $@convention(objc_method) (Optional<NSString>, Foo) -> () // CHECK: destroy_value [[OPT_BRIDGED]] // CHECK: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK: destroy_value [[ARG0]] // CHECK: } // @interface Foo -(BOOL) zim; @end func getZim(_ f: Foo) -> Bool { return f.zim() } // CHECK-ios-i386-LABEL: sil hidden @_T013objc_bridging6getZim{{.*}}F // CHECK-ios-i386: bb0([[SELF:%.*]] : $Foo): // CHECK-ios-i386: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-ios-i386: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Bool // CHECK-ios-i386: [[OBJC_BOOL:%.*]] = apply [[METHOD]]([[BORROWED_SELF]]) : $@convention(objc_method) (Foo) -> ObjCBool // CHECK-ios-i386: [[CONVERT:%.*]] = function_ref @swift_ObjCBoolToBool : $@convention(thin) (ObjCBool) -> Bool // CHECK-ios-i386: [[SWIFT_BOOL:%.*]] = apply [[CONVERT]]([[OBJC_BOOL]]) : $@convention(thin) (ObjCBool) -> Bool // CHECK-ios-i386: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK-ios-i386: return [[SWIFT_BOOL]] : $Bool // CHECK-ios-i386: } // CHECK-watchos-i386-LABEL: sil hidden @_T013objc_bridging6getZim{{.*}}F // CHECK-watchos-i386: bb0([[SELF:%.*]] : $Foo): // CHECK-watchos-i386: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-watchos-i386: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Boo // CHECK-watchos-i386: [[BOOL:%.*]] = apply [[METHOD]]([[BORROWED_SELF]]) : $@convention(objc_method) (Foo) -> Bool // CHECK-watchos-i386: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK-watchos-i386: return [[BOOL]] : $Bool // CHECK-watchos-i386: } // CHECK-macosx-x86_64-LABEL: sil hidden @_T013objc_bridging6getZim{{.*}}F // CHECK-macosx-x86_64: bb0([[SELF:%.*]] : $Foo): // CHECK-macosx-x86_64: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-macosx-x86_64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Bool // CHECK-macosx-x86_64: [[OBJC_BOOL:%.*]] = apply [[METHOD]]([[BORROWED_SELF]]) : $@convention(objc_method) (Foo) -> ObjCBool // CHECK-macosx-x86_64: [[CONVERT:%.*]] = function_ref @swift_ObjCBoolToBool : $@convention(thin) (ObjCBool) -> Bool // CHECK-macosx-x86_64: [[SWIFT_BOOL:%.*]] = apply [[CONVERT]]([[OBJC_BOOL]]) : $@convention(thin) (ObjCBool) -> Bool // CHECK-macosx-x86_64: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK-macosx-x86_64: return [[SWIFT_BOOL]] : $Bool // CHECK-macosx-x86_64: } // CHECK-ios-x86_64-LABEL: sil hidden @_T013objc_bridging6getZim{{.*}}F // CHECK-ios-x86_64: bb0([[SELF:%.*]] : $Foo): // CHECK-ios-x86_64: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-ios-x86_64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Boo // CHECK-ios-x86_64: [[BOOL:%.*]] = apply [[METHOD]]([[BORROWED_SELF]]) : $@convention(objc_method) (Foo) -> Bool // CHECK-ios-x86_64: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK-ios-x86_64: return [[BOOL]] : $Bool // CHECK-ios-x86_64: } // CHECK-arm64-LABEL: sil hidden @_T013objc_bridging6getZim{{.*}}F // CHECK-arm64: bb0([[SELF:%.*]] : $Foo): // CHECK-arm64: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-arm64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Boo // CHECK-arm64: [[BOOL:%.*]] = apply [[METHOD]]([[BORROWED_SELF]]) : $@convention(objc_method) (Foo) -> Bool // CHECK-arm64: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK-arm64: return [[BOOL]] : $Bool // CHECK-arm64: } // @interface Foo -(void) setZim: (BOOL)b; @end func setZim(_ f: Foo, b: Bool) { f.setZim(b) } // CHECK-ios-i386-LABEL: sil hidden @_T013objc_bridging6setZim{{.*}}F // CHECK-ios-i386: bb0([[ARG0:%.*]] : $Foo, [[ARG1:%.*]] : $Bool): // CHECK-ios-i386: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK-ios-i386: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZim!1.foreign // CHECK-ios-i386: [[CONVERT:%.*]] = function_ref @swift_BoolToObjCBool : $@convention(thin) (Bool) -> ObjCBool // CHECK-ios-i386: [[OBJC_BOOL:%.*]] = apply [[CONVERT]]([[ARG1]]) : $@convention(thin) (Bool) -> ObjCBool // CHECK-ios-i386: apply [[METHOD]]([[OBJC_BOOL]], [[BORROWED_ARG0]]) : $@convention(objc_method) (ObjCBool, Foo) -> () // CHECK-ios-i386: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK-ios-i386: destroy_value [[ARG0]] // CHECK-ios-i386: } // CHECK-macosx-x86_64-LABEL: sil hidden @_T013objc_bridging6setZim{{.*}}F // CHECK-macosx-x86_64: bb0([[ARG0:%.*]] : $Foo, [[ARG1:%.*]] : $Bool): // CHECK-macosx-x86_64: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK-macosx-x86_64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZim!1.foreign // CHECK-macosx-x86_64: [[CONVERT:%.*]] = function_ref @swift_BoolToObjCBool : $@convention(thin) (Bool) -> ObjCBool // CHECK-macosx-x86_64: [[OBJC_BOOL:%.*]] = apply [[CONVERT]]([[ARG1]]) : $@convention(thin) (Bool) -> ObjCBool // CHECK-macosx-x86_64: apply [[METHOD]]([[OBJC_BOOL]], [[BORROWED_ARG0]]) : $@convention(objc_method) (ObjCBool, Foo) -> () // CHECK-macosx-x86_64: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK-macosx-x86_64: destroy_value [[ARG0]] // CHECK-macosx-x86_64: } // CHECK-ios-x86_64-LABEL: sil hidden @_T013objc_bridging6setZim{{.*}}F // CHECK-ios-x86_64: bb0([[ARG0:%.*]] : $Foo, [[ARG1:%.*]] : $Bool): // CHECK-ios-x86_64: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK-ios-x86_64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZim!1.foreign // CHECK-ios-x86_64: apply [[METHOD]]([[ARG1]], [[BORROWED_ARG0]]) : $@convention(objc_method) (Bool, Foo) -> () // CHECK-ios-x86_64: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK-ios-x86_64: destroy_value [[ARG0]] // CHECK-ios-x86_64: } // CHECK-arm64-LABEL: sil hidden @_T013objc_bridging6setZim{{.*}}F // CHECK-arm64: bb0([[ARG0:%.*]] : $Foo, [[ARG1:%.*]] : $Bool): // CHECK-arm64: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK-arm64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZim!1.foreign // CHECK-arm64: apply [[METHOD]]([[ARG1]], [[BORROWED_ARG0]]) : $@convention(objc_method) (Bool, Foo) -> () // CHECK-arm64: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK-arm64: destroy_value [[ARG0]] // CHECK-arm64: } // CHECK-watchos-i386-LABEL: sil hidden @_T013objc_bridging6setZim{{.*}}F // CHECK-watchos-i386: bb0([[ARG0:%.*]] : $Foo, [[ARG1:%.*]] : $Bool): // CHECK-watchos-i386: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK-watchos-i386: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZim!1.foreign // CHECK-watchos-i386: apply [[METHOD]]([[ARG1]], [[BORROWED_ARG0]]) : $@convention(objc_method) (Bool, Foo) -> () // CHECK-watchos-i386: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK-watchos-i386: destroy_value [[ARG0]] // CHECK-watchos-i386: } // @interface Foo -(_Bool) zang; @end func getZang(_ f: Foo) -> Bool { return f.zang() } // CHECK-LABEL: sil hidden @_T013objc_bridging7getZangSbSo3FooCF // CHECK: bb0([[ARG:%.*]] : $Foo) // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG]] : $Foo, #Foo.zang!1.foreign // CHECK: [[BOOL:%.*]] = apply [[METHOD]]([[BORROWED_ARG]]) : $@convention(objc_method) (Foo) -> Bool // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[BOOL]] // @interface Foo -(void) setZang: (_Bool)b; @end func setZang(_ f: Foo, _ b: Bool) { f.setZang(b) } // CHECK-LABEL: sil hidden @_T013objc_bridging7setZangySo3FooC_SbtF // CHECK: bb0([[ARG0:%.*]] : $Foo, [[ARG1:%.*]] : $Bool): // CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZang!1.foreign // CHECK: apply [[METHOD]]([[ARG1]], [[BORROWED_ARG0]]) : $@convention(objc_method) (Bool, Foo) -> () // CHECK: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK: destroy_value [[ARG0]] // CHECK: } // end sil function '_T013objc_bridging7setZangySo3FooC_SbtF' // NSString *bar(void); func callBar() -> String { return bar() } // CHECK-LABEL: sil hidden @_T013objc_bridging7callBar{{.*}}F // CHECK: bb0: // CHECK: [[BAR:%.*]] = function_ref @bar // CHECK: [[OPT_BRIDGED:%.*]] = apply [[BAR]]() : $@convention(c) () -> @autoreleased Optional<NSString> // CHECK: switch_enum [[OPT_BRIDGED]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // CHECK: [[SOME_BB]]([[BRIDGED:%.*]] : $NSString): // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]] // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]] // CHECK: bb5([[NATIVE:%.*]] : $String): // CHECK: return [[NATIVE]] // CHECK: } // void setBar(NSString *s); func callSetBar(_ s: String) { var s = s setBar(s) } // CHECK-LABEL: sil hidden @_T013objc_bridging10callSetBar{{.*}}F // CHECK: bb0({{%.*}} : $String): // CHECK: [[SET_BAR:%.*]] = function_ref @setBar // CHECK: [[NV:%.*]] = load // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NV]] // CHECK: switch_enum [[OPT_NATIVE]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // CHECK: [[SOME_BB]]([[NATIVE:%.*]] : $String): // CHECK-NOT: unchecked_enum_data // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_NATIVE:%.*]] = begin_borrow [[NATIVE]] // CHECK: [[BRIDGED:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_NATIVE]]) // CHECK: = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: end_borrow [[BORROWED_NATIVE]] from [[NATIVE]] // CHECK: bb3([[OPT_BRIDGED:%.*]] : $Optional<NSString>): // CHECK: apply [[SET_BAR]]([[OPT_BRIDGED]]) // CHECK: destroy_value [[OPT_BRIDGED]] // CHECK: } var NSS: NSString // -- NSString methods don't convert 'self' extension NSString { var nsstrFakeProp: NSString { get { return NSS } set {} } // CHECK-LABEL: sil hidden [thunk] @_T0So8NSStringC13objc_bridgingE13nsstrFakePropABfgTo // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } // CHECK-LABEL: sil hidden [thunk] @_T0So8NSStringC13objc_bridgingE13nsstrFakePropABfsTo // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } func nsstrResult() -> NSString { return NSS } // CHECK-LABEL: sil hidden [thunk] @_T0So8NSStringC13objc_bridgingE11nsstrResultAByFTo // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } func nsstrArg(_ s: NSString) { } // CHECK-LABEL: sil hidden [thunk] @_T0So8NSStringC13objc_bridgingE8nsstrArgyABFTo // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } } class Bas : NSObject { // -- Bridging thunks for String properties convert between NSString var strRealProp: String = "Hello" // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11strRealPropSSfgTo : $@convention(objc_method) (Bas) -> @autoreleased NSString { // CHECK: bb0([[THIS:%.*]] : $Bas): // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] : $Bas // CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK: // function_ref objc_bridging.Bas.strRealProp.getter // CHECK: [[PROPIMPL:%.*]] = function_ref @_T013objc_bridging3BasC11strRealPropSSfg // CHECK: [[PROP_COPY:%.*]] = apply [[PROPIMPL]]([[BORROWED_THIS_COPY]]) : $@convention(method) (@guaranteed Bas) -> @owned String // CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK: destroy_value [[THIS_COPY]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_PROP_COPY:%.*]] = begin_borrow [[PROP_COPY]] // CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_PROP_COPY]]) // CHECK: end_borrow [[BORROWED_PROP_COPY]] from [[PROP_COPY]] // CHECK: destroy_value [[PROP_COPY]] // CHECK: return [[NSSTR]] // CHECK: } // CHECK-LABEL: sil hidden @_T013objc_bridging3BasC11strRealPropSSfg // CHECK: [[PROP_ADDR:%.*]] = ref_element_addr %0 : {{.*}}, #Bas.strRealProp // CHECK: [[PROP:%.*]] = load [copy] [[PROP_ADDR]] // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11strRealPropSSfsTo : $@convention(objc_method) (NSString, Bas) -> () { // CHECK: bb0([[VALUE:%.*]] : $NSString, [[THIS:%.*]] : $Bas): // CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[VALUE_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[VALUE_COPY]] // CHECK: [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[VALUE_BOX]] // CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK: [[SETIMPL:%.*]] = function_ref @_T013objc_bridging3BasC11strRealPropSSfs // CHECK: apply [[SETIMPL]]([[STR]], [[BORROWED_THIS_COPY]]) // CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK: destroy_value [[THIS_COPY]] // CHECK: } // end sil function '_T013objc_bridging3BasC11strRealPropSSfsTo' // CHECK-LABEL: sil hidden @_T013objc_bridging3BasC11strRealPropSSfs // CHECK: bb0(%0 : $String, %1 : $Bas): // CHECK: [[STR_ADDR:%.*]] = ref_element_addr %1 : {{.*}}, #Bas.strRealProp // CHECK: assign {{.*}} to [[STR_ADDR]] // CHECK: } var strFakeProp: String { get { return "" } set {} } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11strFakePropSSfgTo : $@convention(objc_method) (Bas) -> @autoreleased NSString { // CHECK: bb0([[THIS:%.*]] : $Bas): // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK: [[GETTER:%.*]] = function_ref @_T013objc_bridging3BasC11strFakePropSSfg // CHECK: [[STR:%.*]] = apply [[GETTER]]([[BORROWED_THIS_COPY]]) // CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK: destroy_value [[THIS_COPY]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_STR:%.*]] = begin_borrow [[STR]] // CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_STR]]) // CHECK: end_borrow [[BORROWED_STR]] from [[STR]] // CHECK: destroy_value [[STR]] // CHECK: return [[NSSTR]] // CHECK: } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11strFakePropSSfsTo : $@convention(objc_method) (NSString, Bas) -> () { // CHECK: bb0([[NSSTR:%.*]] : $NSString, [[THIS:%.*]] : $Bas): // CHECK: [[NSSTR_COPY:%.*]] = copy_value [[NSSTR]] // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR_COPY]] // CHECK: [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[NSSTR_BOX]] // CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK: [[SETTER:%.*]] = function_ref @_T013objc_bridging3BasC11strFakePropSSfs // CHECK: apply [[SETTER]]([[STR]], [[BORROWED_THIS_COPY]]) // CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK: destroy_value [[THIS_COPY]] // CHECK: } // end sil function '_T013objc_bridging3BasC11strFakePropSSfsTo' // -- Bridging thunks for explicitly NSString properties don't convert var nsstrRealProp: NSString var nsstrFakeProp: NSString { get { return NSS } set {} } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC13nsstrRealPropSo8NSStringCfgTo : $@convention(objc_method) (Bas) -> @autoreleased NSString { // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC13nsstrRealPropSo8NSStringCfsTo : $@convention(objc_method) (NSString, Bas) -> // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } // -- Bridging thunks for String methods convert between NSString func strResult() -> String { return "" } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC9strResultSSyFTo // CHECK: bb0([[THIS:%.*]] : $Bas): // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK: [[METHOD:%.*]] = function_ref @_T013objc_bridging3BasC9strResultSSyF // CHECK: [[STR:%.*]] = apply [[METHOD]]([[BORROWED_THIS_COPY]]) // CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK: destroy_value [[THIS_COPY]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_STR:%.*]] = begin_borrow [[STR]] // CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_STR]]) // CHECK: end_borrow [[BORROWED_STR]] from [[STR]] // CHECK: destroy_value [[STR]] // CHECK: return [[NSSTR]] // CHECK: } func strArg(_ s: String) { } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC6strArgySSFTo // CHECK: bb0([[NSSTR:%.*]] : $NSString, [[THIS:%.*]] : $Bas): // CHECK: [[NSSTR_COPY:%.*]] = copy_value [[NSSTR]] // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR_COPY]] // CHECK: [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[NSSTR_BOX]] // CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK: [[METHOD:%.*]] = function_ref @_T013objc_bridging3BasC6strArgySSF // CHECK: apply [[METHOD]]([[STR]], [[BORROWED_THIS_COPY]]) // CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK: destroy_value [[THIS_COPY]] // CHECK: } // end sil function '_T013objc_bridging3BasC6strArgySSFTo' // -- Bridging thunks for explicitly NSString properties don't convert func nsstrResult() -> NSString { return NSS } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11nsstrResultSo8NSStringCyFTo // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } func nsstrArg(_ s: NSString) { } // CHECK-LABEL: sil hidden @_T013objc_bridging3BasC8nsstrArgySo8NSStringCF // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } init(str: NSString) { nsstrRealProp = str super.init() } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC8arrayArgySays9AnyObject_pGFTo : $@convention(objc_method) (NSArray, Bas) -> () // CHECK: bb0([[NSARRAY:%[0-9]+]] : $NSArray, [[SELF:%[0-9]+]] : $Bas): // CHECK: [[NSARRAY_COPY:%.*]] = copy_value [[NSARRAY]] : $NSArray // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Bas // CHECK: [[CONV_FN:%[0-9]+]] = function_ref @_T0Sa10FoundationE36_unconditionallyBridgeFromObjectiveCSayxGSo7NSArrayCSgFZ // CHECK: [[OPT_NSARRAY:%[0-9]+]] = enum $Optional<NSArray>, #Optional.some!enumelt.1, [[NSARRAY_COPY]] : $NSArray // CHECK: [[ARRAY_META:%[0-9]+]] = metatype $@thin Array<AnyObject>.Type // CHECK: [[ARRAY:%[0-9]+]] = apply [[CONV_FN]]<AnyObject>([[OPT_NSARRAY]], [[ARRAY_META]]) // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_T013objc_bridging3BasC8arrayArgySays9AnyObject_pGF : $@convention(method) (@owned Array<AnyObject>, @guaranteed Bas) -> () // CHECK: [[RESULT:%[0-9]+]] = apply [[SWIFT_FN]]([[ARRAY]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Array<AnyObject>, @guaranteed Bas) -> () // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] : $Bas // CHECK: return [[RESULT]] : $() func arrayArg(_ array: [AnyObject]) { } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11arrayResultSays9AnyObject_pGyFTo : $@convention(objc_method) (Bas) -> @autoreleased NSArray // CHECK: bb0([[SELF:%[0-9]+]] : $Bas): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Bas // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_T013objc_bridging3BasC11arrayResultSays9AnyObject_pGyF : $@convention(method) (@guaranteed Bas) -> @owned Array<AnyObject> // CHECK: [[ARRAY:%[0-9]+]] = apply [[SWIFT_FN]]([[BORROWED_SELF_COPY]]) : $@convention(method) (@guaranteed Bas) -> @owned Array<AnyObject> // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: [[CONV_FN:%[0-9]+]] = function_ref @_T0Sa10FoundationE19_bridgeToObjectiveCSo7NSArrayCyF // CHECK: [[BORROWED_ARRAY:%.*]] = begin_borrow [[ARRAY]] // CHECK: [[NSARRAY:%[0-9]+]] = apply [[CONV_FN]]<AnyObject>([[BORROWED_ARRAY]]) : $@convention(method) <τ_0_0> (@guaranteed Array<τ_0_0>) -> @owned NSArray // CHECK: end_borrow [[BORROWED_ARRAY]] from [[ARRAY]] // CHECK: destroy_value [[ARRAY]] // CHECK: return [[NSARRAY]] func arrayResult() -> [AnyObject] { return [] } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC9arrayPropSaySSGfgTo : $@convention(objc_method) (Bas) -> @autoreleased NSArray // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC9arrayPropSaySSGfsTo : $@convention(objc_method) (NSArray, Bas) -> () var arrayProp: [String] = [] } // CHECK-LABEL: sil hidden @_T013objc_bridging16applyStringBlockS3SXB_SS1xtF func applyStringBlock(_ f: @convention(block) (String) -> String, x: String) -> String { // CHECK: bb0([[BLOCK:%.*]] : $@convention(block) (NSString) -> @autoreleased NSString, [[STRING:%.*]] : $String): // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK: [[BORROWED_BLOCK_COPY:%.*]] = begin_borrow [[BLOCK_COPY]] // CHECK: [[BLOCK_COPY_COPY:%.*]] = copy_value [[BORROWED_BLOCK_COPY]] // CHECK: [[BORROWED_STRING:%.*]] = begin_borrow [[STRING]] // CHECK: [[STRING_COPY:%.*]] = copy_value [[BORROWED_STRING]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_STRING_COPY:%.*]] = begin_borrow [[STRING_COPY]] // CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_STRING_COPY]]) : $@convention(method) (@guaranteed String) // CHECK: end_borrow [[BORROWED_STRING_COPY]] from [[STRING_COPY]] // CHECK: destroy_value [[STRING_COPY]] // CHECK: [[RESULT_NSSTR:%.*]] = apply [[BLOCK_COPY_COPY]]([[NSSTR]]) : $@convention(block) (NSString) -> @autoreleased NSString // CHECK: destroy_value [[NSSTR]] // CHECK: [[FINAL_BRIDGE:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[OPTIONAL_NSSTR:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[RESULT_NSSTR]] // CHECK: [[RESULT:%.*]] = apply [[FINAL_BRIDGE]]([[OPTIONAL_NSSTR]], {{.*}}) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String // CHECK: destroy_value [[BLOCK_COPY_COPY]] // CHECK: destroy_value [[STRING]] // CHECK: destroy_value [[BLOCK_COPY]] // CHECK: destroy_value [[BLOCK]] // CHECK: return [[RESULT]] : $String return f(x) } // CHECK: } // end sil function '_T013objc_bridging16applyStringBlockS3SXB_SS1xtF' // CHECK-LABEL: sil hidden @_T013objc_bridging15bridgeCFunction{{.*}}F func bridgeCFunction() -> (String!) -> (String!) { // CHECK: [[THUNK:%.*]] = function_ref @_T0SC18NSStringFromStringSQySSGABFTO : $@convention(thin) (@owned Optional<String>) -> @owned Optional<String> // CHECK: [[THICK:%.*]] = thin_to_thick_function [[THUNK]] // CHECK: return [[THICK]] return NSStringFromString } func forceNSArrayMembers() -> (NSArray, NSArray) { let x = NSArray(objects: nil, count: 0) return (x, x) } // Check that the allocating initializer shim for initializers that take pointer // arguments lifetime-extends the bridged pointer for the right duration. // <rdar://problem/16738050> // CHECK-LABEL: sil shared [serializable] @_T0So7NSArrayCABSQySPys9AnyObject_pSgGG7objects_s5Int32V5counttcfC // CHECK: [[SELF:%.*]] = alloc_ref_dynamic // CHECK: [[METHOD:%.*]] = function_ref @_T0So7NSArrayCABSQySPys9AnyObject_pSgGG7objects_s5Int32V5counttcfcTO // CHECK: [[RESULT:%.*]] = apply [[METHOD]] // CHECK: return [[RESULT]] // Check that type lowering preserves the bool/BOOL distinction when bridging // imported C functions. // CHECK-ios-i386-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF // CHECK-ios-i386: function_ref @useBOOL : $@convention(c) (ObjCBool) -> () // CHECK-ios-i386: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-ios-i386: function_ref @getBOOL : $@convention(c) () -> ObjCBool // CHECK-ios-i386: function_ref @getBool : $@convention(c) () -> Bool // CHECK-macosx-x86_64-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF // CHECK-macosx-x86_64: function_ref @useBOOL : $@convention(c) (ObjCBool) -> () // CHECK-macosx-x86_64: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-macosx-x86_64: function_ref @getBOOL : $@convention(c) () -> ObjCBool // CHECK-macosx-x86_64: function_ref @getBool : $@convention(c) () -> Bool // FIXME: no distinction on x86_64, arm64 or watchos-i386, since SILGen looks // at the underlying Clang decl of the bridged decl to decide whether it needs // bridging. // // CHECK-watchos-i386-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF // CHECK-watchos-i386: function_ref @useBOOL : $@convention(c) (Bool) -> () // CHECK-watchos-i386: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-watchos-i386: function_ref @getBOOL : $@convention(c) () -> Bool // CHECK-watchos-i386: function_ref @getBool : $@convention(c) () -> Bool // CHECK-ios-x86_64-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF // CHECK-ios-x86_64: function_ref @useBOOL : $@convention(c) (Bool) -> () // CHECK-ios-x86_64: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-ios-x86_64: function_ref @getBOOL : $@convention(c) () -> Bool // CHECK-ios-x86_64: function_ref @getBool : $@convention(c) () -> Bool // CHECK-arm64-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF // CHECK-arm64: function_ref @useBOOL : $@convention(c) (Bool) -> () // CHECK-arm64: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-arm64: function_ref @getBOOL : $@convention(c) () -> Bool // CHECK-arm64: function_ref @getBool : $@convention(c) () -> Bool func bools(_ x: Bool) -> (Bool, Bool) { useBOOL(x) useBool(x) return (getBOOL(), getBool()) } // CHECK-LABEL: sil hidden @_T013objc_bridging9getFridge{{.*}}F // CHECK: bb0([[HOME:%[0-9]+]] : $APPHouse): func getFridge(_ home: APPHouse) -> Refrigerator { // CHECK: [[BORROWED_HOME:%.*]] = begin_borrow [[HOME]] // CHECK: [[GETTER:%[0-9]+]] = class_method [volatile] [[BORROWED_HOME]] : $APPHouse, #APPHouse.fridge!getter.1.foreign // CHECK: [[OBJC_RESULT:%[0-9]+]] = apply [[GETTER]]([[BORROWED_HOME]]) // CHECK: [[BRIDGE_FN:%[0-9]+]] = function_ref @_T010Appliances12RefrigeratorV36_unconditionallyBridgeFromObjectiveCACSo15APPRefrigeratorCSgFZ // CHECK: [[REFRIGERATOR_META:%[0-9]+]] = metatype $@thin Refrigerator.Type // CHECK: [[RESULT:%[0-9]+]] = apply [[BRIDGE_FN]]([[OBJC_RESULT]], [[REFRIGERATOR_META]]) // CHECK: end_borrow [[BORROWED_HOME]] from [[HOME]] // CHECK: destroy_value [[HOME]] : $APPHouse // CHECK: return [[RESULT]] : $Refrigerator return home.fridge } // CHECK-LABEL: sil hidden @_T013objc_bridging16updateFridgeTemp{{.*}}F // CHECK: bb0([[HOME:%[0-9]+]] : $APPHouse, [[DELTA:%[0-9]+]] : $Double): func updateFridgeTemp(_ home: APPHouse, delta: Double) { // += // CHECK: [[PLUS_EQ:%[0-9]+]] = function_ref @_T0s2peoiySdz_SdtF // Borrowed home // CHECK: [[BORROWED_HOME:%.*]] = begin_borrow [[HOME]] // Temporary fridge // CHECK: [[TEMP_FRIDGE:%[0-9]+]] = alloc_stack $Refrigerator // Get operation // CHECK: [[GETTER:%[0-9]+]] = class_method [volatile] [[BORROWED_HOME]] : $APPHouse, #APPHouse.fridge!getter.1.foreign // CHECK: [[OBJC_FRIDGE:%[0-9]+]] = apply [[GETTER]]([[BORROWED_HOME]]) // CHECK: [[BRIDGE_FROM_FN:%[0-9]+]] = function_ref @_T010Appliances12RefrigeratorV36_unconditionallyBridgeFromObjectiveCACSo15APPRefrigeratorCSgFZ // CHECK: [[REFRIGERATOR_META:%[0-9]+]] = metatype $@thin Refrigerator.Type // CHECK: [[FRIDGE:%[0-9]+]] = apply [[BRIDGE_FROM_FN]]([[OBJC_FRIDGE]], [[REFRIGERATOR_META]]) // Addition // CHECK: [[TEMP:%[0-9]+]] = struct_element_addr [[TEMP_FRIDGE]] : $*Refrigerator, #Refrigerator.temperature // CHECK: apply [[PLUS_EQ]]([[TEMP]], [[DELTA]]) // Setter // CHECK: [[FRIDGE:%[0-9]+]] = load [trivial] [[TEMP_FRIDGE]] : $*Refrigerator // CHECK: [[SETTER:%[0-9]+]] = class_method [volatile] [[BORROWED_HOME]] : $APPHouse, #APPHouse.fridge!setter.1.foreign // CHECK: [[BRIDGE_TO_FN:%[0-9]+]] = function_ref @_T010Appliances12RefrigeratorV19_bridgeToObjectiveCSo15APPRefrigeratorCyF // CHECK: [[OBJC_ARG:%[0-9]+]] = apply [[BRIDGE_TO_FN]]([[FRIDGE]]) // CHECK: apply [[SETTER]]([[OBJC_ARG]], [[BORROWED_HOME]]) : $@convention(objc_method) (APPRefrigerator, APPHouse) -> () // CHECK: destroy_value [[OBJC_ARG]] // CHECK: end_borrow [[BORROWED_HOME]] from [[HOME]] // CHECK: destroy_value [[HOME]] home.fridge.temperature += delta }
8f430fcac8d2b5eca65fab20f3571bb1
55.705701
247
0.633525
false
false
false
false
joerocca/GitHawk
refs/heads/master
Classes/Issues/Comments/Markdown/MMElement+CodeBlock.swift
mit
1
// // MMElement+CodeBlock.swift // Freetime // // Created by Ryan Nystrom on 6/17/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import MMMarkdown func CreateCodeBlock(element: MMElement, markdown: String) -> IssueCommentCodeBlockModel { // create the text from all 1d "none" child elements // code blocks should not have any other child element type aside from "entity", which is skipped let text = element.children.reduce("") { guard $1.type == .none || $1.type == .entity else { return $0 } return $0 + substringOrNewline(text: markdown, range: $1.range) }.trimmingCharacters(in: .whitespacesAndNewlines) var inset = IssueCommentCodeBlockCell.textViewInset inset.left += IssueCommentCodeBlockCell.scrollViewInset.left inset.right += IssueCommentCodeBlockCell.scrollViewInset.right let attributedString: NSAttributedString if let language = element.language, let highlighted = GithubHighlighting.highlight(text, as: language) { attributedString = highlighted } else { attributedString = NSAttributedString( string: text, attributes: [ .foregroundColor: Styles.Colors.Gray.dark.color, .font: Styles.Fonts.code ] ) } let stringSizing = NSAttributedStringSizing( containerWidth: 0, attributedText: attributedString, inset: inset, backgroundColor: Styles.Colors.Gray.lighter.color ) return IssueCommentCodeBlockModel( code: stringSizing, language: element.language ) }
2c723051e02a3a69c40bfa5862f64041
33
101
0.671569
false
false
false
false
mingxianzyh/D3View
refs/heads/master
D3View/D3View/D3ScrollView.swift
mit
1
// // D3ScrollView.swift // Neighborhood // // Created by mozhenhau on 15-6-08. // Copyright (c) 2014 mozhenhau. All rights reserved. // 滚动图 // 使用方法:initScrollView, 修改样式用initStyle import UIKit enum ScrollViewStyle{ case all case noLabel case noBar } class D3ScrollView: UIView ,UIScrollViewDelegate{ var d3ImgView : UIImageView! //显示的第一张图 private var d3ScrollView : UIScrollView! //scroll private var d3PageControl : UIPageControl! //下方的圆点 private var d3Label : UILabel! //下方的标题 private var d3MaskView : UIView! //下方的蒙版 private var myTimer:NSTimer? var imgArr:Array<String> = [] //图片数组 var labelArr:Array<String> = [] //标题数组 var currentPage:Int = 0 //滚到哪一页,当前页 private var style:ScrollViewStyle = ScrollViewStyle.all var local:Bool = false //是不是用本地图 override func layoutSubviews() { //调整各部件位置大小 d3ImgView.frame = CGRectMake(0,0,self.frame.width,self.frame.height) d3ScrollView.frame = CGRectMake(0,0,self.frame.width,self.frame.height) d3Label.frame = CGRectMake(10,self.frame.height-30,self.frame.width-100,30) d3PageControl.frame = CGRectMake(0,self.frame.height-30,100,30) d3PageControl.center.x = self.frame.width/2 d3MaskView.frame = CGRectMake(0,self.frame.height-30,self.frame.width,30) } required init(coder aDecoder: NSCoder) { super.init(coder:aDecoder)! //默认样式 d3ImgView = UIImageView(image: UIImage(named:"")) self.contentMode = UIViewContentMode.ScaleAspectFit self.clipsToBounds = true d3ScrollView = UIScrollView() d3ScrollView.pagingEnabled = true d3ScrollView!.delegate = self d3ScrollView.scrollEnabled = true d3Label = UILabel() d3Label.font = UIFont.systemFontOfSize(14) d3Label.textColor = UIColor.whiteColor() d3PageControl = UIPageControl() d3MaskView = UIView() d3MaskView.backgroundColor = UIColor(red: 0.0 , green: 0.0, blue: 0.0, alpha: 0.6) addSubview(d3ImgView) addSubview(d3ScrollView) addSubview(d3MaskView) addSubview(d3Label) addSubview(d3PageControl) } func initScrollView(imgs:Array<String>?,labels:Array<String>?,style:ScrollViewStyle) { self.imgArr = imgs! self.labelArr = labels! initStyle(style) if myTimer != nil { myTimer?.invalidate() myTimer = nil } //imgView 首先显示第一张图 if imgArr.count > 0{ getImg(d3ImgView, img: imgArr[0]) } if labelArr.count > 0{ d3Label.text = labelArr[0] } //只有一张图就可以结束了,不用划动 if imgArr.count <= 1 { d3PageControl!.numberOfPages = 0 } else{ //scrollView 可移动范围3个宽度 d3ScrollView!.contentSize = CGSizeMake(self.frame.size.width * 3,self.frame.size.height) //scrollView 第二个宽度居中 d3ScrollView!.contentOffset = CGPointMake(self.frame.size.width, 0) //pagecontrol 有多少张图就多少个点 d3PageControl!.numberOfPages = imgArr.count d3PageControl!.pageIndicatorTintColor = UIColor.lightGrayColor() d3PageControl!.currentPageIndicatorTintColor = UIColor(red: 153/255, green: 201/255, blue: 47/255, alpha: 1) myTimer = NSTimer.scheduledTimerWithTimeInterval(5, target:self, selector:"autoSlide", userInfo:nil, repeats:true) } } func initStyle(style:ScrollViewStyle){ self.style = style switch(style){ case .noLabel: d3Label.hidden = true case .noBar: d3MaskView.hidden = true d3Label.hidden = true default: break } } func start() { if myTimer != nil { myTimer!.fireDate = NSDate().dateByAddingTimeInterval(5) } } func stop() { if myTimer != nil { myTimer!.fireDate = NSDate.distantFuture() } } //scrollView 开始手动滚动调用的方法 func scrollViewWillBeginDragging(scrollView: UIScrollView) { self.stop() d3ImgView.image = nil //总页数 let totalPage:Int = imgArr.count //当前图片如果是第一张,则左边图片为最后一张,否则为上一张 let imgView1:String = imgArr[(currentPage == 0 ? (totalPage - 1) : (currentPage - 1))] //当前图片 let imgView2:String = imgArr[currentPage] //当前图片如果是最后一张,则右边图片为第一张,否则为下一张 let imgView3:String = imgArr[(currentPage == (totalPage - 1) ? 0 : (currentPage + 1))] var scrollImgArr:Array<String> = [imgView1,imgView2,imgView3] for i:Int in 0..<3 { let imgView:UIImageView = UIImageView() imgView.frame = CGRectMake(CGFloat(i)*self.frame.size.width,0,self.frame.size.width,self.frame.size.height) getImg(imgView, img: scrollImgArr[i]) d3ScrollView!.addSubview(imgView) } } //scrollView 手动滚动停止调用的方法 func scrollViewDidEndDecelerating(scrollView: UIScrollView) { turnPage() self.start() } //scrollView 开始自动滚动调用的方法 func autoSlide() { scrollViewWillBeginDragging(d3ScrollView) //代码模拟 用手向右拉了一个 scrollView 的宽度 d3ScrollView!.setContentOffset(CGPointMake(d3ScrollView!.frame.size.width*2,0),animated: true) } //scrollView 自动滚动停止调用的方法 func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) { turnPage() self.start() } //换页时候调用的方法 func turnPage() { let totalPage:Int = imgArr.count //如果 scrollView 的 x 坐标大于320,即已经向右换一页 //并且判断当前页是否最后一页,如果是则下一页为第一张图 if d3ScrollView!.contentOffset.x > d3ScrollView!.frame.size.width { currentPage = (currentPage < (totalPage - 1) ? (currentPage + 1) : 0) } else if d3ScrollView!.contentOffset.x < d3ScrollView!.frame.size.width { currentPage = (currentPage > 0 ? (currentPage - 1) : (totalPage - 1)) } //换页后mainImgView 显示改图片,并且显示该页标题 let img:String = imgArr[currentPage] getImg(d3ImgView, img: img) if !d3Label.hidden{ d3Label.text = labelArr[currentPage] } d3PageControl!.currentPage = currentPage //把临时加进去的 imgView 从 scrollView 删除,释放内存 for imgView:AnyObject in d3ScrollView!.subviews { if imgView is UIImageView { (imgView as! UIImageView).removeFromSuperview() } } //scrollView重新摆回第二个页面在中间状态 d3ScrollView!.contentOffset = CGPointMake(d3ScrollView!.frame.size.width,0) } private func getImg(imgView:UIImageView,img:String){ if !local{ //TODO: 自行替换加载图的方式 imgView.image = UIImage(data: NSData(contentsOfURL: NSURL(string:img)!)!) // imgView.loadImage(img) imgView.contentMode = UIViewContentMode.ScaleAspectFit imgView.clipsToBounds = true } else{ imgView.image = UIImage(named:img) } } }
1b26937fa24be2d52ed70a2ee09b45c1
29.52459
126
0.585336
false
false
false
false
leosimas/ios_KerbalCampaigns
refs/heads/master
Kerbal Campaigns/Models/Bean/Campaign.swift
apache-2.0
1
// // Campaign.swift // Kerbal Campaigns // // Created by SSA on 15/09/17. // Copyright © 2017 Simas Team. All rights reserved. // import RealmSwift class Campaign : Object { dynamic var id = "" dynamic var completed : Bool = false dynamic var name = "" dynamic var difficulty = "" dynamic var introduction = "" dynamic var length = "" dynamic var difficultyNumber = 1 dynamic var difficultyText = "" let missions = List<Mission>() override static func primaryKey() -> String? { return "id" } func currentProgress() -> Int { var completed = 0 for mission in missions { if (mission.completed) { completed += 1 } } return Int(Float(completed) / Float(missions.count) * 100) } }
129791dbc25b9b80adaf0d60b1875ad9
21.184211
66
0.56465
false
false
false
false
DStorck/SwiftNewsApp
refs/heads/master
BlackHospital/Pods/RealmSwift/RealmSwift/Schema.swift
apache-2.0
8
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm #if swift(>=3.0) /** This class represents the collection of model object schemas persisted to Realm. When using Realm, `Schema` objects allow performing migrations and introspecting the database's schema. `Schema`s map to collections of tables in the core database. */ public final class Schema: CustomStringConvertible { // MARK: Properties internal let rlmSchema: RLMSchema /// `ObjectSchema`s for all object types in this Realm. Meant /// to be used during migrations for dynamic introspection. public var objectSchema: [ObjectSchema] { return rlmSchema.objectSchema.map(ObjectSchema.init) } /// Returns a human-readable description of the object schemas contained in this schema. public var description: String { return rlmSchema.description } // MARK: Initializers internal init(_ rlmSchema: RLMSchema) { self.rlmSchema = rlmSchema } // MARK: ObjectSchema Retrieval /// Returns the object schema with the given class name, if it exists. public subscript(className: String) -> ObjectSchema? { if let rlmObjectSchema = rlmSchema.schema(forClassName: className) { return ObjectSchema(rlmObjectSchema) } return nil } } // MARK: Equatable extension Schema: Equatable {} /// Returns whether the two schemas are equal. public func == (lhs: Schema, rhs: Schema) -> Bool { // swiftlint:disable:this valid_docs return lhs.rlmSchema.isEqual(to: rhs.rlmSchema) } #else /** `Schema` instances represent collections of model object schemas managed by a Realm. When using Realm, `Schema` instances allow performing migrations and introspecting the database's schema. Schemas map to collections of tables in the core database. */ public final class Schema: CustomStringConvertible { // MARK: Properties internal let rlmSchema: RLMSchema /** An array of `ObjectSchema`s for all object types in the Realm. This property is intended to be used during migrations for dynamic introspection. */ public var objectSchema: [ObjectSchema] { return rlmSchema.objectSchema.map(ObjectSchema.init) } /// Returns a human-readable description of the object schemas contained in this schema. public var description: String { return rlmSchema.description } // MARK: Initializers internal init(_ rlmSchema: RLMSchema) { self.rlmSchema = rlmSchema } // MARK: ObjectSchema Retrieval /// Looks up and returns an `ObjectSchema` for the given class name in the Realm, if it exists. public subscript(className: String) -> ObjectSchema? { if let rlmObjectSchema = rlmSchema.schemaForClassName(className) { return ObjectSchema(rlmObjectSchema) } return nil } } // MARK: Equatable extension Schema: Equatable {} /// Returns a Boolean value that indicates whether two `Schema` instances are equivalent. public func == (lhs: Schema, rhs: Schema) -> Bool { // swiftlint:disable:this valid_docs return lhs.rlmSchema.isEqualToSchema(rhs.rlmSchema) } #endif
dd109cfa8894e3d814b6de6f2dbc5ce0
29.456693
99
0.686918
false
false
false
false
protoman92/SwiftUtilities
refs/heads/master
SwiftUtilities/date/Dates.swift
apache-2.0
1
// // Dates.swift // SwiftUtilities // // Created by Hai Pham on 8/9/16. // Copyright © 2016 Swiften. All rights reserved. // extension Date: IsInstanceType {} extension Calendar: IsInstanceType {} public typealias CalendarUnits = Set<Calendar.Component> public extension Date { /// Check if the current Date is earlier than, or at least the same as, /// another Date. /// /// - Parameter date: The Date to be compared to. /// - Returns: A Bool value. public func notLaterThan(date: Date) -> Bool { return compare(date) != .orderedDescending } /// Check if the current Date is earlier than another Date. /// /// - Parameter date: The Date to be compared to. /// - Returns: A Bool value. public func earlierThan(date: Date) -> Bool { return compare(date) == .orderedAscending } /// Check if the current Date is later than, or at least the same as, /// another Date. /// /// - Parameter date: The Date to be compared to. /// - Returns: A Bool value. public func notEarlierThan(date: Date) -> Bool { return compare(date) != .orderedAscending } /// Check if the current Date is later than another Date. /// /// - Parameter date: The Date to be compared to. /// - Returns: A Bool value. public func laterThan(date: Date) -> Bool { return compare(date) == .orderedDescending } /// Check if the current Date is the same as another Date. /// /// - Parameter date: The Date to be compared to. /// - Returns: A Bool value. public func sameAs(date: Date) -> Bool { return compare(date) == .orderedSame } } public extension Calendar { /// Check if a Date is earlier than or the same as another Date, based on /// the specified /// granularity level. /// /// - Parameters: /// - date: The Date to be compared. /// - ref: The Date to be compared to. /// - granularity: The level of comparison. /// - Returns: A Bool value. public func notLaterThan(compare date: Date, to ref: Date, granularity: Calendar.Component) -> Bool { let result = compare(date, to: ref, toGranularity: granularity) return result != .orderedDescending } /// Check if a Date is earlier than another Date, based on the specified /// granularity level. /// /// - Parameters: /// - date: The Date to be compared. /// - ref: The Date to be compared to. /// - granularity: The level of comparison. /// - Returns: A Bool value. public func earlierThan(compare date: Date, to ref: Date, granularity: Calendar.Component) -> Bool { let result = compare(date, to: ref, toGranularity: granularity) return result == .orderedAscending } /// Check if a Date is later than or the same as another Date, based on /// the specified /// granularity level. /// /// - Parameters: /// - date: The Date to be compared. /// - ref: The Date to be compared to. /// - granularity: The level of comparison. /// - Returns: A Bool value. public func notEarlierThan(compare date: Date, to ref: Date, granularity: Calendar.Component) -> Bool { let result = compare(date, to: ref, toGranularity: granularity) return result != .orderedAscending } /// Check if a Date is later than another Date, based on the specified /// granularity level. /// /// - Parameters: /// - date: The Date to be compared. /// - ref: The Date to be compared to. /// - granularity: The level of comparison. /// - Returns: A Bool value. public func laterThan(compare date: Date, to ref: Date, granularity: Calendar.Component) -> Bool { let result = compare(date, to: ref, toGranularity: granularity) return result == .orderedDescending } /// Check if a Date is the same as another Date, based on the specified /// granularity level. /// /// - Parameters: /// - date: The Date to be compared. /// - ref: The Date to be compared to. /// - granularity: The level of comparison. /// - Returns: A Bool value. public func sameAs(compare date: Date, to ref: Date, granularity: Calendar.Component) -> Bool { let result = compare(date, to: ref, toGranularity: granularity) return result == .orderedSame } } public extension DateComponents { /// Create a DateComponents from separate components. /// /// - Parameters: /// - day: The day number. /// - month: The month number. /// - year: The year number. /// - hour: The hour number. /// - minute: The minute number. /// - second: The second number. /// - Returns: A DateComponents struct. public static func from(day: Int? = nil, month: Int? = nil, year: Int? = nil, hour: Int? = nil, minute: Int? = nil, second: Int? = nil) -> DateComponents { var component = DateComponents() component.day = day ?? 1 component.month = month ?? 0 component.year = year ?? 0 component.hour = hour ?? 0 component.minute = minute ?? 0 component.second = second ?? 0 return component } /// Get a random DateComponents. /// /// - Returns: A DateComponents struct. public static func random() -> DateComponents { return DateComponents.from(day: Int.randomBetween(1, 28), month: Int.randomBetween(1, 12), year: Int.randomBetween(2000, 2016), hour: Int.randomBetween(0, 59), minute: Int.randomBetween(0, 59), second: Int.randomBetween(0, 59)) } } public extension Calendar.Component { /// Get a random Calendar.Component. /// /// - Returns: A Calendar.Component instance. public static func random() -> Calendar.Component { let components: Set<Calendar.Component> = [.minute, .hour, .day, .month, .year, .weekday] let index = Int.randomBetween(0, components.count - 1) return components.map({$0})[index] } } public extension Date { /// Get a random Date instance. /// /// - Returns: A Date instance. public static func random() -> Date? { let components = DateComponents.random() return Calendar(identifier: .gregorian).date(from: components) } public static func randomBetween(_ first: Date, _ second: Date) -> Date? { let firstMillis = Int(first.timeIntervalSince1970) let secondMillis = Int(second.timeIntervalSince1970) let randomMillis = Double(Int.randomBetween(firstMillis, secondMillis)) return Date(timeIntervalSince1970: randomMillis) } }
3fb91dbe5fa36e553e32887667cc0b6f
32.173709
76
0.584772
false
false
false
false
blackbear/OpenHumansUpload
refs/heads/master
OpenHumansUpload/OpenHumansUpload/ViewController.swift
mit
1
// // ViewController.swift // OpenHumansUpload // // Created by James Turner on 4/28/16. // Copyright © 2016 Open Humans. All rights reserved. // import UIKit import HealthKit import Foundation import Crashlytics class ViewController: UIViewController { @IBOutlet weak var actionButton: UIButton! @IBOutlet weak var instructions: UILabel! var healthStore : HKHealthStore! var accessToken = "" var fileList : JSONArray = JSONArray() enum AppState { case Start, Checking, Prelogin, Postlogin } var currentState = AppState.Start func logUser(userId : String) { // TODO: Use the current user's information // You can call any combination of these three methods Crashlytics.sharedInstance().setUserIdentifier(userId) } override func viewDidLoad() { super.viewDidLoad() instructions.hidden = true actionButton.hidden = true let oauth = OH_OAuth2.sharedInstance(); if oauth.hasCachedToken() { instructions.text = "Logging in..." instructions.hidden = false OH_OAuth2.sharedInstance().authenticateOAuth2(self, allowLogin: false, handler: { (status : AuthorizationStatus) -> Void in if (status == AuthorizationStatus.AUTHORIZED) { OH_OAuth2.sharedInstance().getMemberInfo({ (memberId, messagePermission, usernameShared, username, files) in self.logUser(memberId) self.fileList = files dispatch_async(dispatch_get_main_queue(), { self.performSegueWithIdentifier("startupToMain", sender: self) }) }, onFailure: { dispatch_async(dispatch_get_main_queue(), { self.authenticateRequiresLogin() }) }) } else { self.authenticateRequiresLogin() } }); } else { self.authenticateRequiresLogin() } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "startupToMain") { let vc = segue.destinationViewController as! MainMenu vc.fileList = fileList } } func authenticateRequiresLogin() { instructions.text = "Welcome to the Open Humans HealthKit Uploader. This tool will allow you to upload your HealthKit data (visible in the Health app) to your Open Humans account so that researchers can access the information you have recorded on your device.\n\nTo begin, you need to authenticate your identity with the Open Humans Web Site." actionButton.setTitle("Go to Open Humans website", forState: .Normal) instructions.hidden = false actionButton.hidden = false } func uploadSucceeded(res: String) { print(res); } func memberInfoFailed() { } func authenticateFailed() -> Void { authenticateRequiresLogin() } func authenticateCanceled() -> Void { authenticateRequiresLogin() } override func viewDidAppear(animated: Bool) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func validateToken(token: String) -> Void { } @IBAction func nextAction(sender: AnyObject) { OH_OAuth2.sharedInstance().authenticateOAuth2(self, allowLogin: true, handler: { (status : AuthorizationStatus) -> Void in OH_OAuth2.sharedInstance().getMemberInfo({ (memberId, messagePermission, usernameShared, username, files) in self.logUser(memberId) self.performSegueWithIdentifier("startupToMain", sender: self) }, onFailure: { self.authenticateRequiresLogin() }) }); } }
a7a1fc5be57f38b81b4a8515cc62178a
31.578125
351
0.586811
false
false
false
false
whitepixelstudios/Armchair
refs/heads/master
Source/Armchair.swift
mit
1
// Armchair.swift // // Copyright (c) 2014 Armchair (http://github.com/UrbanApps/Armchair) // // 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 import StoreKit import SystemConfiguration #if os(iOS) import UIKit #elseif os(OSX) import AppKit #else // Not yet supported #endif // MARK: - // MARK: PUBLIC Interface // MARK: - // MARK: Properties /* * Get/Set your Apple generated software id. * This is the only required setup value. * This call needs to be first. No default. */ public var appID: String = "" public func appID(_ appID: String) { Armchair.appID = appID Manager.defaultManager.appID = appID } /* * Get/Set the App Name to use in the prompt * Default value is your localized display name from the info.plist */ public func appName() -> String { return Manager.defaultManager.appName } public func appName(_ appName: String) { Manager.defaultManager.appName = appName } /* * Get/Set the title to use on the review prompt. * Default value is a localized "Rate <appName>" */ public func reviewTitle() -> String { return Manager.defaultManager.reviewTitle } public func reviewTitle(_ reviewTitle: String) { Manager.defaultManager.reviewTitle = reviewTitle } /* * Get/Set the message to use on the review prompt. * Default value is a localized * "If you enjoy using <appName>, would you mind taking a moment to rate it? It won't take more than a minute. Thanks for your support!" */ public func reviewMessage() -> String { return Manager.defaultManager.reviewMessage } public func reviewMessage(_ reviewMessage: String) { Manager.defaultManager.reviewMessage = reviewMessage } /* * Get/Set the cancel button title to use on the review prompt. * Default value is a localized "No, Thanks" */ public func cancelButtonTitle() -> String { return Manager.defaultManager.cancelButtonTitle } public func cancelButtonTitle(_ cancelButtonTitle: String) { Manager.defaultManager.cancelButtonTitle = cancelButtonTitle } /* * Get/Set the rate button title to use on the review prompt. * Default value is a localized "Rate <appName>" */ public func rateButtonTitle() -> String { return Manager.defaultManager.rateButtonTitle } public func rateButtonTitle(_ rateButtonTitle: String) { Manager.defaultManager.rateButtonTitle = rateButtonTitle } /* * Get/Set the remind me later button title to use on the review prompt. * It is optional, so you can set it to nil to hide the remind button from displaying * Default value is a localized "Remind me later" */ public func remindButtonTitle() -> String? { return Manager.defaultManager.remindButtonTitle } public func remindButtonTitle(_ remindButtonTitle: String?) { Manager.defaultManager.remindButtonTitle = remindButtonTitle } /* * Get/Set the NSUserDefault keys that store the usage data for Armchair * Default values are in the form of "<appID>_Armchair<Setting>" */ public func keyForArmchairKeyType(_ keyType: ArmchairKey) -> String { return Manager.defaultManager.keyForArmchairKeyType(keyType) } public func setKey(_ key: NSString, armchairKeyType: ArmchairKey) { Manager.defaultManager.setKey(key, armchairKeyType: armchairKeyType) } /* * Get/Set the prefix to the NSUserDefault keys that store the usage data for Armchair * Default value is the App ID, and it is prepended to the keys for key type, above * This prevents different apps using a shared Key/Value store from overwriting each other. */ public func keyPrefix() -> String { return Manager.defaultManager.keyPrefix } public func keyPrefix(_ keyPrefix: String) { Manager.defaultManager.keyPrefix = keyPrefix } /* * Get/Set the object that stores the usage data for Armchair * it is optional but if you pass nil, Armchair can not run. * Default value is NSUserDefaults.standardUserDefaults() */ public func userDefaultsObject() -> ArmchairDefaultsObject? { return Manager.defaultManager.userDefaultsObject } public func userDefaultsObject(_ userDefaultsObject: ArmchairDefaultsObject?) { Manager.defaultManager.userDefaultsObject = userDefaultsObject } /* * Users will need to have the same version of your app installed for this many * days before they will be prompted to rate it. * Default => 30 */ public func daysUntilPrompt() -> UInt { return Manager.defaultManager.daysUntilPrompt } public func daysUntilPrompt(_ daysUntilPrompt: UInt) { Manager.defaultManager.daysUntilPrompt = daysUntilPrompt } /* * An example of a 'use' would be if the user launched the app. Bringing the app * into the foreground (on devices that support it) would also be considered * a 'use'. * * Users need to 'use' the same version of the app this many times before * before they will be prompted to rate it. * Default => 20 */ public func usesUntilPrompt() -> UInt { return Manager.defaultManager.usesUntilPrompt } public func usesUntilPrompt(_ usesUntilPrompt: UInt) { Manager.defaultManager.usesUntilPrompt = usesUntilPrompt } /* * A significant event can be anything you want to be in your app. In a * telephone app, a significant event might be placing or receiving a call. * In a game, it might be beating a level or a boss. This is just another * layer of filtering that can be used to make sure that only the most * loyal of your users are being prompted to rate you on the app store. * If you leave this at a value of 0 (default), then this won't be a criterion * used for rating. * * To tell Armchair that the user has performed * a significant event, call the method Armchair.userDidSignificantEvent() * Default => 0 */ public func significantEventsUntilPrompt() -> UInt { return Manager.defaultManager.significantEventsUntilPrompt } public func significantEventsUntilPrompt(_ significantEventsUntilPrompt: UInt) { Manager.defaultManager.significantEventsUntilPrompt = significantEventsUntilPrompt } /* * Once the rating alert is presented to the user, they might select * 'Remind me later'. This value specifies how many days Armchair * will wait before reminding them. A value of 0 disables reminders and * removes the 'Remind me later' button. * Default => 1 */ public func daysBeforeReminding() -> UInt { return Manager.defaultManager.daysBeforeReminding } public func daysBeforeReminding(_ daysBeforeReminding: UInt) { Manager.defaultManager.daysBeforeReminding = daysBeforeReminding } /* * By default, Armchair tracks all new bundle versions. * When it detects a new version, it resets the values saved for usage, * significant events, popup shown, user action etc... * By setting this to false, Armchair will ONLY track the version it * was initialized with. If this setting is set to true, Armchair * will reset after each new version detection. * Default => true */ public func tracksNewVersions() -> Bool { return Manager.defaultManager.tracksNewVersions } public func tracksNewVersions(_ tracksNewVersions: Bool) { Manager.defaultManager.tracksNewVersions = tracksNewVersions } /* * If the user has rated the app once before, and you don't want it to show on * a new version, set this to false. This is useful if you release small bugfix * versions and don't want to pester your users with popups for every minor * version. For example, you might set this to false for every minor build, then * when you push a major version upgrade, leave it as true to ask for a rating again. * Default => true */ public func shouldPromptIfRated() -> Bool { return Manager.defaultManager.shouldPromptIfRated } public func shouldPromptIfRated(_ shouldPromptIfRated: Bool) { Manager.defaultManager.shouldPromptIfRated = shouldPromptIfRated } /* * Return whether Armchair will try and present the Storekit review prompt (useful for custom dialog modification) */ public var shouldTryStoreKitReviewPrompt : Bool { return Manager.defaultManager.shouldTryStoreKitReviewPrompt } /* * If set to true, the main bundle will always be used to load localized strings. * Set this to true if you have provided your own custom localizations in * ArmchairLocalizable.strings in your main bundle * Default => false. */ public func useMainAppBundleForLocalizations() -> Bool { return Manager.defaultManager.useMainAppBundleForLocalizations } public func useMainAppBundleForLocalizations(_ useMainAppBundleForLocalizations: Bool) { Manager.defaultManager.useMainAppBundleForLocalizations = useMainAppBundleForLocalizations } /* * If you are an Apple Affiliate, enter your code here. * If none is set, the author's code will be used as it is better to be set as something * rather than nothing. If you want to thank me for making Armchair, feel free * to leave this value at it's default. */ public func affiliateCode() -> String { return Manager.defaultManager.affiliateCode } public func affiliateCode(_ affiliateCode: String) { Manager.defaultManager.affiliateCode = affiliateCode } /* * If you are an Apple Affiliate, enter your campaign code here. * Default => "Armchair-<appID>" */ public func affiliateCampaignCode() -> String { return Manager.defaultManager.affiliateCampaignCode } public func affiliateCampaignCode(_ affiliateCampaignCode: String) { Manager.defaultManager.affiliateCampaignCode = affiliateCampaignCode } #if os(iOS) /* * If set to true, use SKStoreReviewController's requestReview() prompt instead of the default prompt. * If not on iOS 10.3+, reort to the default prompt. * Default => false. */ public func useStoreKitReviewPrompt() -> Bool { return Manager.defaultManager.useStoreKitReviewPrompt } public func useStoreKitReviewPrompt(_ useStoreKitReviewPrompt: Bool) { Manager.defaultManager.useStoreKitReviewPrompt = useStoreKitReviewPrompt } #endif /* * 'true' will show the Armchair alert everytime. Useful for testing * how your message looks and making sure the link to your app's review page works. * Calling this method in a production build (DEBUG preprocessor macro is not defined) * has no effect. In app store builds, you don't have to worry about accidentally * leaving debugEnabled to true * Default => false */ public func debugEnabled() -> Bool { return Manager.defaultManager.debugEnabled } public func debugEnabled(_ debugEnabled: Bool) { #if Debug Manager.defaultManager.debugEnabled = debugEnabled #else print("[Armchair] Debug is disabled on release builds.") print("[Armchair] If you really want to enable debug mode,") print("[Armchair] add \"-DDebug\" to your Swift Compiler - Custom Flags") print("[Armchair] section in the target's build settings for release") #endif } /** Reset all counters manually. This resets UseCount, SignificantEventCount and FirstUseDate (daysUntilPrompt) */ public func resetUsageCounters() { StandardUserDefaults().setObject(NSNumber(value: Date().timeIntervalSince1970), forKey: keyForArmchairKeyType(ArmchairKey.FirstUseDate)) StandardUserDefaults().setObject(NSNumber(value: 1), forKey: keyForArmchairKeyType(ArmchairKey.UseCount)) StandardUserDefaults().setObject(NSNumber(value: 0), forKey: keyForArmchairKeyType(ArmchairKey.SignificantEventCount)) StandardUserDefaults().synchronize() } /** Reset all values tracked by Armchair to initial state. */ public func resetAllCounters() { let currentVersionKey = keyForArmchairKeyType(ArmchairKey.CurrentVersion) let trackingVersion: String? = StandardUserDefaults().stringForKey(currentVersionKey) let bundleVersionKey = kCFBundleVersionKey as String let currentVersion = Bundle.main.object(forInfoDictionaryKey: bundleVersionKey) as? String StandardUserDefaults().setObject(trackingVersion as AnyObject?, forKey: keyForArmchairKeyType(ArmchairKey.PreviousVersion)) StandardUserDefaults().setObject(StandardUserDefaults().objectForKey(keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion)), forKey: keyForArmchairKeyType(ArmchairKey.PreviousVersionRated)) StandardUserDefaults().setObject(StandardUserDefaults().objectForKey(keyForArmchairKeyType(ArmchairKey.DeclinedToRate)), forKey: keyForArmchairKeyType(ArmchairKey.PreviousVersionDeclinedToRate)) StandardUserDefaults().setObject(currentVersion as AnyObject?, forKey: currentVersionKey) resetUsageCounters() StandardUserDefaults().setObject(NSNumber(value: false), forKey: keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion)) StandardUserDefaults().setObject(NSNumber(value: false), forKey: keyForArmchairKeyType(ArmchairKey.DeclinedToRate)) StandardUserDefaults().setObject(NSNumber(value: 0), forKey: keyForArmchairKeyType(ArmchairKey.ReminderRequestDate)) StandardUserDefaults().synchronize() } /* * * */ public func resetDefaults() { Manager.defaultManager.debugEnabled = false Manager.defaultManager.appName = Manager.defaultManager.defaultAppName() Manager.defaultManager.reviewTitle = Manager.defaultManager.defaultReviewTitle() Manager.defaultManager.reviewMessage = Manager.defaultManager.defaultReviewMessage() Manager.defaultManager.cancelButtonTitle = Manager.defaultManager.defaultCancelButtonTitle() Manager.defaultManager.rateButtonTitle = Manager.defaultManager.defaultRateButtonTitle() Manager.defaultManager.remindButtonTitle = Manager.defaultManager.defaultRemindButtonTitle() Manager.defaultManager.daysUntilPrompt = 30 Manager.defaultManager.daysBeforeReminding = 1 Manager.defaultManager.shouldPromptIfRated = true Manager.defaultManager.significantEventsUntilPrompt = 20 Manager.defaultManager.tracksNewVersions = true Manager.defaultManager.useMainAppBundleForLocalizations = false Manager.defaultManager.affiliateCode = Manager.defaultManager.defaultAffiliateCode() Manager.defaultManager.affiliateCampaignCode = Manager.defaultManager.defaultAffiliateCampaignCode() Manager.defaultManager.didDeclineToRateClosure = nil Manager.defaultManager.didDisplayAlertClosure = nil Manager.defaultManager.didOptToRateClosure = nil Manager.defaultManager.didOptToRemindLaterClosure = nil Manager.defaultManager.customAlertClosure = nil #if os(iOS) Manager.defaultManager.usesAnimation = true Manager.defaultManager.tintColor = nil Manager.defaultManager.usesAlertController = Manager.defaultManager.defaultUsesAlertController() Manager.defaultManager.opensInStoreKit = Manager.defaultManager.defaultOpensInStoreKit() Manager.defaultManager.willPresentModalViewClosure = nil Manager.defaultManager.didDismissModalViewClosure = nil #endif Manager.defaultManager.armchairKeyFirstUseDate = Manager.defaultManager.defaultArmchairKeyFirstUseDate() Manager.defaultManager.armchairKeyUseCount = Manager.defaultManager.defaultArmchairKeyUseCount() Manager.defaultManager.armchairKeySignificantEventCount = Manager.defaultManager.defaultArmchairKeySignificantEventCount() Manager.defaultManager.armchairKeyCurrentVersion = Manager.defaultManager.defaultArmchairKeyCurrentVersion() Manager.defaultManager.armchairKeyRatedCurrentVersion = Manager.defaultManager.defaultArmchairKeyRatedCurrentVersion() Manager.defaultManager.armchairKeyDeclinedToRate = Manager.defaultManager.defaultArmchairKeyDeclinedToRate() Manager.defaultManager.armchairKeyReminderRequestDate = Manager.defaultManager.defaultArmchairKeyReminderRequestDate() Manager.defaultManager.armchairKeyPreviousVersion = Manager.defaultManager.defaultArmchairKeyPreviousVersion() Manager.defaultManager.armchairKeyPreviousVersionRated = Manager.defaultManager.defaultArmchairKeyPreviousVersionRated() Manager.defaultManager.armchairKeyPreviousVersionDeclinedToRate = Manager.defaultManager.defaultArmchairKeyDeclinedToRate() Manager.defaultManager.armchairKeyRatedAnyVersion = Manager.defaultManager.defaultArmchairKeyRatedAnyVersion() Manager.defaultManager.armchairKeyAppiraterMigrationCompleted = Manager.defaultManager.defaultArmchairKeyAppiraterMigrationCompleted() Manager.defaultManager.armchairKeyUAAppReviewManagerMigrationCompleted = Manager.defaultManager.defaultArmchairKeyUAAppReviewManagerMigrationCompleted() Manager.defaultManager.keyPrefix = Manager.defaultManager.defaultKeyPrefix() } #if os(iOS) /* * Set whether or not Armchair uses animation when pushing modal StoreKit * view controllers for the app. * Default => true */ public func usesAnimation() -> Bool { return Manager.defaultManager.usesAnimation } public func usesAnimation(_ usesAnimation: Bool) { Manager.defaultManager.usesAnimation = usesAnimation } /* * Set a tint color to apply to UIAlertController * Default => nil (the default tint color is used) */ public func tintColor() -> UIColor? { return Manager.defaultManager.tintColor } public func tintColor(tintColor: UIColor?) { Manager.defaultManager.tintColor = tintColor } /* * Set whether or not Armchair uses a UIAlertController when presenting on iOS 8 * We prefer not to use it so that the Rate button can be on the bottom and the cancel button on the top, * Something not possible as of iOS 8.0 * Default => false */ public func usesAlertController() -> Bool { return Manager.defaultManager.usesAlertController } public func usesAlertController(_ usesAlertController: Bool) { Manager.defaultManager.usesAlertController = usesAlertController } /* * If set to true, Armchair will open App Store link inside the app using * SKStoreProductViewController. * - itunes affiliate codes DO NOT work on iOS 7 inside StoreKit, * - itunes affiliate codes DO work on iOS 8 inside StoreKit, * Default => false on iOS 7, true on iOS 8+ */ public func opensInStoreKit() -> Bool { return Manager.defaultManager.opensInStoreKit } public func opensInStoreKit(_ opensInStoreKit: Bool) { Manager.defaultManager.opensInStoreKit = opensInStoreKit } #endif // MARK: Events /* * Tells Armchair that the user performed a significant event. * A significant event is whatever you want it to be. If you're app is used * to make VoIP calls, then you might want to call this method whenever the * user places a call. If it's a game, you might want to call this whenever * the user beats a level boss. * * If the user has performed enough significant events and used the app enough, * you can suppress the rating alert by passing false for canPromptForRating. The * rating alert will simply be postponed until it is called again with true for * canPromptForRating. */ public func userDidSignificantEvent(_ canPromptForRating: Bool) { Manager.defaultManager.userDidSignificantEvent(canPromptForRating) } /* * Tells Armchair that the user performed a significant event. * A significant event is whatever you want it to be. If you're app is used * to make VoIP calls, then you might want to call this method whenever the * user places a call. If it's a game, you might want to call this whenever * the user beats a level boss. * * This is similar to the userDidSignificantEvent method, but allows the passing of a * ArmchairShouldPromptClosure that will be executed before prompting. * The closure passes all the keys and values that Armchair uses to * determine if it the prompt conditions have been met, and it is up to you * to use this info and return a Bool on whether or not the prompt should be shown. * The closure is run synchronous and on the main queue, so be sure to handle it appropriately. * Return true to proceed and show the prompt, return false to kill the pending presentation. */ public func userDidSignificantEvent(_ shouldPrompt: @escaping ArmchairShouldPromptClosure) { Manager.defaultManager.userDidSignificantEvent(shouldPrompt) } // MARK: Prompts /* * Tells Armchair to show the prompt (a rating alert). The prompt * will be showed if there is an internet connection available, the user hasn't * declined to rate, hasn't rated current version and you are tracking new versions. * * You could call to show the prompt regardless of Armchair settings, * for instance, in the case of some special event in your app. */ public func showPrompt() { Manager.defaultManager.showPrompt() } /* * Tells Armchair to show the review prompt alert if all restrictions have been met. * The prompt will be shown if all restrictions are met, there is an internet connection available, * the user hasn't declined to rate, hasn't rated current version, and you are tracking new versions. * * You could call to show the prompt, for instance, in the case of some special event in your app, * like a user login. */ public func showPromptIfNecessary() { Manager.defaultManager.showPrompt(ifNecessary: true) } /* * Tells Armchair to show the review prompt alert. * * This is similar to the showPromptIfNecessary method, but allows the passing of a * ArmchairShouldPromptClosure that will be executed before prompting. * The closure passes all the keys and values that Armchair uses to * determine if it the prompt conditions have been met, and it is up to you * to use this info and return a Bool on whether or not the prompt should be shown. * The closure is run synchronous and on the main queue, so be sure to handle it appropriately. * Return true to proceed and show the prompt, return false to kill the pending presentation. */ public func showPrompt(_ shouldPrompt: ArmchairShouldPromptClosure) { Manager.defaultManager.showPrompt(shouldPrompt) } /** Returns true if rating conditions have been met already and rating prompt is likely to be shown. */ public func ratingConditionsHaveBeenMet() -> Bool { return Manager.defaultManager.ratingConditionsHaveBeenMet() } // MARK: Misc /* * This is the review URL string, generated by substituting the appID, affiliate code * and affilitate campaign code into the template URL. */ public func reviewURLString() -> String { return Manager.defaultManager.reviewURLString() } /* * Tells Armchair to open the App Store page where the user can specify a * rating for the app. Also records the fact that this has happened, so the * user won't be prompted again to rate the app. * * The only case where you should call this directly is if your app has an * explicit "Rate this app" command somewhere. In all other cases, don't worry * about calling this -- instead, just call the other functions listed above, * and let Armchair handle the bookkeeping of deciding when to ask the user * whether to rate the app. */ public func rateApp() { Manager.defaultManager.rateApp() } #if os(iOS) /* * Tells Armchair to immediately close any open rating modals * for instance, a StoreKit rating View Controller. */ public func closeModalPanel() { Manager.defaultManager.closeModalPanel() } #endif // MARK: Closures /* * Armchair uses closures instead of delegate methods for callbacks. * Default is nil for all of them. */ public typealias ArmchairClosure = () -> () public typealias ArmchairClosureCustomAlert = (_ rateAppClosure: @escaping ArmchairClosure, _ remindLaterClosure: @escaping ArmchairClosure, _ noThanksClosure: @escaping ArmchairClosure) -> () public typealias ArmchairAnimateClosure = (Bool) -> () public typealias ArmchairShouldPromptClosure = (ArmchairTrackingInfo) -> Bool public typealias ArmchairShouldIncrementClosure = () -> Bool public func onDidDisplayAlert(_ didDisplayAlertClosure: ArmchairClosure?) { Manager.defaultManager.didDisplayAlertClosure = didDisplayAlertClosure } public func customAlertClosure(_ customAlertClosure: ArmchairClosureCustomAlert?) { Manager.defaultManager.customAlertClosure = customAlertClosure } public func onDidDeclineToRate(_ didDeclineToRateClosure: ArmchairClosure?) { Manager.defaultManager.didDeclineToRateClosure = didDeclineToRateClosure } public func onDidOptToRate(_ didOptToRateClosure: ArmchairClosure?) { Manager.defaultManager.didOptToRateClosure = didOptToRateClosure } public func onDidOptToRemindLater(_ didOptToRemindLaterClosure: ArmchairClosure?) { Manager.defaultManager.didOptToRemindLaterClosure = didOptToRemindLaterClosure } #if os(iOS) public func onWillPresentModalView(_ willPresentModalViewClosure: ArmchairAnimateClosure?) { Manager.defaultManager.willPresentModalViewClosure = willPresentModalViewClosure } public func onDidDismissModalView(_ didDismissModalViewClosure: ArmchairAnimateClosure?) { Manager.defaultManager.didDismissModalViewClosure = didDismissModalViewClosure } #endif /* * The setShouldPromptClosure is called just after all the rating coditions * have been met and Armchair has decided it should display a prompt, * but just before the prompt actually displays. * * The closure passes all the keys and values that Armchair used to * determine that the prompt conditions had been met, but it is up to you * to use this info and return a Bool on whether or not the prompt should be shown. * Return true to proceed and show the prompt, return false to kill the pending presentation. */ public func shouldPromptClosure(_ shouldPromptClosure: ArmchairShouldPromptClosure?) { Manager.defaultManager.shouldPromptClosure = shouldPromptClosure } /* * The setShouldIncrementUseClosure, if valid, is called before incrementing the use count. * Returning false allows you to ignore a use. This may be usefull in cases such as Facebook login * where the app is backgrounded momentarily and the resultant enter foreground event should * not be considered another use. */ public func shouldIncrementUseCountClosure(_ shouldIncrementUseCountClosure: ArmchairShouldIncrementClosure?) { Manager.defaultManager.shouldIncrementUseCountClosure = shouldIncrementUseCountClosure } // MARK: Armchair Logger Protocol public typealias ArmchairLogger = (Manager, _ log: String, _ file: StaticString, _ function: StaticString, _ line: UInt) -> Void /* * Set a closure to capture debug log and to plug in the desired logging framework. */ public func logger(_ logger: @escaping ArmchairLogger) { Manager.defaultManager.logger = logger } // MARK: - // MARK: Armchair Defaults Protocol @objc public protocol ArmchairDefaultsObject { func objectForKey(_ defaultName: String) -> AnyObject? func setObject(_ value: AnyObject?, forKey defaultName: String) func removeObjectForKey(_ defaultName: String) func stringForKey(_ defaultName: String) -> String? func integerForKey(_ defaultName: String) -> Int func doubleForKey(_ defaultName: String) -> Double func boolForKey(_ defaultName: String) -> Bool func setInteger(_ value: Int, forKey defaultName: String) func setDouble(_ value: Double, forKey defaultName: String) func setBool(_ value: Bool, forKey defaultName: String) @discardableResult func synchronize() -> Bool } open class StandardUserDefaults: ArmchairDefaultsObject { let defaults = UserDefaults.standard @objc open func objectForKey(_ defaultName: String) -> AnyObject? { return defaults.object(forKey: defaultName) as AnyObject? } @objc open func setObject(_ value: AnyObject?, forKey defaultName: String) { defaults.set(value, forKey: defaultName) } @objc open func removeObjectForKey(_ defaultName: String) { defaults.removeObject(forKey: defaultName) } @objc open func stringForKey(_ defaultName: String) -> String? { return defaults.string(forKey: defaultName) } @objc open func integerForKey(_ defaultName: String) -> Int { return defaults.integer(forKey: defaultName) } @objc open func doubleForKey(_ defaultName: String) -> Double { return defaults.double(forKey: defaultName) } @objc open func boolForKey(_ defaultName: String) -> Bool { return defaults.bool(forKey: defaultName) } @objc open func setInteger(_ value: Int, forKey defaultName: String) { defaults.set(value, forKey: defaultName) } @objc open func setDouble(_ value: Double, forKey defaultName: String) { defaults.set(value, forKey: defaultName) } @objc open func setBool(_ value: Bool, forKey defaultName: String) { defaults.set(value, forKey: defaultName) } @discardableResult @objc open func synchronize() -> Bool { return defaults.synchronize() } } public enum ArmchairKey: String, CustomStringConvertible { case FirstUseDate = "First Use Date" case UseCount = "Use Count" case SignificantEventCount = "Significant Event Count" case CurrentVersion = "Current Version" case RatedCurrentVersion = "Rated Current Version" case DeclinedToRate = "Declined To Rate" case ReminderRequestDate = "Reminder Request Date" case PreviousVersion = "Previous Version" case PreviousVersionRated = "Previous Version Rated" case PreviousVersionDeclinedToRate = "Previous Version Declined To Rate" case RatedAnyVersion = "Rated Any Version" case AppiraterMigrationCompleted = "Appirater Migration Completed" case UAAppReviewManagerMigrationCompleted = "UAAppReviewManager Migration Completed" static let allValues = [FirstUseDate, UseCount, SignificantEventCount, CurrentVersion, RatedCurrentVersion, DeclinedToRate, ReminderRequestDate, PreviousVersion, PreviousVersionRated, PreviousVersionDeclinedToRate, RatedAnyVersion, AppiraterMigrationCompleted, UAAppReviewManagerMigrationCompleted] public var description : String { get { return self.rawValue } } } open class ArmchairTrackingInfo: CustomStringConvertible { open let info: Dictionary<ArmchairKey, AnyObject> init(info: Dictionary<ArmchairKey, AnyObject>) { self.info = info } open var description: String { get { var description = "ArmchairTrackingInfo\r" for (key, val) in info { description += " - \(key): \(val)\r" } return description } } } public struct AppiraterKey { static var FirstUseDate = "kAppiraterFirstUseDate" static var UseCount = "kAppiraterUseCount" static var SignificantEventCount = "kAppiraterSignificantEventCount" static var CurrentVersion = "kAppiraterCurrentVersion" static var RatedCurrentVersion = "kAppiraterRatedCurrentVersion" static var RatedAnyVersion = "kAppiraterRatedAnyVersion" static var DeclinedToRate = "kAppiraterDeclinedToRate" static var ReminderRequestDate = "kAppiraterReminderRequestDate" } // MARK: - // MARK: PRIVATE Interface #if os(iOS) open class ArmchairManager : NSObject, SKStoreProductViewControllerDelegate { } #elseif os(OSX) open class ArmchairManager : NSObject, NSAlertDelegate { } #else // Untested, and currently unsupported #endif open class Manager : ArmchairManager { #if os(iOS) fileprivate var operatingSystemVersion = NSString(string: UIDevice.current.systemVersion).doubleValue #elseif os(OSX) private var operatingSystemVersion = Double(ProcessInfo.processInfo.operatingSystemVersion.majorVersion) #else #endif // MARK: - // MARK: Review Alert & Properties #if os(iOS) fileprivate var ratingAlert: UIAlertController? = nil fileprivate let reviewURLTemplate = "itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&id=APP_ID&at=AFFILIATE_CODE&ct=AFFILIATE_CAMPAIGN_CODE&action=write-review" fileprivate let reviewURLTemplateiOS11 = "https://itunes.apple.com/us/app/idAPP_ID?ls=1&mt=8&at=AFFILIATE_CODE&ct=AFFILIATE_CAMPAIGN_CODE&action=write-review" #elseif os(OSX) private var ratingAlert: NSAlert? = nil private let reviewURLTemplate = "macappstore://itunes.apple.com/us/app/idAPP_ID?ls=1&mt=12&at=AFFILIATE_CODE&ct=AFFILIATE_CAMPAIGN_CODE" #else #endif fileprivate lazy var appName: String = self.defaultAppName() fileprivate func defaultAppName() -> String { let mainBundle = Bundle.main let displayName = mainBundle.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String let bundleNameKey = kCFBundleNameKey as String let name = mainBundle.object(forInfoDictionaryKey: bundleNameKey) as? String return displayName ?? name ?? "This App" } fileprivate lazy var reviewTitle: String = self.defaultReviewTitle() fileprivate func defaultReviewTitle() -> String { var template = "Rate %@" // Check for a localized version of the default title if let bundle = self.bundle() { template = bundle.localizedString(forKey: template, value: bundle.localizedString(forKey: template, value:"", table: nil), table: "ArmchairLocalizable") } return template.replacingOccurrences(of: "%@", with: "\(self.appName)", options: NSString.CompareOptions(rawValue: 0), range: nil) } fileprivate lazy var reviewMessage: String = self.defaultReviewMessage() fileprivate func defaultReviewMessage() -> String { var template = "If you enjoy using %@, would you mind taking a moment to rate it? It won't take more than a minute. Thanks for your support!" // Check for a localized version of the default title if let bundle = self.bundle() { template = bundle.localizedString(forKey: template, value: bundle.localizedString(forKey: template, value:"", table: nil), table: "ArmchairLocalizable") } return template.replacingOccurrences(of: "%@", with: "\(self.appName)", options: NSString.CompareOptions(rawValue: 0), range: nil) } fileprivate lazy var cancelButtonTitle: String = self.defaultCancelButtonTitle() fileprivate func defaultCancelButtonTitle() -> String { var title = "No, Thanks" // Check for a localized version of the default title if let bundle = self.bundle() { title = bundle.localizedString(forKey: title, value: bundle.localizedString(forKey: title, value:"", table: nil), table: "ArmchairLocalizable") } return title } fileprivate lazy var rateButtonTitle: String = self.defaultRateButtonTitle() fileprivate func defaultRateButtonTitle() -> String { var template = "Rate %@" // Check for a localized version of the default title if let bundle = self.bundle() { template = bundle.localizedString(forKey: template, value: bundle.localizedString(forKey: template, value:"", table: nil), table: "ArmchairLocalizable") } return template.replacingOccurrences(of: "%@", with: "\(self.appName)", options: NSString.CompareOptions(rawValue: 0), range: nil) } fileprivate lazy var remindButtonTitle: String? = self.defaultRemindButtonTitle() fileprivate func defaultRemindButtonTitle() -> String? { //if reminders are disabled, return a nil title to supress the button if self.daysBeforeReminding == 0 { return nil } var title = "Remind me later" // Check for a localized version of the default title if let bundle = self.bundle() { title = bundle.localizedString(forKey: title, value: bundle.localizedString(forKey: title, value:"", table: nil), table: "ArmchairLocalizable") } return title } // Tracking Logic / Configuration fileprivate var appID: String = "" { didSet { keyPrefix = defaultKeyPrefix() if affiliateCampaignCode == defaultAffiliateCampaignCode() { affiliateCampaignCode = affiliateCampaignCode + "-\(appID)" } } } // MARK: Properties with sensible defaults fileprivate var daysUntilPrompt: UInt = 30 fileprivate var usesUntilPrompt: UInt = 20 fileprivate var significantEventsUntilPrompt: UInt = 0 fileprivate var daysBeforeReminding: UInt = 1 fileprivate var tracksNewVersions: Bool = true fileprivate var shouldPromptIfRated: Bool = true fileprivate var useMainAppBundleForLocalizations: Bool = false fileprivate var debugEnabled: Bool = false { didSet { if self.debugEnabled { debugLog("Debug enabled for app: \(appID)") } } } // If you aren't going to set an affiliate code yourself, please leave this as is. // It is my affiliate code. It is better that somebody's code is used rather than nobody's. fileprivate var affiliateCode: String = "11l7j9" fileprivate var affiliateCampaignCode: String = "Armchair" #if os(iOS) fileprivate var usesAnimation: Bool = true fileprivate var tintColor: UIColor? = nil fileprivate lazy var usesAlertController: Bool = self.defaultUsesAlertController() fileprivate lazy var opensInStoreKit: Bool = self.defaultOpensInStoreKit() fileprivate var useStoreKitReviewPrompt: Bool = false fileprivate func defaultOpensInStoreKit() -> Bool { return operatingSystemVersion >= 8 } fileprivate func defaultUsesAlertController() -> Bool { return operatingSystemVersion >= 9 } #endif // MARK: Tracking Keys with sensible defaults fileprivate lazy var armchairKeyFirstUseDate: String = self.defaultArmchairKeyFirstUseDate() fileprivate lazy var armchairKeyUseCount: String = self.defaultArmchairKeyUseCount() fileprivate lazy var armchairKeySignificantEventCount: String = self.defaultArmchairKeySignificantEventCount() fileprivate lazy var armchairKeyCurrentVersion: String = self.defaultArmchairKeyCurrentVersion() fileprivate lazy var armchairKeyRatedCurrentVersion: String = self.defaultArmchairKeyRatedCurrentVersion() fileprivate lazy var armchairKeyDeclinedToRate: String = self.defaultArmchairKeyDeclinedToRate() fileprivate lazy var armchairKeyReminderRequestDate: String = self.defaultArmchairKeyReminderRequestDate() fileprivate lazy var armchairKeyPreviousVersion: String = self.defaultArmchairKeyPreviousVersion() fileprivate lazy var armchairKeyPreviousVersionRated: String = self.defaultArmchairKeyPreviousVersionRated() fileprivate lazy var armchairKeyPreviousVersionDeclinedToRate: String = self.defaultArmchairKeyPreviousVersionDeclinedToRate() fileprivate lazy var armchairKeyRatedAnyVersion: String = self.defaultArmchairKeyRatedAnyVersion() fileprivate lazy var armchairKeyAppiraterMigrationCompleted: String = self.defaultArmchairKeyAppiraterMigrationCompleted() fileprivate lazy var armchairKeyUAAppReviewManagerMigrationCompleted: String = self.defaultArmchairKeyUAAppReviewManagerMigrationCompleted() fileprivate func defaultArmchairKeyFirstUseDate() -> String { return "ArmchairFirstUseDate" } fileprivate func defaultArmchairKeyUseCount() -> String { return "ArmchairUseCount" } fileprivate func defaultArmchairKeySignificantEventCount() -> String { return "ArmchairSignificantEventCount" } fileprivate func defaultArmchairKeyCurrentVersion() -> String { return "ArmchairKeyCurrentVersion" } fileprivate func defaultArmchairKeyRatedCurrentVersion() -> String { return "ArmchairRatedCurrentVersion" } fileprivate func defaultArmchairKeyDeclinedToRate() -> String { return "ArmchairKeyDeclinedToRate" } fileprivate func defaultArmchairKeyReminderRequestDate() -> String { return "ArmchairReminderRequestDate" } fileprivate func defaultArmchairKeyPreviousVersion() -> String { return "ArmchairPreviousVersion" } fileprivate func defaultArmchairKeyPreviousVersionRated() -> String { return "ArmchairPreviousVersionRated" } fileprivate func defaultArmchairKeyPreviousVersionDeclinedToRate() -> String { return "ArmchairPreviousVersionDeclinedToRate" } fileprivate func defaultArmchairKeyRatedAnyVersion() -> String { return "ArmchairKeyRatedAnyVersion" } fileprivate func defaultArmchairKeyAppiraterMigrationCompleted() -> String { return "ArmchairAppiraterMigrationCompleted" } fileprivate func defaultArmchairKeyUAAppReviewManagerMigrationCompleted() -> String { return "ArmchairUAAppReviewManagerMigrationCompleted" } fileprivate lazy var keyPrefix: String = self.defaultKeyPrefix() fileprivate func defaultKeyPrefix() -> String { if !self.appID.isEmpty { return self.appID + "_" } else { return "_" } } fileprivate var userDefaultsObject:ArmchairDefaultsObject? = StandardUserDefaults() // MARK: Optional Closures var didDisplayAlertClosure: ArmchairClosure? var didDeclineToRateClosure: ArmchairClosure? var didOptToRateClosure: ArmchairClosure? var didOptToRemindLaterClosure: ArmchairClosure? var customAlertClosure: ArmchairClosureCustomAlert? #if os(iOS) var willPresentModalViewClosure: ArmchairAnimateClosure? var didDismissModalViewClosure: ArmchairAnimateClosure? #endif var shouldPromptClosure: ArmchairShouldPromptClosure? var shouldIncrementUseCountClosure: ArmchairShouldIncrementClosure? // MARK: State Vars fileprivate var modalPanelOpen: Bool = false #if os(iOS) fileprivate lazy var currentStatusBarStyle: UIStatusBarStyle = { return UIApplication.shared.statusBarStyle }() #endif // MARK: - // MARK: PRIVATE Methods fileprivate func userDidSignificantEvent(_ canPromptForRating: Bool) { DispatchQueue.global(qos: .background).async { self.incrementSignificantEventAndRate(canPromptForRating) } } fileprivate func userDidSignificantEvent(_ shouldPrompt: @escaping ArmchairShouldPromptClosure) { DispatchQueue.global(qos: .background).async { self.incrementSignificantEventAndRate(shouldPrompt) } } // MARK: - // MARK: PRIVATE Rating Helpers fileprivate func incrementAndRate(_ canPromptForRating: Bool) { migrateKeysIfNecessary() incrementUseCount() showPrompt(ifNecessary: canPromptForRating) } fileprivate func incrementAndRate(_ shouldPrompt: ArmchairShouldPromptClosure) { migrateKeysIfNecessary() incrementUseCount() showPrompt(shouldPrompt) } fileprivate func incrementSignificantEventAndRate(_ canPromptForRating: Bool) { migrateKeysIfNecessary() incrementSignificantEventCount() showPrompt(ifNecessary: canPromptForRating) } fileprivate func incrementSignificantEventAndRate(_ shouldPrompt: ArmchairShouldPromptClosure) { migrateKeysIfNecessary() incrementSignificantEventCount() showPrompt(shouldPrompt) } fileprivate func incrementUseCount() { var shouldIncrement = true if let closure = shouldIncrementUseCountClosure { shouldIncrement = closure() } if shouldIncrement { _incrementCountForKeyType(ArmchairKey.UseCount) } } fileprivate func incrementSignificantEventCount() { _incrementCountForKeyType(ArmchairKey.SignificantEventCount) } fileprivate func _incrementCountForKeyType(_ incrementKeyType: ArmchairKey) { let incrementKey = keyForArmchairKeyType(incrementKeyType) let bundleVersionKey = kCFBundleVersionKey as String // App's version. Not settable as the other ivars because that would be crazy. let currentVersion = Bundle.main.object(forInfoDictionaryKey: bundleVersionKey) as? String if currentVersion == nil { assertionFailure("Could not read kCFBundleVersionKey from InfoDictionary") return } // Get the version number that we've been tracking thus far let currentVersionKey = keyForArmchairKeyType(ArmchairKey.CurrentVersion) var trackingVersion: String? = userDefaultsObject?.stringForKey(currentVersionKey) // New install, or changed keys if trackingVersion == nil { trackingVersion = currentVersion userDefaultsObject?.setObject(currentVersion as AnyObject?, forKey: currentVersionKey) } debugLog("Tracking version: \(trackingVersion!)") if trackingVersion == currentVersion { // Check if the first use date has been set. if not, set it. let firstUseDateKey = keyForArmchairKeyType(ArmchairKey.FirstUseDate) var timeInterval: Double? = userDefaultsObject?.doubleForKey(firstUseDateKey) if 0 == timeInterval { timeInterval = Date().timeIntervalSince1970 userDefaultsObject?.setObject(NSNumber(value: timeInterval!), forKey: firstUseDateKey) } // Increment the key's count var incrementKeyCount = userDefaultsObject!.integerForKey(incrementKey) incrementKeyCount += 1 userDefaultsObject?.setInteger(incrementKeyCount, forKey:incrementKey) debugLog("Incremented \(incrementKeyType): \(incrementKeyCount)") } else if tracksNewVersions { // it's a new version of the app, so restart tracking resetAllCounters() debugLog("Reset Tracking Version to: \(trackingVersion!)") } userDefaultsObject?.synchronize() } fileprivate func showPrompt(ifNecessary canPromptForRating: Bool) { if canPromptForRating && connectedToNetwork() && ratingConditionsHaveBeenMet() { var shouldPrompt: Bool = true if let closure = shouldPromptClosure { if Thread.isMainThread { shouldPrompt = closure(trackingInfo()) } else { DispatchQueue.main.sync { shouldPrompt = closure(self.trackingInfo()) } } } if shouldPrompt { DispatchQueue.main.async { self.showRatingAlert() } } } } fileprivate func showPrompt(_ shouldPrompt: ArmchairShouldPromptClosure) { var shouldPromptVal = false if Thread.isMainThread { shouldPromptVal = shouldPrompt(trackingInfo()) } else { DispatchQueue.main.sync { shouldPromptVal = shouldPrompt(self.trackingInfo()) } } if (shouldPromptVal) { DispatchQueue.main.async { self.showRatingAlert() } } } fileprivate func showPrompt() { if !appID.isEmpty && connectedToNetwork() && !userHasDeclinedToRate() && !userHasRatedCurrentVersion() { showRatingAlert() } } fileprivate func ratingConditionsHaveBeenMet() -> Bool { if debugEnabled { return true } if appID.isEmpty { return false } // check if the app has been used long enough let timeIntervalOfFirstLaunch = userDefaultsObject?.doubleForKey(keyForArmchairKeyType(ArmchairKey.FirstUseDate)) if let timeInterval = timeIntervalOfFirstLaunch { let dateOfFirstLaunch = Date(timeIntervalSince1970: timeInterval) let timeSinceFirstLaunch = Date().timeIntervalSince(dateOfFirstLaunch) let timeUntilRate: TimeInterval = 60 * 60 * 24 * Double(daysUntilPrompt) if timeSinceFirstLaunch < timeUntilRate { return false } } else { return false } // check if the app has been used enough times let useCount = userDefaultsObject?.integerForKey(keyForArmchairKeyType(ArmchairKey.UseCount)) if let count = useCount { if UInt(count) <= usesUntilPrompt { return false } } else { return false } // check if the user has done enough significant events let significantEventCount = userDefaultsObject?.integerForKey(keyForArmchairKeyType(ArmchairKey.SignificantEventCount)) if let count = significantEventCount { if UInt(count) < significantEventsUntilPrompt { return false } } else { return false } // Check if the user previously has declined to rate this version of the app if userHasDeclinedToRate() { return false } // Check if the user has already rated the app? if userHasRatedCurrentVersion() { return false } // If the user wanted to be reminded later, has enough time passed? let timeIntervalOfReminder = userDefaultsObject?.doubleForKey(keyForArmchairKeyType(ArmchairKey.ReminderRequestDate)) if let timeInterval = timeIntervalOfReminder { let reminderRequestDate = Date(timeIntervalSince1970: timeInterval) let timeSinceReminderRequest = Date().timeIntervalSince(reminderRequestDate) let timeUntilReminder: TimeInterval = 60 * 60 * 24 * Double(daysBeforeReminding) if timeSinceReminderRequest < timeUntilReminder { return false } } else { return false } // if we have a global set to not show if the end-user has already rated once, and the developer has not opted out of displaying on minor updates let ratedAnyVersion = userDefaultsObject?.boolForKey(keyForArmchairKeyType(ArmchairKey.RatedAnyVersion)) if let ratedAlready = ratedAnyVersion { if (!shouldPromptIfRated && ratedAlready) { return false } } return true } fileprivate func userHasDeclinedToRate() -> Bool { if let declined = userDefaultsObject?.boolForKey(keyForArmchairKeyType(ArmchairKey.DeclinedToRate)) { return declined } else { return false } } fileprivate func userHasRatedCurrentVersion() -> Bool { if let ratedCurrentVersion = userDefaultsObject?.boolForKey(keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion)) { return ratedCurrentVersion } else { return false } } fileprivate func showsRemindButton() -> Bool { return (daysBeforeReminding > 0 && remindButtonTitle != nil) } public var shouldTryStoreKitReviewPrompt : Bool { if #available(iOS 10.3, *), useStoreKitReviewPrompt { return true } return false } fileprivate func requestStoreKitReviewPrompt() -> Bool { if #available(iOS 10.3, *), useStoreKitReviewPrompt { SKStoreReviewController.requestReview() // Assume this version is rated. There is no API to tell if the user actaully rated. userDefaultsObject?.setBool(true, forKey: keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion)) userDefaultsObject?.setBool(true, forKey: keyForArmchairKeyType(ArmchairKey.RatedAnyVersion)) userDefaultsObject?.synchronize() closeModalPanel() return true } return false } fileprivate func showRatingAlert() { if let customClosure = customAlertClosure { customClosure({[weak self] in if let result = self?.requestStoreKitReviewPrompt(), result { ///Showed storekit prompt, all done } else { /// Didn't show storekit prompt, present app store manually self?._rateApp() } }, {[weak self] in self?.remindMeLater()}, {[weak self] in self?.dontRate()}) if let closure = self.didDisplayAlertClosure { closure() } } else { #if os(iOS) if requestStoreKitReviewPrompt() { ///Showed storekit prompt, all done } else { /// Didn't show storekit prompt, present app store manually let alertView : UIAlertController = UIAlertController(title: reviewTitle, message: reviewMessage, preferredStyle: UIAlertControllerStyle.alert) alertView.addAction(UIAlertAction(title: cancelButtonTitle, style:UIAlertActionStyle.default, handler: { (alert: UIAlertAction!) in self.dontRate() })) if (showsRemindButton()) { alertView.addAction(UIAlertAction(title: remindButtonTitle!, style:UIAlertActionStyle.default, handler: { (alert: UIAlertAction!) in self.remindMeLater() })) } alertView.addAction(UIAlertAction(title: rateButtonTitle, style:UIAlertActionStyle.cancel, handler: { (alert: UIAlertAction!) in self._rateApp() })) ratingAlert = alertView // get the top most controller (= the StoreKit Controller) and dismiss it if let presentingController = UIApplication.shared.keyWindow?.rootViewController { if let topController = Manager.topMostViewController(presentingController) { topController.present(alertView, animated: usesAnimation) { [weak self] in if let closure = self?.didDisplayAlertClosure { closure() } print("presentViewController() completed") } } // note that tint color has to be set after the controller is presented in order to take effect (last checked in iOS 9.3) alertView.view.tintColor = tintColor } } #elseif os(OSX) let alert: NSAlert = NSAlert() alert.messageText = reviewTitle alert.informativeText = reviewMessage alert.addButton(withTitle: rateButtonTitle) if showsRemindButton() { alert.addButton(withTitle: remindButtonTitle!) } alert.addButton(withTitle: cancelButtonTitle) ratingAlert = alert if let window = NSApplication.shared.keyWindow { alert.beginSheetModal(for: window) { (response: NSApplication.ModalResponse) in self.handleNSAlertResponse(response) } } else { let response = alert.runModal() handleNSAlertResponse(response) } if let closure = self.didDisplayAlertClosure { closure() } #else #endif } } // MARK: - // MARK: PRIVATE Alert View / StoreKit Delegate Methods #if os(iOS) //Delegate call from the StoreKit view. open func productViewControllerDidFinish(_ viewController: SKStoreProductViewController!) { closeModalPanel() } //Close the in-app rating (StoreKit) view and restore the previous status bar style. fileprivate func closeModalPanel() { let usedAnimation = usesAnimation if modalPanelOpen { UIApplication.shared.setStatusBarStyle(currentStatusBarStyle, animated:usesAnimation) modalPanelOpen = false // get the top most controller (= the StoreKit Controller) and dismiss it if let presentingController = UIApplication.shared.keyWindow?.rootViewController { if let topController = Manager.topMostViewController(presentingController) { topController.dismiss(animated: usesAnimation) {} currentStatusBarStyle = UIStatusBarStyle.default } } } if let closure = self.didDismissModalViewClosure { closure(usedAnimation) } } #elseif os(OSX) private func handleNSAlertResponse(_ response: NSApplication.ModalResponse) { switch (response) { case .alertFirstButtonReturn: // they want to rate it _rateApp() case .alertSecondButtonReturn: // remind them later or cancel if showsRemindButton() { remindMeLater() } else { dontRate() } case .alertThirdButtonReturn: // they don't want to rate it dontRate() default: return } } #else #endif private func dontRate() { userDefaultsObject?.setBool(true, forKey: keyForArmchairKeyType(ArmchairKey.DeclinedToRate)) userDefaultsObject?.synchronize() if let closure = didDeclineToRateClosure { closure() } } private func remindMeLater() { userDefaultsObject?.setDouble(Date().timeIntervalSince1970, forKey: keyForArmchairKeyType(ArmchairKey.ReminderRequestDate)) userDefaultsObject?.synchronize() if let closure = didOptToRemindLaterClosure { closure() } } private func _rateApp() { rateApp() if let closure = didOptToRateClosure { closure() } } fileprivate func rateApp() { userDefaultsObject?.setBool(true, forKey: keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion)) userDefaultsObject?.setBool(true, forKey: keyForArmchairKeyType(ArmchairKey.RatedAnyVersion)) userDefaultsObject?.synchronize() #if os(iOS) // Use the in-app StoreKit view if set, available (iOS 7+) and imported. This works in the simulator. if opensInStoreKit { let storeViewController = SKStoreProductViewController() var productParameters: [String:AnyObject]! = [SKStoreProductParameterITunesItemIdentifier : appID as AnyObject] if (operatingSystemVersion >= 8) { productParameters[SKStoreProductParameterAffiliateToken] = affiliateCode as AnyObject? productParameters[SKStoreProductParameterCampaignToken] = affiliateCampaignCode as AnyObject? } storeViewController.loadProduct(withParameters: productParameters, completionBlock: nil) storeViewController.delegate = self if let closure = willPresentModalViewClosure { closure(usesAnimation) } if let rootController = Manager.getRootViewController() { rootController.present(storeViewController, animated: usesAnimation) { self.modalPanelOpen = true //Temporarily use a status bar to match the StoreKit view. self.currentStatusBarStyle = UIApplication.shared.statusBarStyle UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.default, animated: self.usesAnimation) } } //Use the standard openUrl method } else { if let url = URL(string: reviewURLString()) { UIApplication.shared.openURL(url) } } // Check for iOS simulator #if (arch(i386) || arch(x86_64)) && os(iOS) debugLog("iTunes App Store is not supported on the iOS simulator.") debugLog(" - We would have went to \(reviewURLString()).") debugLog(" - Try running on a test-device") let fakeURL = reviewURLString().replacingOccurrences(of: "itms-apps", with:"http") debugLog(" - Or try copy/pasting \(fakeURL) into a browser on your computer.") #endif #elseif os(OSX) if let url = URL(string: reviewURLString()) { let opened = NSWorkspace.shared.open(url) if !opened { debugLog("Failed to open \(url)") } } #else #endif } fileprivate func reviewURLString() -> String { #if os(iOS) let template = operatingSystemVersion >= 11 ? reviewURLTemplateiOS11 : reviewURLTemplate #elseif os(OSX) let template = reviewURLTemplate #else #endif var reviewURL = template.replacingOccurrences(of: "APP_ID", with: "\(appID)") reviewURL = reviewURL.replacingOccurrences(of: "AFFILIATE_CODE", with: "\(affiliateCode)") reviewURL = reviewURL.replacingOccurrences(of: "AFFILIATE_CAMPAIGN_CODE", with: "\(affiliateCampaignCode)") return reviewURL } // Mark: - // Mark: PRIVATE Key Helpers private func trackingInfo() -> ArmchairTrackingInfo { var trackingInfo: Dictionary<ArmchairKey, AnyObject> = [:] for keyType in ArmchairKey.allValues { let obj: AnyObject? = userDefaultsObject?.objectForKey(keyForArmchairKeyType(keyType)) if let val = obj as? NSObject { trackingInfo[keyType] = val } else { trackingInfo[keyType] = NSNull() } } return ArmchairTrackingInfo(info: trackingInfo) } fileprivate func keyForArmchairKeyType(_ keyType: ArmchairKey) -> String { switch (keyType) { case .FirstUseDate: return keyPrefix + armchairKeyFirstUseDate case .UseCount: return keyPrefix + armchairKeyUseCount case .SignificantEventCount: return keyPrefix + armchairKeySignificantEventCount case .CurrentVersion: return keyPrefix + armchairKeyCurrentVersion case .RatedCurrentVersion: return keyPrefix + armchairKeyRatedCurrentVersion case .DeclinedToRate: return keyPrefix + armchairKeyDeclinedToRate case .ReminderRequestDate: return keyPrefix + armchairKeyReminderRequestDate case .PreviousVersion: return keyPrefix + armchairKeyPreviousVersion case .PreviousVersionRated: return keyPrefix + armchairKeyPreviousVersionRated case .PreviousVersionDeclinedToRate: return keyPrefix + armchairKeyPreviousVersionDeclinedToRate case .RatedAnyVersion: return keyPrefix + armchairKeyRatedAnyVersion case .AppiraterMigrationCompleted: return keyPrefix + armchairKeyAppiraterMigrationCompleted case .UAAppReviewManagerMigrationCompleted: return keyPrefix + armchairKeyUAAppReviewManagerMigrationCompleted } } fileprivate func setKey(_ key: NSString, armchairKeyType: ArmchairKey) { switch armchairKeyType { case .FirstUseDate: armchairKeyFirstUseDate = key as String case .UseCount: armchairKeyUseCount = key as String case .SignificantEventCount: armchairKeySignificantEventCount = key as String case .CurrentVersion: armchairKeyCurrentVersion = key as String case .RatedCurrentVersion: armchairKeyRatedCurrentVersion = key as String case .DeclinedToRate: armchairKeyDeclinedToRate = key as String case .ReminderRequestDate: armchairKeyReminderRequestDate = key as String case .PreviousVersion: armchairKeyPreviousVersion = key as String case .PreviousVersionRated: armchairKeyPreviousVersionRated = key as String case .PreviousVersionDeclinedToRate: armchairKeyPreviousVersionDeclinedToRate = key as String case .RatedAnyVersion: armchairKeyRatedAnyVersion = key as String case .AppiraterMigrationCompleted: armchairKeyAppiraterMigrationCompleted = key as String case .UAAppReviewManagerMigrationCompleted: armchairKeyUAAppReviewManagerMigrationCompleted = key as String } } private func armchairKeyForAppiraterKey(_ appiraterKey: String) -> String { switch appiraterKey { case AppiraterKey.FirstUseDate: return keyForArmchairKeyType(ArmchairKey.FirstUseDate) case AppiraterKey.UseCount: return keyForArmchairKeyType(ArmchairKey.UseCount) case AppiraterKey.SignificantEventCount: return keyForArmchairKeyType(ArmchairKey.SignificantEventCount) case AppiraterKey.CurrentVersion: return keyForArmchairKeyType(ArmchairKey.CurrentVersion) case AppiraterKey.RatedCurrentVersion: return keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion) case AppiraterKey.DeclinedToRate: return keyForArmchairKeyType(ArmchairKey.DeclinedToRate) case AppiraterKey.ReminderRequestDate: return keyForArmchairKeyType(ArmchairKey.ReminderRequestDate) case AppiraterKey.RatedAnyVersion: return keyForArmchairKeyType(ArmchairKey.RatedAnyVersion) default: return "" } } private func migrateAppiraterKeysIfNecessary() { let appiraterAlreadyCompletedKey: NSString = keyForArmchairKeyType(.AppiraterMigrationCompleted) as NSString let appiraterMigrationAlreadyCompleted = userDefaultsObject?.boolForKey(appiraterAlreadyCompletedKey as String) if let completed = appiraterMigrationAlreadyCompleted { if completed { return } } let oldKeys: [String] = [AppiraterKey.FirstUseDate, AppiraterKey.UseCount, AppiraterKey.SignificantEventCount, AppiraterKey.CurrentVersion, AppiraterKey.RatedCurrentVersion, AppiraterKey.RatedAnyVersion, AppiraterKey.DeclinedToRate, AppiraterKey.ReminderRequestDate] for oldKey in oldKeys { let oldValue: NSObject? = userDefaultsObject?.objectForKey(oldKey) as? NSObject if let val = oldValue { let newKey = armchairKeyForAppiraterKey(oldKey) userDefaultsObject?.setObject(val, forKey: newKey) userDefaultsObject?.removeObjectForKey(oldKey) } } userDefaultsObject?.setObject(NSNumber(value: true), forKey: appiraterAlreadyCompletedKey as String) userDefaultsObject?.synchronize() } // This only supports the default UAAppReviewManager keys. If you customized them, you will have to manually migrate your values over. private func migrateUAAppReviewManagerKeysIfNecessary() { let appReviewManagerAlreadyCompletedKey: NSString = keyForArmchairKeyType(.UAAppReviewManagerMigrationCompleted) as NSString let appReviewManagerMigrationAlreadyCompleted = userDefaultsObject?.boolForKey(appReviewManagerAlreadyCompletedKey as String) if let completed = appReviewManagerMigrationAlreadyCompleted { if completed { return } } // By default, UAAppReviewManager keys are in the format <appID>_UAAppReviewManagerKey<keyType> let oldKeys: [String:ArmchairKey] = ["\(appID)_UAAppReviewManagerKeyFirstUseDate" : ArmchairKey.FirstUseDate, "\(appID)_UAAppReviewManagerKeyUseCount" : ArmchairKey.UseCount, "\(appID)_UAAppReviewManagerKeySignificantEventCount" : ArmchairKey.SignificantEventCount, "\(appID)_UAAppReviewManagerKeyCurrentVersion" : ArmchairKey.CurrentVersion, "\(appID)_UAAppReviewManagerKeyRatedCurrentVersion" : ArmchairKey.RatedCurrentVersion, "\(appID)_UAAppReviewManagerKeyDeclinedToRate" : ArmchairKey.DeclinedToRate, "\(appID)_UAAppReviewManagerKeyReminderRequestDate" : ArmchairKey.ReminderRequestDate, "\(appID)_UAAppReviewManagerKeyPreviousVersion" : ArmchairKey.PreviousVersion, "\(appID)_UAAppReviewManagerKeyPreviousVersionRated" : ArmchairKey.PreviousVersionRated, "\(appID)_UAAppReviewManagerKeyPreviousVersionDeclinedToRate" : ArmchairKey.PreviousVersionDeclinedToRate, "\(appID)_UAAppReviewManagerKeyRatedAnyVersion" : ArmchairKey.RatedAnyVersion] for (oldKey, newKeyType) in oldKeys { let oldValue: NSObject? = userDefaultsObject?.objectForKey(oldKey) as? NSObject if let val = oldValue { userDefaultsObject?.setObject(val, forKey: keyForArmchairKeyType(newKeyType)) userDefaultsObject?.removeObjectForKey(oldKey) } } userDefaultsObject?.setObject(NSNumber(value: true), forKey: appReviewManagerAlreadyCompletedKey as String) userDefaultsObject?.synchronize() } private func migrateKeysIfNecessary() { migrateAppiraterKeysIfNecessary() migrateUAAppReviewManagerKeysIfNecessary() } // MARK: - // MARK: Internet Connectivity private func connectedToNetwork() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { SCNetworkReachabilityCreateWithAddress(nil, $0) } }) else { return false } var flags : SCNetworkReachabilityFlags = [] if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) { return false } let isReachable = flags.contains(.reachable) let needsConnection = flags.contains(.connectionRequired) return (isReachable && !needsConnection) } // MARK: - // MARK: PRIVATE Misc Helpers private func bundle() -> Bundle? { var bundle: Bundle? = nil if useMainAppBundleForLocalizations { bundle = Bundle.main } else { let armchairBundleURL: URL? = Bundle.main.url(forResource: "Armchair", withExtension: "bundle") if let url = armchairBundleURL { bundle = Bundle(url: url) } else { bundle = Bundle(for: type(of: self)) } } return bundle } #if os(iOS) private static func topMostViewController(_ controller: UIViewController?) -> UIViewController? { var isPresenting: Bool = false var topController: UIViewController? = controller repeat { // this path is called only on iOS 6+, so -presentedViewController is fine here. if let controller = topController { if let presented = controller.presentedViewController { isPresenting = true topController = presented } else { isPresenting = false } } } while isPresenting return topController } private static func getRootViewController() -> UIViewController? { if var window = UIApplication.shared.keyWindow { if window.windowLevel != UIWindowLevelNormal { let windows: NSArray = UIApplication.shared.windows as NSArray for candidateWindow in windows { if let candidateWindow = candidateWindow as? UIWindow { if candidateWindow.windowLevel == UIWindowLevelNormal { window = candidateWindow break } } } } return iterateSubViewsForViewController(window) } return nil } private static func iterateSubViewsForViewController(_ parentView: UIView) -> UIViewController? { for subView in parentView.subviews { if let responder = subView.next { if responder.isKind(of: UIViewController.self) { return topMostViewController(responder as? UIViewController) } } if let found = iterateSubViewsForViewController(subView) { return found } } return nil } #endif private func hideRatingAlert() { if let alert = ratingAlert { debugLog("Hiding Alert") #if os(iOS) let isAlertVisible = alert.isViewLoaded && alert.view.window != nil if isAlertVisible { alert.dismiss(animated: false, completion: { self.dontRate() }) } #elseif os(OSX) if let window = NSApplication.shared.keyWindow { if let parent = window.sheetParent { parent.endSheet(window) } } #else #endif ratingAlert = nil } } fileprivate func defaultAffiliateCode() -> String { return "11l7j9" } fileprivate func defaultAffiliateCampaignCode() -> String { return "Armchair" } // MARK: - // MARK: Notification Handlers @objc public func appWillResignActive(_ notification: Notification) { debugLog("appWillResignActive:") hideRatingAlert() } @objc public func applicationDidFinishLaunching(_ notification: Notification) { DispatchQueue.global(qos: .background).async { self.debugLog("applicationDidFinishLaunching:") self.migrateKeysIfNecessary() self.incrementUseCount() } } @objc public func applicationWillEnterForeground(_ notification: Notification) { DispatchQueue.global(qos: .background).async { self.debugLog("applicationWillEnterForeground:") self.migrateKeysIfNecessary() self.incrementUseCount() } } // MARK: - // MARK: Singleton public class var defaultManager: Manager { assert(Armchair.appID != "", "Armchair.appID(appID: String) has to be the first Armchair call made.") struct Singleton { static let instance: Manager = Manager(appID: Armchair.appID) } return Singleton.instance } init(appID: String) { super.init() setupNotifications() } // MARK: Singleton Instance Setup fileprivate func setupNotifications() { #if os(iOS) NotificationCenter.default.addObserver(self, selector: #selector(Manager.appWillResignActive(_:)), name: NSNotification.Name.UIApplicationWillResignActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(Manager.applicationDidFinishLaunching(_:)), name: NSNotification.Name.UIApplicationDidFinishLaunching, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(Manager.applicationWillEnterForeground(_:)), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil) #elseif os(OSX) NotificationCenter.default.addObserver(self, selector: #selector(Manager.appWillResignActive(_:)), name: NSApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(Manager.applicationDidFinishLaunching(_:)), name: NSApplication.didFinishLaunchingNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(Manager.applicationWillEnterForeground(_:)), name: NSApplication.willBecomeActiveNotification, object: nil) #else #endif } // MARK: - // MARK: Printable override open var debugDescription: String { get { return "Armchair: appID=\(Armchair.appID)" } } // MARK: - // MARK: Debug let lockQueue = DispatchQueue(label: "com.armchair.lockqueue") public var logger: ArmchairLogger = { manager, log, file, function, line in if manager.debugEnabled { manager.lockQueue.sync(execute: { print("[Armchair] \(log)") }) } } fileprivate func debugLog(_ log: String, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) { logger(self, log, file, function, line) } }
56b793ce4ba36e911c8509e1615e1896
42.622924
302
0.66108
false
false
false
false
budbee/SelfieKit
refs/heads/master
SelfieKit/Classes/FaceView.swift
mit
1
// // FaceView.swift // SelfieKit // // Created by Axel Möller on 29/04/16. // Copyright © 2016 Budbee AB. All rights reserved. // import UIKit class FaceView: UIView { lazy var ellipseView: UIImageView = { [unowned self] in let ellipseView = UIImageView() ellipseView.image = self.getImage("faceOverlay") ellipseView.translatesAutoresizingMaskIntoConstraints = false return ellipseView }() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clear translatesAutoresizingMaskIntoConstraints = false [ellipseView].forEach { addSubview($0) } setupConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupConstraints() { let attributes: [NSLayoutAttribute] = [.centerX, .centerY, .width, .height] for attribute in attributes { addConstraint(NSLayoutConstraint(item: ellipseView, attribute: attribute, relatedBy: .equal, toItem: self, attribute: attribute, multiplier: 1, constant: 0)) } } func getImage(_ name: String) -> UIImage { let traitCollection = UITraitCollection(displayScale: 3) var bundle = Bundle(for: self.classForCoder) let bundlePath = (Bundle(for: self.classForCoder).resourcePath)! + "/SelfieKit.bundle" let resourceBundle = Bundle(path: bundlePath) if nil != resourceBundle { bundle = resourceBundle! } guard let image = UIImage(named: name, in: bundle, compatibleWith: traitCollection) else { return UIImage() } return image } }
691c61296b847ae362de2a35f0a7ff0b
28.733333
169
0.613789
false
false
false
false
chandanthepsi/google-maps-ios-utils
refs/heads/master
samples/SwiftDemoApp/SwiftDemoApp/ViewController.swift
apache-2.0
1
/* Copyright (c) 2016 Google Inc. * * 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 GoogleMaps import UIKit /// Point of Interest Item which implements the GMUClusterItem protocol. class POIItem: NSObject, GMUClusterItem { var position: CLLocationCoordinate2D var name: String! init(position: CLLocationCoordinate2D, name: String) { self.position = position self.name = name } } let kClusterItemCount = 10000 let kCameraLatitude = -33.8 let kCameraLongitude = 151.2 class ViewController: UIViewController, GMUClusterManagerDelegate, GMSMapViewDelegate { fileprivate var mapView: GMSMapView! fileprivate var clusterManager: GMUClusterManager! override func loadView() { let camera = GMSCameraPosition.camera(withLatitude: kCameraLatitude, longitude: kCameraLongitude, zoom: 10) mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera) self.view = mapView } override func viewDidLoad() { super.viewDidLoad() // Set up the cluster manager with default icon generator and renderer. let iconGenerator = GMUDefaultClusterIconGenerator() let algorithm = GMUNonHierarchicalDistanceBasedAlgorithm() let renderer = GMUDefaultClusterRenderer(mapView: mapView, clusterIconGenerator: iconGenerator) clusterManager = GMUClusterManager(map: mapView, algorithm: algorithm, renderer: renderer) // Generate and add random items to the cluster manager. generateClusterItems() // Call cluster() after items have been added to perform the clustering and rendering on map. clusterManager.cluster() // Register self to listen to both GMUClusterManagerDelegate and GMSMapViewDelegate events. clusterManager.setDelegate(self, mapDelegate: self) } // MARK: - GMUClusterManagerDelegate @objc func clusterManager(_ clusterManager: GMUClusterManager, didTap cluster: GMUCluster) { let newCamera = GMSCameraPosition.camera(withTarget: cluster.position, zoom: mapView.camera.zoom + 1) let update = GMSCameraUpdate.setCamera(newCamera) mapView.moveCamera(update) } // MARK: - GMUMapViewDelegate func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool { if let poiItem = marker.userData as? POIItem { NSLog("Did tap marker for cluster item \(poiItem.name)") } else { NSLog("Did tap a normal marker") } return false } // MARK: - Private /// Randomly generates cluster items within some extent of the camera and adds them to the /// cluster manager. fileprivate func generateClusterItems() { let extent = 0.2 for index in 1...kClusterItemCount { let lat = kCameraLatitude + extent * randomScale() let lng = kCameraLongitude + extent * randomScale() let name = "Item \(index)" let item = POIItem(position: CLLocationCoordinate2DMake(lat, lng), name: name) clusterManager.add(item) } } /// Returns a random value between -1.0 and 1.0. fileprivate func randomScale() -> Double { return Double(arc4random()) / Double(UINT32_MAX) * 2.0 - 1.0 } }
2c6613becc745697940c9a01b429a846
33.298077
99
0.731147
false
false
false
false
hrscy/TodayNews
refs/heads/master
News/News/Classes/Huoshan/View/SmallVideoCell.swift
mit
1
// // SmallVideoCell.swift // News // // Created by 杨蒙 on 2018/1/16. // Copyright © 2018年 hrscy. All rights reserved. // import UIKit import IBAnimatable import Kingfisher import BMPlayer import SnapKit import NVActivityIndicatorView class SmallVideoCell: UICollectionViewCell, RegisterCellFromNib { var didSelectAvatarOrNameButton: (()->())? var smallVideo = NewsModel() { didSet { bgImageView.image = nil nameButton.setTitle(smallVideo.raw_data.user.info.name, for: .normal) avatarButton.kf.setImage(with: URL(string: smallVideo.raw_data.user.info.avatar_url), for: .normal) vImageView.isHidden = !smallVideo.raw_data.user.info.user_verified concernButton.isSelected = smallVideo.raw_data.user.relation.is_following titleLabel.attributedText = smallVideo.raw_data.attrbutedText } } /// 头像按钮 @IBOutlet weak var avatarButton: AnimatableButton! @IBOutlet weak var vImageView: UIImageView! /// 用户名按钮 @IBOutlet weak var nameButton: AnimatableButton! /// 关注按钮 @IBOutlet weak var concernButton: AnimatableButton! /// 标题 @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var scrollLabel: UILabel! @IBOutlet weak var bgImageView: UIImageView! /// 关注按钮点击 @IBAction func concernButtonClicked(_ sender: UIButton) { if sender.isSelected { // 已经关注,点击则取消关注 // 已关注用户,取消关注 NetworkTool.loadRelationUnfollow(userId: smallVideo.raw_data.user.info.user_id, completionHandler: { (_) in sender.isSelected = !sender.isSelected sender.theme_backgroundColor = "colors.globalRedColor" }) } else { // 未关注,点击则关注这个用户 // 点击关注按钮,关注用户 NetworkTool.loadRelationFollow(userId: smallVideo.raw_data.user.info.user_id, completionHandler: { (_) in sender.isSelected = !sender.isSelected sender.theme_backgroundColor = "colors.userDetailFollowingConcernBtnBgColor" }) } } /// 头像按钮或用户名按钮点击 @IBAction func avatarButtonClicked(_ sender: AnimatableButton) { didSelectAvatarOrNameButton?() } override func awakeFromNib() { super.awakeFromNib() } }
c0b2293aaf04181682d5a967c8b85070
31.180556
119
0.64782
false
false
false
false
shamanskyh/Precircuiter
refs/heads/main
Precircuiter/Models/Instrument.swift
mit
1
// // Instrument.swift // Precircuiter // // Created by Harry Shamansky on 7/26/14. // Copyright © 2014 Harry Shamansky. All rights reserved. // import Cocoa // MARK: - Enumerations enum DeviceType { case light case movingLight case accessory case staticAccessory case device case practical case sfx case power case other var description: String { switch self { case .light: return "Light" case .movingLight: return "MovingLight" case .accessory: return "Accessory" case .staticAccessory: return "StaticAccessory" case .device: return "Device" case .practical: return "Practical" case .sfx: return "SFX" case .power: return "Power" case .other: return "Other" } } } enum Patcher: Int { case unknown case outsideOfApplication // VWX, Lightwright, or other case auto // Automatically assigned case manual // Manually assigned *in Precircuiter* } enum Dimension { case x case y case z } // MARK: - Structs struct Coordinate { var x: Double var y: Double var z: Double init(xPos: Double, yPos: Double, zPos: Double) { x = xPos y = yPos z = zPos } } // MARK: - Instrument Class class Instrument: NSObject { var dummyInstrument: Bool var undoManager: UndoManager? = nil var deviceType: DeviceType? = nil @objc var instrumentType: String? = nil { willSet { undoManager?.registerUndo(withTarget: self, selector: #selector(setter: Instrument.instrumentType), object: instrumentType) undoManager?.setActionName("Modify Instrument Type") } } @objc var wattage: String? = nil { willSet { undoManager?.registerUndo(withTarget: self, selector: #selector(setter: Instrument.wattage), object: wattage) undoManager?.setActionName("Modify Wattage") } } @objc var purpose: String? = nil { willSet { undoManager?.registerUndo(withTarget: self, selector: #selector(setter: Instrument.purpose), object: purpose) undoManager?.setActionName("Modify Purpose") } } @objc var position: String? = nil { willSet { undoManager?.registerUndo(withTarget: self, selector: #selector(setter: Instrument.position), object: position) undoManager?.setActionName("Modify Position") } } @objc var unitNumber: String? = nil { willSet { undoManager?.registerUndo(withTarget: self, selector: #selector(setter: Instrument.unitNumber), object: unitNumber) undoManager?.setActionName("Modify Unit Number") } } @objc var color: String? = nil { willSet { undoManager?.registerUndo(withTarget: self, selector: #selector(setter: Instrument.color), object: color) undoManager?.setActionName("Modify Color") } } @objc var dimmer: String? = nil { willSet { undoManager?.registerUndo(withTarget: self, selector: #selector(setter: Instrument.dimmer), object: dimmer) undoManager?.setActionName("Modify Dimmer") } } @objc var channel: String? = nil { willSet { undoManager?.registerUndo(withTarget: self, selector: #selector(setter: Instrument.channel), object: channel) undoManager?.setActionName("Modify Channel") } } var address: String? = nil var universe: String? = nil var uAddress: String? = nil var uDimmer: String? = nil var circuitNumber: String? = nil var circuitName: String? = nil var system: String? = nil var userField1: String? = nil var userField2: String? = nil var userField3: String? = nil var userField4: String? = nil var userField5: String? = nil var userField6: String? = nil var numChannels: String? = nil var frameSize: String? = nil var fieldAngle: String? = nil var fieldAngle2: String? = nil var beamAngle: String? = nil var beamAngle2: String? = nil var weight: String? = nil @objc var gobo1: String? = nil { willSet { undoManager?.registerUndo(withTarget: self, selector: #selector(setter: Instrument.gobo1), object: gobo1) undoManager?.setActionName("Modify Gobo 1") } } var gobo1Rotation: String? = nil var gobo2: String? = nil var gobo2Rotation: String? = nil var goboShift: String? = nil var mark: String? = nil var drawBeam: Bool? = nil var drawBeamAs3DSolid: Bool? = nil var useVerticalBeam: Bool? = nil var showBeamAt: String? = nil var falloffDistance: String? = nil var lampRotationAngle: String? = nil var topShutterDepth: String? = nil var topShutterAngle: String? = nil var leftShutterDepth: String? = nil var leftShutterAngle: String? = nil var rightShutterDepth: String? = nil var rightShutterAngle: String? = nil var bottomShutterDepth: String? = nil var bottomShutterAngle: String? = nil var symbolName: String? = nil var useLegend: Bool? = nil var flipFrontBackLegendText: Bool? = nil var flipLeftRightLegendText: Bool? = nil var focus: String? = nil var set3DOrientation: Bool? = nil var xRotation: String? = nil var yRotation: String? = nil var locations: [Coordinate] = [] var rawXLocation: String? = nil var rawYLocation: String? = nil var rawZLocation: String? = nil var fixtureID: String? = nil var UID: String var accessories: String? = nil // MARK: - Binding Properties @objc var secondarySortKey: String? { if self.position != nil || self.unitNumber != nil { return "\(self.position ?? "")\(self.unitNumber ?? "")" } return nil } private var savedSwatchColor: NSColor? private var isClearColor: Bool { return color?.trimmingCharacters(in: .whitespaces) == "N/C" || color?.trimmingCharacters(in: .whitespaces) == "NC" } internal var needsNewSwatchColor = false internal var swatchColor: NSColor? { if (savedSwatchColor == nil && color != nil) || needsNewSwatchColor { needsNewSwatchColor = false if let color = self.color?.toGelColor() { savedSwatchColor = NSColor(cgColor: color) } else { savedSwatchColor = nil } } return savedSwatchColor } // MARK: - Drawing for PlotView internal var selected: Bool = false internal var needsNewViewRepresentation = false private var savedView: NSView? internal var viewRepresentation: NSView { if savedView != nil && needsNewViewRepresentation == false { return savedView! } needsNewViewRepresentation = false if let v = savedView { v.removeFromSuperview() savedView = nil } if self.deviceType == .power { let view = DimmerSymbolView() view.frame.size = kDefaultDimmerSymbolSize view.dimmer = self.dimmer view.dimmerInstrument = self self.savedView = view return view } let view = LightSymbolView() view.selected = self.selected view.frame.size = kDefaultLightSymbolSize view.channel = self.channel view.lightInstrument = self view.color = self.isClearColor ? nil : self.swatchColor self.savedView = view return view } internal func setViewRepresentationFrame(_ frame: CGRect) { self.savedView?.frame = frame } // MARK: - Other Functions // use only if power @objc weak var light: Instrument? = nil { willSet { undoManager?.registerUndo(withTarget: self, selector: #selector(setter: Instrument.light), object: light) } } // use only if non-power @objc weak var receptacle: Instrument? = nil { willSet { undoManager?.registerUndo(withTarget: self, selector: #selector(setter: Instrument.receptacle), object: receptacle) } } // to determine who patched var assignedBy: Patcher = Patcher.unknown /// private helper function to allow the assignedBy variable to be set with an object internal func setAssignedByWithObject(_ value: NSNumber) { self.assignedBy = Patcher(rawValue: value.intValue)! } required init(UID: String?, location: [Coordinate]?, undoManager: UndoManager? = nil) { if let id = UID { self.UID = id } else { self.UID = "" } if let loc = location { self.locations = loc } else { self.locations = [] } self.undoManager = undoManager self.dummyInstrument = false } func addCoordinateToInitialLocation(_ type: Dimension, value: String) throws { var coord = self.locations.first if coord == nil { coord = Coordinate(xPos: 0.0, yPos: 0.0, zPos: 0.0) } else if self.locations.count > 1 { throw InstrumentError.ambiguousLocation } var convertedValue: Double = 0.0; do { try convertedValue = value.unknownUnitToMeters() } catch { throw InstrumentError.unrecognizedCoordinate } switch type { case .x: coord!.x = convertedValue case .y: coord!.y = convertedValue case .z: coord!.z = convertedValue } self.locations = [coord!] } /// Overrides the description and prints a custom description. /// Used in the tool tooltip of the plot view. override var description: String { var runningString = "" if self.deviceType == .light, let channel = self.channel { runningString += "Light (\(channel))" if let dimmer = self.dimmer { runningString += "\nDimmer [\(dimmer)]" } runningString += "" } else if self.deviceType == .power, let dimmer = self.dimmer { runningString += "Dimmer [\(dimmer)]" if let light = self.light, let channel = light.channel { runningString += "\nChannel (\(channel))" } } else if let deviceType = self.deviceType?.description { runningString += deviceType } if let position = self.position { if let unitNumber = self.unitNumber { runningString += "\n—\n\(position), Unit \(unitNumber)" } else { runningString += "\n—\n\(position)" } } else if let unitNumber = self.unitNumber { runningString += "\n—\nUnit \(unitNumber)" } if let instrumentType = self.instrumentType { runningString += ("\n—\n" + instrumentType) } if let wattage = self.wattage { runningString += ("\n" + wattage) } if let purpose = self.purpose { runningString += ("\n—\n" + purpose) } if let color = self.color { runningString += ("\n" + color) } if let gobo = self.gobo1 { runningString += ("\n" + gobo) } guard runningString.count > 0 else { return super.description } return runningString } } // MARK: - NSCopying Protocol Conformance extension Instrument: NSCopying { func copy(with zone: NSZone?) -> Any { let copy = type(of: self).init(UID: self.UID, location: self.locations, undoManager: self.undoManager) copy.undoManager = self.undoManager copy.dummyInstrument = self.dummyInstrument copy.deviceType = self.deviceType copy.instrumentType = self.instrumentType copy.wattage = self.wattage copy.purpose = self.purpose copy.position = self.position copy.unitNumber = self.unitNumber copy.color = self.color copy.dimmer = self.dimmer copy.channel = self.channel copy.address = self.address copy.universe = self.universe copy.uAddress = self.uAddress copy.uDimmer = self.uDimmer copy.circuitNumber = self.circuitNumber copy.circuitName = self.circuitName copy.system = self.system copy.userField1 = self.userField1 copy.userField2 = self.userField2 copy.userField3 = self.userField3 copy.userField4 = self.userField4 copy.userField5 = self.userField5 copy.userField6 = self.userField6 copy.numChannels = self.numChannels copy.frameSize = self.frameSize copy.fieldAngle = self.fieldAngle copy.fieldAngle2 = self.fieldAngle2 copy.beamAngle = self.beamAngle copy.beamAngle2 = self.beamAngle2 copy.weight = self.weight copy.gobo1 = self.gobo1 copy.gobo1Rotation = self.gobo1Rotation copy.gobo2 = self.gobo2 copy.gobo2Rotation = self.gobo2Rotation copy.goboShift = self.goboShift copy.mark = self.mark copy.drawBeam = self.drawBeam copy.drawBeamAs3DSolid = self.drawBeamAs3DSolid copy.useVerticalBeam = self.useVerticalBeam copy.showBeamAt = self.showBeamAt copy.falloffDistance = self.falloffDistance copy.lampRotationAngle = self.lampRotationAngle copy.topShutterDepth = self.topShutterDepth copy.topShutterAngle = self.topShutterAngle copy.leftShutterDepth = self.leftShutterDepth copy.leftShutterAngle = self.leftShutterAngle copy.rightShutterDepth = self.rightShutterDepth copy.rightShutterAngle = self.rightShutterAngle copy.bottomShutterDepth = self.bottomShutterDepth copy.bottomShutterAngle = self.bottomShutterAngle copy.symbolName = self.symbolName copy.useLegend = self.useLegend copy.flipFrontBackLegendText = self.flipFrontBackLegendText copy.flipLeftRightLegendText = self.flipLeftRightLegendText copy.focus = self.focus copy.set3DOrientation = self.set3DOrientation copy.xRotation = self.xRotation copy.yRotation = self.yRotation copy.rawXLocation = self.rawXLocation copy.rawYLocation = self.rawYLocation copy.rawZLocation = self.rawZLocation copy.fixtureID = self.fixtureID copy.accessories = self.accessories copy.light = self.light copy.receptacle = self.receptacle copy.assignedBy = self.assignedBy return copy } }
610359b01c9b46421087695cf9894d15
32.656885
135
0.605634
false
false
false
false
NigelJu/bloodDonatedTW
refs/heads/master
BloodDonated/BloodDonated/Class/ViewControllers/NearInfo/DetailNearInfoViewController.swift
mit
1
// // DetailNearInfoViewController.swift // 捐血趣 // // Created by Nigel on 2018/2/27. // Copyright © 2018年 Nigel. All rights reserved. // import UIKit import CoreLocation class DetailNearInfoViewController: UIViewController { @IBOutlet weak var stationTitleLabel: UILabel! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var commentLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var phoneLabel: UILabel! // 由外部傳遞資料 var info: LocationInfo? override func viewDidLoad() { super.viewDidLoad() stationTitleLabel.text = info?.name addressLabel.text = info?.address commentLabel.text = info?.comment phoneLabel.text = info?.phone timeLabel.text = info?.time } @IBAction func dialButtonDidSelect(_ sender: Any) { guard let phone = info?.phone, phone.count > 0 else { UIAlertController.alert(title: "警告", message: "無此站號碼").otherHandle(alertAction: nil).show(currentVC: self) return } let phoneUrl = "tel://" + phone if !successOpenUrl(withString: phoneUrl) { print("GG") } } @IBAction func navigationButtonDidSelect(_ sender: Any) { UIAlertController.alert(title: "請選擇導航app", message: "若無法開啟您所選擇的app, 將為您導至appStore", style: .actionSheet) .otherHandle(title: "AppleMap") { (action) in guard let geoCode = self.info?.geoCode else { return } self.successOpenUrl(withString: "http://maps.apple.com/?daddr=" + geoCode) }.otherHandle(title: "GoogleMap", alertAction: { (action) in guard let geoCode = self.info?.geoCode else { return } // 導至appleStore if !self.successOpenUrl(withString: "comgooglemaps://?saddr=&daddr=" + geoCode) { self.successOpenUrl(withString: "itms-apps://itunes.apple.com/app/id585027354") } }).cancleHandle(alertAction: nil) .show(currentVC: self) } } extension DetailNearInfoViewController { // 是否成功開啟url @discardableResult fileprivate func successOpenUrl(withString urlString: String) -> Bool { guard let url = URL(string: urlString), UIApplication.shared.canOpenURL(url) else { return false } UIApplication.shared.open(url, options: [:], completionHandler: nil) return true } }
242457501a150cee8a695bafdc108696
29.752941
122
0.589901
false
false
false
false
kinddevelopment/nursing-ios
refs/heads/master
Pods/EVReflection/Source/CloudKit/CKDataObject.swift
apache-2.0
1
// // CKDataObject.swift // EVReflection // // Created by Edwin Vermeer on 9/2/15. // Copyright © 2017 evict. All rights reserved. // import CloudKit /** Conversion functions from and to CKRecord plus properties for easy access to system fields. */ open class CKDataObject: EVObject { /** The unique ID of the record. */ open var recordID: CKRecordID = CKRecordID(recordName: UUID().uuidString) /** The app-defined string that identifies the type of the record. */ open var recordType: String! /** The time when the record was first saved to the server. */ open var creationDate: Date = Date() /** The ID of the user who created the record. */ open var creatorUserRecordID: CKRecordID? /** The time when the record was last saved to the server. */ open var modificationDate: Date = Date() /** The ID of the user who last modified the record. */ open var lastModifiedUserRecordID: CKRecordID? /** A string containing the server change token for the record. */ open var recordChangeTag: String? /** Encoding the system fields so that we can create a new CKRecord based on this */ open var encodedSystemFields: Data? /** Implementation of the setValue forUndefinedKey so that we can catch exceptions for when we use an optional Type like Int? in our object. Instead of using Int? you should use NSNumber? This method is in EVObject and not in NSObject extension because you would get the error: method conflicts with previous declaration with the same Objective-C selector - parameter value: The value that you wanted to set - parameter key: The name of the property that you wanted to set */ open override func setValue(_ value: Any!, forUndefinedKey key: String) { if key == "encodedSystemFields" && value is Data { encodedSystemFields = value as? Data } else { super.setValue(value, forUndefinedKey: key) } } // ------------------------------------------------------------------------ // MARK: - Converting a CKRecord from and to an object // ------------------------------------------------------------------------ /** Convert a CKrecord to an object - parameter record: The CKRecord that will be converted to an object :return: The object that is created from the record */ public convenience init(_ record: CKRecord) { let dict = record.toDictionary() self.init(dictionary: dict) self.recordID = record.recordID self.recordType = record.recordType self.creationDate = record.creationDate ?? Date() self.creatorUserRecordID = record.creatorUserRecordID self.modificationDate = record.modificationDate ?? Date() self.lastModifiedUserRecordID = record.lastModifiedUserRecordID self.recordChangeTag = record.recordChangeTag let data = NSMutableData() let coder = NSKeyedArchiver(forWritingWith: data) record.encodeSystemFields(with: coder) coder.finishEncoding() self.encodedSystemFields = data as Data } /** Convert an object to a CKRecord - parameter theObject: The object that will be converted to a CKRecord :return: The CKRecord that is created from theObject */ open func toCKRecord() -> CKRecord { var record: CKRecord! if let fields = self.encodedSystemFields { let coder = NSKeyedUnarchiver(forReadingWith: fields) record = CKRecord(coder: coder) coder.finishDecoding() } if record == nil { record = CKRecord(recordType: EVReflection.swiftStringFromClass(self), recordID: self.recordID) } let (fromDict, _) = EVReflection.toDictionary(self) dictToCKRecord(record, dict: fromDict) return record } /** Put a dictionary recursively in a CKRecord - parameter record: the record - parameter dict: the dictionary - parameter root: used for expanding the property name */ internal func dictToCKRecord(_ record: CKRecord, dict: NSDictionary, root: String = "") { for (key, value) in dict { if !(["recordID", "recordType", "creationDate", "creatorUserRecordID", "modificationDate", "lastModifiedUserRecordID", "recordChangeTag", "encodedSystemFields"]).contains(key as! String) { if value is NSNull { // record.setValue(nil, forKey: key) // Swift can not set a value on a nulable type. } else if let dict = value as? NSDictionary { dictToCKRecord(record, dict: dict, root: "\(root)\(key as! String)__") } else if key as! String != "recordID" { record.setValue(value, forKey: "\(root)\(key as! String)") } } } } }
c1eef9768ee69a4f01fe774aa9370951
33.585034
200
0.607002
false
false
false
false
Danappelxx/MuttonChop
refs/heads/master
Sources/MuttonChop/TemplateCollection.swift
mit
1
public enum TemplateCollectionError: Error { case noSuchTemplate(named: String) } public struct TemplateCollection { public var templates: [String: Template] public init(templates: [String: Template] = [:]) { self.templates = templates } public func get(template name: String) throws -> Template { guard let template = templates[name] else { throw TemplateCollectionError.noSuchTemplate(named: name) } return template } public func render(template name: String, with context: Context = .array([])) throws -> String { return try get(template: name).render(with: context, partials: self.templates) } } // MARK: IO import Foundation extension TemplateCollection { public init(directory: String, fileExtensions: [String] = ["mustache"]) throws { let files = try FileManager.default.contentsOfDirectory(atPath: directory) .map { NSString(string: $0) } var templates = [String: Template]() for file in files where fileExtensions.contains(file.pathExtension) { let path = NSString(string: directory).appendingPathComponent(String(file)) guard let handle = FileHandle(forReadingAtPath: path), let contents = String(data: handle.readDataToEndOfFile(), encoding: .utf8) else { continue } let template = try Template(contents) templates[file.deletingPathExtension] = template } self.templates = templates } }
306e1460c8f510aced6b147edda9420a
31.8125
100
0.635556
false
false
false
false
foxisintest/vaporTest
refs/heads/master
Sources/App/main.swift
mit
1
import Vapor import HTTP import FluentMongo //demo code /* let drop = Droplet() drop.get { req in return try drop.view.make("welcome", [ "message": drop.localization[req.lang, "welcome", "title"] ]) } drop.resource("posts", PostController()) drop.run() */ //参考 https://segmentfault.com/a/1190000008421393?utm_source=tuicool&utm_medium=referral final class UserMongoDB: Model { var exists: Bool = false var id: Node? var name: String init(name: String) { self.name = name } init(node: Node, in context: Context) throws { id = try node.extract("id") name = try node.extract("name") } func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": id, "name": name ]) } static func prepare(_ database: Database) throws { try database.create("users") { users in users.id() users.string("name") } } static func revert(_ database: Database) throws { try database.delete("users") } } let mongo = try MongoDriver(database: "fox-db", user: "fox", password: "fox", host: "ds023052.mlab.com", port: 23052) let db = Database(mongo) let drop = Droplet() drop.database = db drop.preparations.append(UserMongoDB.self) drop.post("login"){ req in guard let name = req.data["name"]?.string else{ throw Abort.badRequest } var abc = UserMongoDB(name: name) try abc.save() return abc } drop.get("login"){req in // var abc = UserMongoDB(name: "abcdefg") // try abc.save() // return try JSON(["memo":"mongoDB result id:\(abc.id!), name:\(abc.name)]) return try JSON(["memo":"另可用postman测试post方法, Headers空,Body参数为name=xx!!!!!!!!!!!!!!"]) } drop.get("index"){ req in return try drop.view.make("welcome", ["message": "hello vapor1"]) } drop.get("index2"){ req in return try drop.view.make("welcome", ["message": "hello vapor index2"]) } drop.get("crud"){ req in return try drop.view.make("crud", ["message": "hello vapor index2"]) } drop.run()
897ecd464c76b51602bb2e31790e8a0e
22.5
117
0.602364
false
false
false
false
emiscience/SwiftPrefs
refs/heads/master
SwiftPrefs/AppDelegate.swift
mit
1
import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { lazy var preferencesWindowController: PreferencesWindowController = { let wcSB = NSStoryboard(name: "Preferences", bundle: Bundle.main) // or whichever bundle return wcSB.instantiateInitialController() as! PreferencesWindowController }() // lazy var niblessPreferencesWindowController: PreferencesWindowController = { // let npWB = PreferencesWindowController() // // // // let wcSB = NSStoryboard(name: "Preferences", bundle: NSBundle.mainBundle()) // // or whichever bundle // return wcSB.instantiateInitialController() as! PreferencesWindowController // }() @IBAction func showPreferencesWindow(_ sender: NSObject?){ self.preferencesWindowController.showWindow(self) } }
0f17b99dc6a2e3ae31d05204e116b37c
29.172414
85
0.690286
false
false
false
false
yeziahehe/Gank
refs/heads/master
Pods/Kingfisher/Sources/Networking/ImageDownloader.swift
gpl-3.0
1
// // ImageDownloader.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif /// Represents a success result of an image downloading progress. public struct ImageLoadingResult { /// The downloaded image. public let image: Image /// Original URL of the image request. public let url: URL? /// The raw data received from downloader. public let originalData: Data } /// Represents a task of an image downloading process. public struct DownloadTask { /// The `SessionDataTask` object bounded to this download task. Multiple `DownloadTask`s could refer /// to a same `sessionTask`. This is an optimization in Kingfisher to prevent multiple downloading task /// for the same URL resource at the same time. /// /// When you `cancel` a `DownloadTask`, this `SessionDataTask` and its cancel token will be pass through. /// You can use them to identify the cancelled task. public let sessionTask: SessionDataTask /// The cancel token which is used to cancel the task. This is only for identify the task when it is cancelled. /// To cancel a `DownloadTask`, use `cancel` instead. public let cancelToken: SessionDataTask.CancelToken /// Cancel this task if it is running. It will do nothing if this task is not running. /// /// - Note: /// In Kingfisher, there is an optimization to prevent starting another download task if the target URL is being /// downloading. However, even when internally no new session task created, a `DownloadTask` will be still created /// and returned when you call related methods, but it will share the session downloading task with a previous task. /// In this case, if multiple `DownloadTask`s share a single session download task, cancelling a `DownloadTask` /// does not affect other `DownloadTask`s. /// /// If you need to cancel all `DownloadTask`s of a url, use `ImageDownloader.cancel(url:)`. If you need to cancel /// all downloading tasks of an `ImageDownloader`, use `ImageDownloader.cancelAll()`. public func cancel() { sessionTask.cancel(token: cancelToken) } } /// Represents a downloading manager for requesting the image with a URL from server. open class ImageDownloader { // MARK: Singleton /// The default downloader. public static let `default` = ImageDownloader(name: "default") // MARK: Public Properties /// The duration before the downloading is timeout. Default is 15 seconds. open var downloadTimeout: TimeInterval = 15.0 /// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this /// set will be ignored. You can use this set to specify the self-signed site. It only will be used if you don't /// specify the `authenticationChallengeResponder`. /// /// If `authenticationChallengeResponder` is set, this property will be ignored and the implementation of /// `authenticationChallengeResponder` will be used instead. open var trustedHosts: Set<String>? /// Use this to set supply a configuration for the downloader. By default, /// NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used. /// /// You could change the configuration before a downloading task starts. /// A configuration without persistent storage for caches is requested for downloader working correctly. open var sessionConfiguration = URLSessionConfiguration.ephemeral { didSet { session.invalidateAndCancel() session = URLSession(configuration: sessionConfiguration, delegate: sessionDelegate, delegateQueue: nil) } } /// Whether the download requests should use pipeline or not. Default is false. open var requestsUsePipelining = false /// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more. open weak var delegate: ImageDownloaderDelegate? /// A responder for authentication challenge. /// Downloader will forward the received authentication challenge for the downloading session to this responder. open weak var authenticationChallengeResponder: AuthenticationChallengeResponsable? private let name: String private let sessionDelegate: SessionDelegate private var session: URLSession // MARK: Initializers /// Creates a downloader with name. /// /// - Parameter name: The name for the downloader. It should not be empty. public init(name: String) { if name.isEmpty { fatalError("[Kingfisher] You should specify a name for the downloader. " + "A downloader with empty name is not permitted.") } self.name = name sessionDelegate = SessionDelegate() session = URLSession( configuration: sessionConfiguration, delegate: sessionDelegate, delegateQueue: nil) authenticationChallengeResponder = self setupSessionHandler() } deinit { session.invalidateAndCancel() } private func setupSessionHandler() { sessionDelegate.onReceiveSessionChallenge.delegate(on: self) { (self, invoke) in self.authenticationChallengeResponder?.downloader(self, didReceive: invoke.1, completionHandler: invoke.2) } sessionDelegate.onReceiveSessionTaskChallenge.delegate(on: self) { (self, invoke) in self.authenticationChallengeResponder?.downloader( self, task: invoke.1, didReceive: invoke.2, completionHandler: invoke.3) } sessionDelegate.onValidStatusCode.delegate(on: self) { (self, code) in return (self.delegate ?? self).isValidStatusCode(code, for: self) } sessionDelegate.onDownloadingFinished.delegate(on: self) { (self, value) in let (url, result) = value do { let value = try result.get() self.delegate?.imageDownloader(self, didFinishDownloadingImageForURL: url, with: value, error: nil) } catch { self.delegate?.imageDownloader(self, didFinishDownloadingImageForURL: url, with: nil, error: error) } } sessionDelegate.onDidDownloadData.delegate(on: self) { (self, task) in guard let url = task.task.originalRequest?.url else { return task.mutableData } return (self.delegate ?? self).imageDownloader(self, didDownload: task.mutableData, for: url) } } @discardableResult func downloadImage( with url: URL, options: KingfisherParsedOptionsInfo, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<ImageLoadingResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { // Creates default request. var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: downloadTimeout) request.httpShouldUsePipelining = requestsUsePipelining if let requestModifier = options.requestModifier { // Modifies request before sending. guard let r = requestModifier.modified(for: request) else { options.callbackQueue.execute { completionHandler?(.failure(KingfisherError.requestError(reason: .emptyRequest))) } return nil } request = r } // There is a possibility that request modifier changed the url to `nil` or empty. // In this case, throw an error. guard let url = request.url, !url.absoluteString.isEmpty else { options.callbackQueue.execute { completionHandler?(.failure(KingfisherError.requestError(reason: .invalidURL(request: request)))) } return nil } // Wraps `progressBlock` and `completionHandler` to `onProgress` and `onCompleted` respectively. let onProgress = progressBlock.map { block -> Delegate<(Int64, Int64), Void> in let delegate = Delegate<(Int64, Int64), Void>() delegate.delegate(on: self) { (_, progress) in let (downloaded, total) = progress block(downloaded, total) } return delegate } let onCompleted = completionHandler.map { block -> Delegate<Result<ImageLoadingResult, KingfisherError>, Void> in let delegate = Delegate<Result<ImageLoadingResult, KingfisherError>, Void>() delegate.delegate(on: self) { (_, result) in block(result) } return delegate } // SessionDataTask.TaskCallback is a wrapper for `onProgress`, `onCompleted` and `options` (for processor info) let callback = SessionDataTask.TaskCallback( onProgress: onProgress, onCompleted: onCompleted, options: options) // Ready to start download. Add it to session task manager (`sessionHandler`) let downloadTask: DownloadTask if let existingTask = sessionDelegate.task(for: url) { downloadTask = sessionDelegate.append(existingTask, url: url, callback: callback) } else { let sessionDataTask = session.dataTask(with: request) sessionDataTask.priority = options.downloadPriority downloadTask = sessionDelegate.add(sessionDataTask, url: url, callback: callback) } let sessionTask = downloadTask.sessionTask // Start the session task if not started yet. if !sessionTask.started { sessionTask.onTaskDone.delegate(on: self) { (self, done) in // Underlying downloading finishes. // result: Result<(Data, URLResponse?)>, callbacks: [TaskCallback] let (result, callbacks) = done // Before processing the downloaded data. do { let value = try result.get() self.delegate?.imageDownloader( self, didFinishDownloadingImageForURL: url, with: value.1, error: nil) } catch { self.delegate?.imageDownloader( self, didFinishDownloadingImageForURL: url, with: nil, error: error) } switch result { // Download finished. Now process the data to an image. case .success(let (data, response)): let processor = ImageDataProcessor( data: data, callbacks: callbacks, processingQueue: options.processingQueue) processor.onImageProcessed.delegate(on: self) { (self, result) in // `onImageProcessed` will be called for `callbacks.count` times, with each // `SessionDataTask.TaskCallback` as the input parameter. // result: Result<Image>, callback: SessionDataTask.TaskCallback let (result, callback) = result if let image = try? result.get() { self.delegate?.imageDownloader(self, didDownload: image, for: url, with: response) } let imageResult = result.map { ImageLoadingResult(image: $0, url: url, originalData: data) } let queue = callback.options.callbackQueue queue.execute { callback.onCompleted?.call(imageResult) } } processor.process() case .failure(let error): callbacks.forEach { callback in let queue = callback.options.callbackQueue queue.execute { callback.onCompleted?.call(.failure(error)) } } } } delegate?.imageDownloader(self, willDownloadImageForURL: url, with: request) sessionTask.resume() } return downloadTask } // MARK: Dowloading Task /// Downloads an image with a URL and option. /// /// - Parameters: /// - url: Target URL. /// - options: The options could control download behavior. See `KingfisherOptionsInfo`. /// - progressBlock: Called when the download progress updated. This block will be always be called in main queue. /// - completionHandler: Called when the download progress finishes. This block will be called in the queue /// defined in `.callbackQueue` in `options` parameter. /// - Returns: A downloading task. You could call `cancel` on it to stop the download task. @discardableResult open func downloadImage( with url: URL, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<ImageLoadingResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { return downloadImage( with: url, options: KingfisherParsedOptionsInfo(options), progressBlock: progressBlock, completionHandler: completionHandler) } } // MARK: Cancelling Task extension ImageDownloader { /// Cancel all downloading tasks for this `ImageDownloader`. It will trigger the completion handlers /// for all not-yet-finished downloading tasks. /// /// If you need to only cancel a certain task, call `cancel()` on the `DownloadTask` /// returned by the downloading methods. If you need to cancel all `DownloadTask`s of a certain url, /// use `ImageDownloader.cancel(url:)`. public func cancelAll() { sessionDelegate.cancelAll() } /// Cancel all downloading tasks for a given URL. It will trigger the completion handlers for /// all not-yet-finished downloading tasks for the URL. /// /// - Parameter url: The URL which you want to cancel downloading. public func cancel(url: URL) { sessionDelegate.cancel(url: url) } } // Use the default implementation from extension of `AuthenticationChallengeResponsable`. extension ImageDownloader: AuthenticationChallengeResponsable {} // Use the default implementation from extension of `ImageDownloaderDelegate`. extension ImageDownloader: ImageDownloaderDelegate {}
84e82507995d1b044607741c9b36640f
43.754986
120
0.646063
false
false
false
false
007HelloWorld/DouYuZhiBo
refs/heads/develop
Apps/Forum17/2017/Pods/Alamofire/Source/Alamofire.swift
apache-2.0
126
// // Alamofire.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // 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 /// Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct /// URL requests. public protocol URLConvertible { /// Returns a URL that conforms to RFC 2396 or throws an `Error`. /// /// - throws: An `Error` if the type cannot be converted to a `URL`. /// /// - returns: A URL or throws an `Error`. func asURL() throws -> URL } extension String: URLConvertible { /// Returns a URL if `self` represents a valid URL string that conforms to RFC 2396 or throws an `AFError`. /// /// - throws: An `AFError.invalidURL` if `self` is not a valid URL string. /// /// - returns: A URL or throws an `AFError`. public func asURL() throws -> URL { guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) } return url } } extension URL: URLConvertible { /// Returns self. public func asURL() throws -> URL { return self } } extension URLComponents: URLConvertible { /// Returns a URL if `url` is not nil, otherwise throws an `Error`. /// /// - throws: An `AFError.invalidURL` if `url` is `nil`. /// /// - returns: A URL or throws an `AFError`. public func asURL() throws -> URL { guard let url = url else { throw AFError.invalidURL(url: self) } return url } } // MARK: - /// Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. public protocol URLRequestConvertible { /// Returns a URL request or throws if an `Error` was encountered. /// /// - throws: An `Error` if the underlying `URLRequest` is `nil`. /// /// - returns: A URL request. func asURLRequest() throws -> URLRequest } extension URLRequestConvertible { /// The URL request. public var urlRequest: URLRequest? { return try? asURLRequest() } } extension URLRequest: URLRequestConvertible { /// Returns a URL request or throws if an `Error` was encountered. public func asURLRequest() throws -> URLRequest { return self } } // MARK: - extension URLRequest { /// Creates an instance with the specified `method`, `urlString` and `headers`. /// /// - parameter url: The URL. /// - parameter method: The HTTP method. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The new `URLRequest` instance. public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { let url = try url.asURL() self.init(url: url) httpMethod = method.rawValue if let headers = headers { for (headerField, headerValue) in headers { setValue(headerValue, forHTTPHeaderField: headerField) } } } func adapt(using adapter: RequestAdapter?) throws -> URLRequest { guard let adapter = adapter else { return self } return try adapter.adapt(self) } } // MARK: - Data Request /// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, /// `method`, `parameters`, `encoding` and `headers`. /// /// - parameter url: The URL. /// - parameter method: The HTTP method. `.get` by default. /// - parameter parameters: The parameters. `nil` by default. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `DataRequest`. @discardableResult public func request( _ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil) -> DataRequest { return SessionManager.default.request( url, method: method, parameters: parameters, encoding: encoding, headers: headers ) } /// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the /// specified `urlRequest`. /// /// - parameter urlRequest: The URL request /// /// - returns: The created `DataRequest`. @discardableResult public func request(_ urlRequest: URLRequestConvertible) -> DataRequest { return SessionManager.default.request(urlRequest) } // MARK: - Download Request // MARK: URL Request /// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, /// `method`, `parameters`, `encoding`, `headers` and save them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// - parameter url: The URL. /// - parameter method: The HTTP method. `.get` by default. /// - parameter parameters: The parameters. `nil` by default. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult public func download( _ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { return SessionManager.default.download( url, method: method, parameters: parameters, encoding: encoding, headers: headers, to: destination ) } /// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of a URL based on the /// specified `urlRequest` and save them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// - parameter urlRequest: The URL request. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult public func download( _ urlRequest: URLRequestConvertible, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { return SessionManager.default.download(urlRequest, to: destination) } // MARK: Resume Data /// Creates a `DownloadRequest` using the default `SessionManager` from the `resumeData` produced from a /// previous request cancellation to retrieve the contents of the original request and save them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken /// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the /// data is written incorrectly and will always fail to resume the download. For more information about the bug and /// possible workarounds, please refer to the following Stack Overflow post: /// /// - http://stackoverflow.com/a/39347461/1342462 /// /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for additional /// information. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult public func download( resumingWith resumeData: Data, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { return SessionManager.default.download(resumingWith: resumeData, to: destination) } // MARK: - Upload Request // MARK: File /// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` /// for uploading the `file`. /// /// - parameter file: The file to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult public func upload( _ fileURL: URL, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { return SessionManager.default.upload(fileURL, to: url, method: method, headers: headers) } /// Creates a `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for /// uploading the `file`. /// /// - parameter file: The file to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created `UploadRequest`. @discardableResult public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { return SessionManager.default.upload(fileURL, with: urlRequest) } // MARK: Data /// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` /// for uploading the `data`. /// /// - parameter data: The data to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult public func upload( _ data: Data, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { return SessionManager.default.upload(data, to: url, method: method, headers: headers) } /// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for /// uploading the `data`. /// /// - parameter data: The data to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created `UploadRequest`. @discardableResult public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { return SessionManager.default.upload(data, with: urlRequest) } // MARK: InputStream /// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` /// for uploading the `stream`. /// /// - parameter stream: The stream to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult public func upload( _ stream: InputStream, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { return SessionManager.default.upload(stream, to: url, method: method, headers: headers) } /// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for /// uploading the `stream`. /// /// - parameter urlRequest: The URL request. /// - parameter stream: The stream to upload. /// /// - returns: The created `UploadRequest`. @discardableResult public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { return SessionManager.default.upload(stream, with: urlRequest) } // MARK: MultipartFormData /// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls /// `encodingCompletion` with new `UploadRequest` using the `url`, `method` and `headers`. /// /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be /// used for larger payloads such as video content. /// /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding /// technique was used. /// /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. /// `multipartFormDataEncodingMemoryThreshold` by default. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. public func upload( multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil, encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) { return SessionManager.default.upload( multipartFormData: multipartFormData, usingThreshold: encodingMemoryThreshold, to: url, method: method, headers: headers, encodingCompletion: encodingCompletion ) } /// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and /// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`. /// /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be /// used for larger payloads such as video content. /// /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding /// technique was used. /// /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. /// `multipartFormDataEncodingMemoryThreshold` by default. /// - parameter urlRequest: The URL request. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. public func upload( multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, with urlRequest: URLRequestConvertible, encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) { return SessionManager.default.upload( multipartFormData: multipartFormData, usingThreshold: encodingMemoryThreshold, with: urlRequest, encodingCompletion: encodingCompletion ) } #if !os(watchOS) // MARK: - Stream Request // MARK: Hostname and Port /// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `hostname` /// and `port`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter hostName: The hostname of the server to connect to. /// - parameter port: The port of the server to connect to. /// /// - returns: The created `StreamRequest`. @discardableResult @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) public func stream(withHostName hostName: String, port: Int) -> StreamRequest { return SessionManager.default.stream(withHostName: hostName, port: port) } // MARK: NetService /// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `netService`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter netService: The net service used to identify the endpoint. /// /// - returns: The created `StreamRequest`. @discardableResult @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) public func stream(with netService: NetService) -> StreamRequest { return SessionManager.default.stream(with: netService) } #endif
31dd3ab06effd8e94fa5fb18f120ee63
39.617204
118
0.7062
false
false
false
false
IngmarStein/swift
refs/heads/master
validation-test/compiler_crashers_fixed/01259-swift-modulefile-gettype.swift
apache-2.0
11
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse fu> Bool { } func f<g>() -> (g, g -> g) -> g { d j d.i = { } { g) { h } } protocol f { } class d: f{ class func i {} protocol A { } func a struct d<f : e, g: e where g.h == f.h> { } protocol e { } protocol b { } struct c { func e() { } } protocol a : a { } protocol a { } class b<h : c, i : c where h.g == i> : a { } class b<h, i> { } protocol c { } f: A where D.C == E> {s func c() { } } func c<d { enum c { } } protocol A { } struct X<Y> : A { func b(b: X.Type) { } } func a<T>() { enum b { } } func c<d { enum c { } } struct A<T> { } func a(b: Int = 0) { } let c = a
da1b082382900b0f5bcd7ad7bf58f3c3
13.176471
78
0.584025
false
false
false
false
suifengqjn/swiftDemo
refs/heads/master
基本语法/11方法/方法/方法/ViewController.swift
apache-2.0
1
// // ViewController.swift // 方法 // // Created by qianjn on 16/7/24. // Copyright © 2016年 SF. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() ///类和结构体也可以定义方法 ,与oc的不同之处 let ct: Counter = Counter() ct.increment(by: 3) print(ct) ct.reset() print(ct) } ///实例方法 /// Counter 类定义了三个实例方法: // increment每次给计数器增加 1; // increment(by: Int)按照特定的整型数量来增加计数器; // reset会把计数器重置为零。 class Counter { var count = 0 func increment() { count += 1 } func increment(by amount: Int) { count += amount } func reset() { count = 0 } } ///self属性, 能不写就不写 //可以使用 self属性来区分形式参数名和属性名。,还有闭包中会用到self struct Point { var x = 0.0, y = 0.0 func isToTheRightOf(x: Double) -> Bool { return self.x > x } } ///在实例方法中修改值类型 //结构体和枚举是值类型。默认情况下,值类型属性不能被自身的实例方法修改。 //你可以选择在 func关键字前放一个 mutating关键字来使用这个行为: struct Pointcu { var x = 0.0, y = 0.0 mutating func moveByX(deltaX: Double, y deltaY: Double) { x += deltaX y += deltaY } } ///在异变方法里指定自身 struct Pointc22 { var x = 0.0, y = 0.0 mutating func moveBy(x deltaX: Double, y deltaY: Double) { self = Pointc22(x: x + deltaX, y: y + deltaY) } } ///类型方法 看文档老半天,p也没看懂 }
65668fc0c18cd4ed0a44883142134871
18.4875
66
0.508018
false
false
false
false
knomi/Allsorts
refs/heads/master
Allsorts/Orderable.swift
mit
1
// // Orderable.swift // Allsorts // // Copyright (c) 2015 Pyry Jahkola. All rights reserved. // /// Three-way comparison operator of two `Orderable`\ s. infix operator <=> : ComparisonPrecedence /// A type that can be efficiently three-way compared with another value of its /// type using the `<=>` operator. /// /// Any `Comparable` can be made `Orderable` by simply declaring protocol /// conformance in an extension, but some types (like `Swift.String`) may have a /// more efficient implementation for `<=>`. /// /// Axioms: /// ``` /// (i) ∀x: x <=> x == Ordering.equal (reflexivity) /// (ii) ∀x,y: if (x <=> y).rawValue == i /// then (y <=> x).rawValue == -i (antisymmetry) /// (iii) ∀x,y,z: if (x <=> y).rawValue == i /// and (y <=> z).rawValue == i /// then (x <=> z).rawValue == i (transitivity) /// ``` public protocol Orderable { static func <=> (left: Self, right: Self) -> Ordering } /// Default implementation for making `Comparable` types `Orderable`. public func <=> <T : Comparable>(left: T, right: T) -> Ordering { return Ordering.compare(left, right) } /// Default implementation for making `Orderable` types `Equatable`. Override /// if needed. public func == <T : Orderable & Comparable>(left: T, right: T) -> Bool { switch left <=> right { case .equal: return true default: return false } } /// Default implementation for making `Orderable` types `Comparable`. Override /// if needed. public func < <T : Orderable & Comparable>(left: T, right: T) -> Bool { switch left <=> right { case .less: return true default: return false } }
d2d08cc8df81d45e82ed81b55962af0a
30.673077
80
0.617486
false
false
false
false
SmallPlanetSwift/Saturn
refs/heads/master
Source/TypeExtensions/UIView+String.swift
mit
1
// // UIView+String.swift // Saturn // // Created by Quinn McHenry on 11/16/15. // Copyright © 2015 Small Planet. All rights reserved. // extension UIViewContentMode: StringLiteralConvertible { public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType public typealias UnicodeScalarLiteralType = Character public init(stringLiteral value: String) { switch value.lowercaseString { case "scaletofill": self = ScaleToFill case "scaleaspectfit": self = ScaleAspectFit case "scaleaspectfill": self = ScaleAspectFill case "redraw": self = Redraw case "center": self = Center case "top": self = Top case "bottom": self = Bottom case "left": self = Left case "right": self = Right case "topleft": self = TopLeft case "topright": self = TopRight case "bottomleft": self = BottomLeft case "bottomright": self = BottomRight default: self = Center } } public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { self.init(stringLiteral: value) } public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { self.init(stringLiteral: "\(value)") } }
e7f9c8101bb8e99864749369fe0190a5
25.925926
91
0.577717
false
false
false
false
marty-suzuki/HoverConversion
refs/heads/master
HoverConversionSample/HoverConversionSample/Request/UsersLookUpRequest.swift
mit
1
// // UsersLookUpRequest.swift // HoverConversionSample // // Created by 鈴木大貴 on 2016/09/08. // Copyright © 2016年 szk-atmosphere. All rights reserved. // import Foundation import TwitterKit struct UsersLookUpRequest: TWTRGetRequestable { typealias ResponseType = [TWTRUser] typealias ParseResultType = [[String : NSObject]] let path: String = "/1.1/users/lookup.json" let screenNames: [String] var parameters: [AnyHashable: Any]? { let screenNameValue: String = screenNames.joined(separator: ",") let parameters: [AnyHashable: Any] = [ "screen_name" : screenNameValue, "include_entities" : "true" ] return parameters } static func decode(_ data: Data) -> TWTRResult<ResponseType> { switch UsersLookUpRequest.parseData(data) { case .success(let parsedData): return .success(parsedData.flatMap { TWTRUser(jsonDictionary: $0) }) case .failure(let error): return .failure(error) } } }
4d9876a8bd6cba91f6c94f500c3dc3d3
27.405405
80
0.630828
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
Wikipedia/Code/WikidataFetcher+Places.swift
mit
1
import Foundation import WMF import MapKit extension WikidataFetcher { private func wikidata(forArticleURL articleURL: URL, failure: @escaping (Error) -> Void, success: @escaping ([String: Any]) -> Void) { guard let title = articleURL.wmf_title, let language = articleURL.wmf_languageCode else { failure(RequestError.invalidParameters) return } let queryParameters = ["action": "wbgetentities", "title": title, "sites": "\(language)wiki", "format": "json"] let components = configuration.wikidataAPIURLComponents(with: queryParameters) session.getJSONDictionary(from: components.url, ignoreCache: false) { (jsonObject, response, error) in guard let jsonObject = jsonObject else { failure(RequestError.unexpectedResponse) return } success(jsonObject) } } func wikidataBoundingRegion(forArticleURL articleURL: URL, failure: @escaping (Error) -> Void, success: @escaping (MKCoordinateRegion) -> Void) { wikidata(forArticleURL: articleURL, failure: failure) { (jsonObject) in guard let entities = jsonObject["entities"] as? [String: Any], let entity = entities.values.first as? [String: Any], let claims = entity["claims"] as? [String: Any] else { failure(RequestError.unexpectedResponse) return } let keys = ["P1332", "P1333", "P1334", "P1335"] // bounding coordinates let coordinates = keys.compactMap({ (key) -> CLLocationCoordinate2D? in guard let values = claims[key] as? [Any] else { return nil } guard let point = values.first as? [String: Any] else { return nil } guard let mainsnak = point["mainsnak"] as? [String: Any] else { return nil } guard let datavalue = mainsnak["datavalue"] as? [String: Any] else { return nil } guard let value = datavalue["value"] as? [String: Any] else { return nil } guard let latitude = value["latitude"] as? CLLocationDegrees, let longitude = value["longitude"] as? CLLocationDegrees else { return nil } return CLLocationCoordinate2D(latitude: latitude, longitude: longitude) }) guard coordinates.count > 3 else { failure(RequestError.unexpectedResponse) return } success(coordinates.wmf_boundingRegion(with: 1)) } } }
a2563abc854e3d261e01c8f10c8b1989
41.954545
149
0.546737
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS Tests/ConversationList/ConversationListCell/ConversationStatusLineTests+Muting.swift
gpl-3.0
1
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import XCTest @testable import Wire class ConversationStatusLineTests_Muting: CoreDataSnapshotTestCase { override func setUp() { selfUserInTeam = true super.setUp() } override var needsCaches: Bool { return true } } // MARK: - Only replies extension ConversationStatusLineTests_Muting { func testStatusShowSpecialSummaryForSingleEphemeralReplyWhenOnlyReplies_oneToOne() { // GIVEN let sut = self.otherUserConversation! sut.setMessageDestructionTimeoutValue(.custom(100), for: .selfUser) let selfMessage = appendSelfMessage(to: sut) appendReply(to: sut, selfMessage: selfMessage) sut.mutedMessageTypes = .regular markAllMessagesAsUnread(in: sut) // WHEN let status = sut.status.description(for: sut) // THEN XCTAssertEqual(status.string, "Replied to your message") } /// TODO: move this test to SE func testStatusShowSpecialSummaryForSingleEphemeralReplyWhenOnlyReplies_group() { // GIVEN let sut = self.createGroupConversation() sut.addParticipantAndSystemMessageIfMissing(createUser(name: "other"), date: nil) sut.setMessageDestructionTimeoutValue(.custom(100), for: .selfUser) let selfMessage = appendSelfMessage(to: sut) appendReply(to: sut, selfMessage: selfMessage) markAllMessagesAsUnread(in: sut) sut.mutedMessageTypes = .regular // WHEN let status = sut.status.description(for: sut) // THEN XCTAssertEqual(status.string, "Someone replied to your message") } func testStatusShowSummaryForMultipleEphemeralRepliesWhenOnlyReplies() { // GIVEN let sut = self.createGroupConversation() sut.setMessageDestructionTimeoutValue(.custom(100), for: .selfUser) let selfMessage = appendSelfMessage(to: sut) for _ in 1...5 { appendReply(to: sut, selfMessage: selfMessage) } markAllMessagesAsUnread(in: sut) sut.mutedMessageTypes = .regular // WHEN let status = sut.status.description(for: sut) // THEN XCTAssertEqual(status.string, "Someone replied to your message") } func testStatusShowSummaryForMultipleMessagesAndReplyWhenNoNotifications() { // GIVEN let sut = self.otherUserConversation! sut.mutedMessageTypes = [.all] for _ in 1...5 { appendTextMessage(to: sut) } let selfMessage = appendSelfMessage(to: sut) appendReply(to: sut, selfMessage: selfMessage) markAllMessagesAsUnread(in: sut) // WHEN let status = sut.status.description(for: sut) // THEN XCTAssertEqual(status.string, "1 reply, 5 messages") } func testStatusShowSummaryForOneReplyWhenNoNotifications() { // GIVEN let sut = self.otherUserConversation! sut.mutedMessageTypes = [.all] let selfMessage = appendSelfMessage(to: sut) appendReply(to: sut, selfMessage: selfMessage) markAllMessagesAsUnread(in: sut) // WHEN let status = sut.status.description(for: sut) // THEN XCTAssertEqual(status.string, "1 reply") } func testStatusShowSummaryForMultipleRepliesAndMultipleMessagesWhenOnlyReplies() { // GIVEN let sut = self.otherUserConversation! for _ in 1...5 { appendTextMessage(to: sut) } let selfMessage = appendSelfMessage(to: sut) for _ in 1...5 { appendReply(to: sut, selfMessage: selfMessage) } markAllMessagesAsUnread(in: sut) sut.mutedMessageTypes = .regular // WHEN let status = sut.status.description(for: sut) // THEN XCTAssertEqual(status.string, "5 replies, 5 messages") } } // MARK: - mentions & replies extension ConversationStatusLineTests_Muting { func testStatusShowSummaryForMultipleMentionsAndRepliesAndMultipleMessagesWhenOnlyMentionsAndReplies() { // GIVEN let sut = self.otherUserConversation! for _ in 1...5 { appendTextMessage(to: sut) } let selfMessage = appendSelfMessage(to: sut) for _ in 1...5 { appendReply(to: sut, selfMessage: selfMessage) } for _ in 1...5 { appendMention(to: sut) } markAllMessagesAsUnread(in: sut) sut.mutedMessageTypes = .regular // WHEN let status = sut.status.description(for: sut) // THEN XCTAssertEqual(status.string, "5 mentions, 5 replies, 5 messages") } } // MARK: - Only mentions extension ConversationStatusLineTests_Muting { func testStatusShowSummaryForSingleMessageWhenOnlyMentions() { // GIVEN let sut = self.otherUserConversation! appendTextMessage(to: sut) markAllMessagesAsUnread(in: sut) sut.mutedMessageTypes = .regular // WHEN let status = sut.status.description(for: sut) // THEN XCTAssertEqual(status.string, "1 message") } func testStatusShowSpecialSummaryForSingleEphemeralMentionWhenOnlyMentions_oneToOne() { // GIVEN let sut = self.otherUserConversation! sut.setMessageDestructionTimeoutValue(.custom(100), for: .selfUser) appendMention(to: sut) markAllMessagesAsUnread(in: sut) sut.mutedMessageTypes = .regular // WHEN let status = sut.status.description(for: sut) // THEN XCTAssertEqual(status.string, "Mentioned you") } func testStatusShowSpecialSummaryForSingleEphemeralMentionWhenOnlyMentions_group() { // GIVEN let sut = self.createGroupConversation() sut.addParticipantAndSystemMessageIfMissing(createUser(name: "other"), date: nil) sut.setMessageDestructionTimeoutValue(.custom(100), for: .selfUser) appendMention(to: sut) markAllMessagesAsUnread(in: sut) sut.mutedMessageTypes = .regular // WHEN let status = sut.status.description(for: sut) // THEN XCTAssertEqual(status.string, "Someone mentioned you") } func testStatusShowSummaryForMultipleEphemeralMentionsWhenOnlyMentions() { // GIVEN let sut = self.createGroupConversation() sut.setMessageDestructionTimeoutValue(.custom(100), for: .selfUser) for _ in 1...5 { appendMention(to: sut) } markAllMessagesAsUnread(in: sut) sut.mutedMessageTypes = .regular // WHEN let status = sut.status.description(for: sut) // THEN XCTAssertEqual(status.string, "5 mentions") } func testStatusShowContentForSingleMentionWhenOnlyMentions() { // GIVEN let sut = self.otherUserConversation! appendTextMessage(to: sut) markAllMessagesAsUnread(in: sut) sut.mutedMessageTypes = .regular // WHEN let status = sut.status.description(for: sut) // THEN XCTAssertEqual(status.string, "1 message") } func testStatusShowSummaryForMultipleMentionsWhenOnlyMentions() { // GIVEN let sut = self.otherUserConversation! for _ in 1...5 { appendMention(to: sut) } markAllMessagesAsUnread(in: sut) sut.mutedMessageTypes = .regular // WHEN let status = sut.status.description(for: sut) // THEN XCTAssertEqual(status.string, "5 mentions") } func testStatusShowSummaryForMultipleMentionsAndMultipleMessagesWhenOnlyMentions() { // GIVEN let sut = self.otherUserConversation! for _ in 1...5 { appendTextMessage(to: sut) } for _ in 1...5 { appendMention(to: sut) } markAllMessagesAsUnread(in: sut) sut.mutedMessageTypes = .regular // WHEN let status = sut.status.description(for: sut) // THEN XCTAssertEqual(status.string, "5 mentions, 5 messages") } } // MARK: - No notifications extension ConversationStatusLineTests_Muting { func testStatusShowSummaryForSingleMentionWhenNoNotifications() { // GIVEN let sut = self.otherUserConversation! appendMention(to: sut) markAllMessagesAsUnread(in: sut) sut.mutedMessageTypes = .all // WHEN let status = sut.status.description(for: sut) // THEN XCTAssertEqual(status.string, "1 mention") } func testStatusShowSummaryForSingleEphemeralMentionWhenNoNotifications() { // GIVEN let sut = self.otherUserConversation! sut.setMessageDestructionTimeoutValue(.custom(100), for: .selfUser) appendMention(to: sut) markAllMessagesAsUnread(in: sut) sut.mutedMessageTypes = .all // WHEN let status = sut.status.description(for: sut) // THEN XCTAssertEqual(status.string, "1 mention") } func testStatusShowSummaryForMultipleMessagesWhenNoNotifications() { // GIVEN let sut = self.otherUserConversation! sut.mutedMessageTypes = [.all] for _ in 1...5 { appendTextMessage(to: sut) } markAllMessagesAsUnread(in: sut) // WHEN let status = sut.status.description(for: sut) // THEN XCTAssertEqual(status.string, "5 messages") } func testStatusShowSummaryForMultipleVariousMessagesWhenNoNotifications() { // GIVEN let sut = self.otherUserConversation! sut.mutedMessageTypes = [.all] for _ in 1...5 { appendTextMessage(to: sut) } for _ in 1...5 { appendImage(to: sut) } markAllMessagesAsUnread(in: sut) // WHEN let status = sut.status.description(for: sut) // THEN XCTAssertEqual(status.string, "10 messages") } func testStatusShowSummaryForMultipleMessagesAndMentionWhenNoNotifications() { // GIVEN let sut = self.otherUserConversation! sut.mutedMessageTypes = [.all] for _ in 1...5 { appendTextMessage(to: sut) } appendMention(to: sut) markAllMessagesAsUnread(in: sut) // WHEN let status = sut.status.description(for: sut) // THEN XCTAssertEqual(status.string, "1 mention, 5 messages") } }
8998fd5362fdb63c34b2088d77632304
28.492105
108
0.635406
false
true
false
false
jaropawlak/Signal-iOS
refs/heads/master
Signal/src/call/NonCallKitCallUIAdaptee.swift
gpl-3.0
1
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation /** * Manage call related UI in a pre-CallKit world. */ class NonCallKitCallUIAdaptee: CallUIAdaptee { let TAG = "[NonCallKitCallUIAdaptee]" let notificationsAdapter: CallNotificationsAdapter let callService: CallService // Starting/Stopping incoming call ringing is our apps responsibility for the non CallKit interface. let hasManualRinger = true required init(callService: CallService, notificationsAdapter: CallNotificationsAdapter) { self.callService = callService self.notificationsAdapter = notificationsAdapter } func startOutgoingCall(handle: String) -> SignalCall { AssertIsOnMainThread() let call = SignalCall.outgoingCall(localId: UUID(), remotePhoneNumber: handle) self.callService.handleOutgoingCall(call).then { Logger.debug("\(self.TAG) handleOutgoingCall succeeded") }.catch { error in Logger.error("\(self.TAG) handleOutgoingCall failed with error: \(error)") }.retainUntilComplete() return call } func reportIncomingCall(_ call: SignalCall, callerName: String) { AssertIsOnMainThread() Logger.debug("\(TAG) \(#function)") self.showCall(call) // present lock screen notification if UIApplication.shared.applicationState == .active { Logger.debug("\(TAG) skipping notification since app is already active.") } else { notificationsAdapter.presentIncomingCall(call, callerName: callerName) } } func reportMissedCall(_ call: SignalCall, callerName: String) { AssertIsOnMainThread() notificationsAdapter.presentMissedCall(call, callerName: callerName) } func answerCall(localId: UUID) { AssertIsOnMainThread() guard let call = self.callService.call else { owsFail("\(self.TAG) in \(#function) No current call.") return } guard call.localId == localId else { owsFail("\(self.TAG) in \(#function) localId does not match current call") return } self.answerCall(call) } func answerCall(_ call: SignalCall) { AssertIsOnMainThread() guard call.localId == self.callService.call?.localId else { owsFail("\(self.TAG) in \(#function) localId does not match current call") return } self.callService.handleAnswerCall(call) } func declineCall(localId: UUID) { AssertIsOnMainThread() guard let call = self.callService.call else { owsFail("\(self.TAG) in \(#function) No current call.") return } guard call.localId == localId else { owsFail("\(self.TAG) in \(#function) localId does not match current call") return } self.declineCall(call) } func declineCall(_ call: SignalCall) { AssertIsOnMainThread() guard call.localId == self.callService.call?.localId else { owsFail("\(self.TAG) in \(#function) localId does not match current call") return } self.callService.handleDeclineCall(call) } func recipientAcceptedCall(_ call: SignalCall) { AssertIsOnMainThread() // no-op } func localHangupCall(_ call: SignalCall) { AssertIsOnMainThread() // If both parties hang up at the same moment, // call might already be nil. guard self.callService.call == nil || call.localId == self.callService.call?.localId else { owsFail("\(self.TAG) in \(#function) localId does not match current call") return } self.callService.handleLocalHungupCall(call) } internal func remoteDidHangupCall(_ call: SignalCall) { AssertIsOnMainThread() Logger.debug("\(TAG) in \(#function) is no-op") } internal func remoteBusy(_ call: SignalCall) { AssertIsOnMainThread() Logger.debug("\(TAG) in \(#function) is no-op") } internal func failCall(_ call: SignalCall, error: CallError) { AssertIsOnMainThread() Logger.debug("\(TAG) in \(#function) is no-op") } func setIsMuted(call: SignalCall, isMuted: Bool) { AssertIsOnMainThread() guard call.localId == self.callService.call?.localId else { owsFail("\(self.TAG) in \(#function) localId does not match current call") return } self.callService.setIsMuted(call: call, isMuted: isMuted) } func setHasLocalVideo(call: SignalCall, hasLocalVideo: Bool) { AssertIsOnMainThread() guard call.localId == self.callService.call?.localId else { owsFail("\(self.TAG) in \(#function) localId does not match current call") return } self.callService.setHasLocalVideo(hasLocalVideo: hasLocalVideo) } }
202a8acc4f80fbaab0218ebe475eec40
28.315789
104
0.627369
false
false
false
false
getconnect/connect-swift
refs/heads/master
Pod/Classes/Select.swift
mit
1
// // Select.swift // ConnectSwift // // Created by Chad Edrupt on 2/12/2015. // Copyright © 2015 Connect. All rights reserved. // import Foundation public enum Aggregation { case Count case Sum(String) case Avg(String) case Min(String) case Max(String) } public typealias Select = [String: Aggregation] extension CollectionType where Generator.Element == (String, Aggregation) { var jsonObject: [String: AnyObject] { var map = [String: AnyObject]() for (alias, aggregation) in self { switch aggregation { case .Count: map[alias] = "count" case let .Sum(field): map[alias] = ["sum": field] case let .Avg(field): map[alias] = ["avg": field] case let .Min(field): map[alias] = ["min": field] case let .Max(field): map[alias] = ["max": field] } } return map } }
69f4fd0bf6c7c5b78e6a17a58a5ae06e
23.775
75
0.535822
false
false
false
false
rb-de0/Swift-Design-Pattern
refs/heads/master
Source/Flyweight.swift
mit
1
class DataManager{ private var dataList = [String: Int]() func addData(dataList: (key: String, data: Int)...){ dataList .filter{self.dataList[$0.key] == nil} .forEach{self.dataList.updateValue($0.data, forKey: $0.key)} } func dataForKey(key: String) -> Int?{ return dataList[key] } } let manager = DataManager() manager.addData( (key: "hoge1", data: 1), (key: "hoge2", data: 1), (key: "hoge3", data: 1), (key: "hoge1", data: 1), (key: "hoge2", data: 2) ) print(manager.dataList.count) // => 3
9c4164a1c0cfcdf6826d7ea2bcd75264
21.576923
72
0.553663
false
false
false
false
balitm/Sherpany
refs/heads/master
Sherpany/PhotosTableViewController.swift
mit
1
// // PhotosTableViewController.swift // Sherpany // // Created by Balázs Kilvády on 3/5/16. // Copyright © 2016 kil-dev. All rights reserved. // import UIKit import CoreData class PhotosTableViewController: BaseTableViewController { private let _listDataSource: ListDataSourceProtocol var albumId: Int16 = -1 required init?(coder aDecoder: NSCoder) { _listDataSource = ListDataSource(reuseId: "PhotoCell", entityName: PhotoEntity.entityName, sortKey: "photoId") super.init(coder: aDecoder) _listDataSource.delegate = self } override func viewDidLoad() { super.viewDidLoad() // Setup the data source object. _listDataSource.managedObjectContext = dataStack.mainContext _listDataSource.tableView = tableView tableView.dataSource = _listDataSource // Set the predicate for the Core Data fetch. _listDataSource.predicate = NSPredicate(format: "albumId == %d", self.albumId) // Download and set up the data of the photos in database. if model.isEmptyPhotos() { model.setupPhotos { print("photo info added to db.") } } else if tableView(tableView, numberOfRowsInSection: 0) == 0 { _listDataSource.refetch() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK: - ListDataSourceDelegate extension PhotosTableViewController: ListDataSourceDelegate { // Configure a UsersTableViewCell. func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { if let photo = _listDataSource.objectAtIndexPath(indexPath) as? PhotoEntity { guard let photoCell = cell as? PhotosTableViewCell else { assert(false) } photoCell.titleLabel.text = photo.title if photo.thumbnail == nil { // No image data yet, dowload it now. When the async download is // finished the fetchedResultController will update this cell. model.addPicture(photo, finished: { print("Thumbnail \(photo.thumbnailUrl) downloaded.") }) } else { // Set up the image from the database. photoCell.thumbnail.image = UIImage(data: photo.thumbnail!) photoCell.indicator.stopAnimating() } } } }
e4cf324796b11ea1b21b0514c29f37bb
32.972973
118
0.631663
false
false
false
false
arvedviehweger/swift
refs/heads/master
test/decl/ext/protocol.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift // ---------------------------------------------------------------------------- // Using protocol requirements from inside protocol extensions // ---------------------------------------------------------------------------- protocol P1 { @discardableResult func reqP1a() -> Bool } extension P1 { func extP1a() -> Bool { return !reqP1a() } var extP1b: Bool { return self.reqP1a() } var extP1c: Bool { return extP1b && self.extP1a() } } protocol P2 { associatedtype AssocP2 : P1 func reqP2a() -> AssocP2 } extension P2 { func extP2a() -> AssocP2? { return reqP2a() } func extP2b() { self.reqP2a().reqP1a() } func extP2c() -> Self.AssocP2 { return extP2a()! } } protocol P3 { associatedtype AssocP3 : P2 func reqP3a() -> AssocP3 } extension P3 { func extP3a() -> AssocP3.AssocP2 { return reqP3a().reqP2a() } } protocol P4 { associatedtype AssocP4 func reqP4a() -> AssocP4 } // ---------------------------------------------------------------------------- // Using generics from inside protocol extensions // ---------------------------------------------------------------------------- func acceptsP1<T : P1>(_ t: T) { } extension P1 { func extP1d() { acceptsP1(self) } } func acceptsP2<T : P2>(_ t: T) { } extension P2 { func extP2acceptsP1() { acceptsP1(reqP2a()) } func extP2acceptsP2() { acceptsP2(self) } } // Use of 'Self' as a return type within a protocol extension. protocol SelfP1 { associatedtype AssocType } protocol SelfP2 { } func acceptSelfP1<T, U : SelfP1>(_ t: T, _ u: U) -> T where U.AssocType == T { return t } extension SelfP1 { func tryAcceptSelfP1<Z : SelfP1>(_ z: Z)-> Self where Z.AssocType == Self { return acceptSelfP1(self, z) } } // ---------------------------------------------------------------------------- // Initializers in protocol extensions // ---------------------------------------------------------------------------- protocol InitP1 { init(string: String) } extension InitP1 { init(int: Int) { self.init(string: "integer") } } struct InitS1 : InitP1 { init(string: String) { } } class InitC1 : InitP1 { required init(string: String) { } } func testInitP1() { var is1 = InitS1(int: 5) is1 = InitS1(string: "blah") // check type _ = is1 var ic1 = InitC1(int: 5) ic1 = InitC1(string: "blah") // check type _ = ic1 } // ---------------------------------------------------------------------------- // Subscript in protocol extensions // ---------------------------------------------------------------------------- protocol SubscriptP1 { func readAt(_ i: Int) -> String func writeAt(_ i: Int, string: String) } extension SubscriptP1 { subscript(i: Int) -> String { get { return readAt(i) } set(newValue) { writeAt(i, string: newValue) } } } struct SubscriptS1 : SubscriptP1 { func readAt(_ i: Int) -> String { return "hello" } func writeAt(_ i: Int, string: String) { } } struct SubscriptC1 : SubscriptP1 { func readAt(_ i: Int) -> String { return "hello" } func writeAt(_ i: Int, string: String) { } } func testSubscriptP1(_ ss1: SubscriptS1, sc1: SubscriptC1, i: Int, s: String) { var ss1 = ss1 var sc1 = sc1 _ = ss1[i] ss1[i] = s _ = sc1[i] sc1[i] = s } // ---------------------------------------------------------------------------- // Using protocol extensions on types that conform to the protocols. // ---------------------------------------------------------------------------- struct S1 : P1 { @discardableResult func reqP1a() -> Bool { return true } func once() -> Bool { return extP1a() && extP1b } } func useS1(_ s1: S1) -> Bool { s1.reqP1a() return s1.extP1a() && s1.extP1b } extension S1 { func twice() -> Bool { return extP1a() && extP1b } } // ---------------------------------------------------------------------------- // Protocol extensions with additional requirements // ---------------------------------------------------------------------------- extension P4 where Self.AssocP4 : P1 { func extP4a() { // expected-note 2 {{found this candidate}} acceptsP1(reqP4a()) } } struct S4aHelper { } struct S4bHelper : P1 { func reqP1a() -> Bool { return true } } struct S4a : P4 { func reqP4a() -> S4aHelper { return S4aHelper() } } struct S4b : P4 { func reqP4a() -> S4bHelper { return S4bHelper() } } struct S4c : P4 { func reqP4a() -> Int { return 0 } } struct S4d : P4 { func reqP4a() -> Bool { return false } } extension P4 where Self.AssocP4 == Int { func extP4Int() { } } extension P4 where Self.AssocP4 == Bool { func extP4a() -> Bool { return reqP4a() } // expected-note 2 {{found this candidate}} } func testP4(_ s4a: S4a, s4b: S4b, s4c: S4c, s4d: S4d) { s4a.extP4a() // expected-error{{ambiguous reference to member 'extP4a()'}} s4b.extP4a() // ok s4c.extP4a() // expected-error{{ambiguous reference to member 'extP4a()'}} s4c.extP4Int() // okay var b1 = s4d.extP4a() // okay, "Bool" version b1 = true // checks type above s4d.extP4Int() // expected-error{{'Bool' is not convertible to 'Int'}} _ = b1 } // ---------------------------------------------------------------------------- // Protocol extensions with a superclass constraint on Self // ---------------------------------------------------------------------------- protocol ConformedProtocol { typealias ConcreteConformanceAlias = Self } class BaseWithAlias<T> : ConformedProtocol { typealias ConcreteAlias = T func baseMethod(_: T) {} } class DerivedWithAlias : BaseWithAlias<Int> {} protocol ExtendedProtocol { typealias AbstractConformanceAlias = Self } extension ExtendedProtocol where Self : DerivedWithAlias { func f0(x: T) {} // expected-error {{use of undeclared type 'T'}} func f1(x: ConcreteAlias) { let _: Int = x baseMethod(x) } func f2(x: ConcreteConformanceAlias) { let _: DerivedWithAlias = x } func f3(x: AbstractConformanceAlias) { let _: DerivedWithAlias = x } } // ---------------------------------------------------------------------------- // Using protocol extensions to satisfy requirements // ---------------------------------------------------------------------------- protocol P5 { func reqP5a() } // extension of P5 provides a witness for P6 extension P5 { func reqP6a() { reqP5a() } } protocol P6 { func reqP6a() } // S6a uses P5.reqP6a struct S6a : P5 { func reqP5a() { } } extension S6a : P6 { } // S6b uses P5.reqP6a struct S6b : P5, P6 { func reqP5a() { } } // S6c uses P5.reqP6a struct S6c : P6 { } extension S6c : P5 { func reqP5a() { } } // S6d does not use P5.reqP6a struct S6d : P6 { func reqP6a() { } } extension S6d : P5 { func reqP5a() { } } protocol P7 { associatedtype P7Assoc func getP7Assoc() -> P7Assoc } struct P7FromP8<T> { } protocol P8 { associatedtype P8Assoc func getP8Assoc() -> P8Assoc } // extension of P8 provides conformance to P7Assoc extension P8 { func getP7Assoc() -> P7FromP8<P8Assoc> { return P7FromP8() } } // Okay, P7 requirements satisfied by P8 struct P8a : P8, P7 { func getP8Assoc() -> Bool { return true } } func testP8a(_ p8a: P8a) { var p7 = p8a.getP7Assoc() p7 = P7FromP8<Bool>() // okay, check type of above _ = p7 } // Okay, P7 requirements explicitly specified struct P8b : P8, P7 { func getP7Assoc() -> Int { return 5 } func getP8Assoc() -> Bool { return true } } func testP8b(_ p8b: P8b) { var p7 = p8b.getP7Assoc() p7 = 17 // check type of above _ = p7 } protocol PConforms1 { } extension PConforms1 { func pc2() { } // expected-note{{candidate exactly matches}} } protocol PConforms2 : PConforms1, MakePC2Ambiguous { func pc2() // expected-note{{multiple matching functions named 'pc2()' with type '() -> ()'}} } protocol MakePC2Ambiguous { } extension MakePC2Ambiguous { func pc2() { } // expected-note{{candidate exactly matches}} } struct SConforms2a : PConforms2 { } // expected-error{{type 'SConforms2a' does not conform to protocol 'PConforms2'}} struct SConforms2b : PConforms2 { func pc2() { } } // Satisfying requirements via protocol extensions for fun and profit protocol _MySeq { } protocol MySeq : _MySeq { associatedtype Generator : IteratorProtocol func myGenerate() -> Generator } protocol _MyCollection : _MySeq { associatedtype Index : Strideable var myStartIndex : Index { get } var myEndIndex : Index { get } associatedtype _Element subscript (i: Index) -> _Element { get } } protocol MyCollection : _MyCollection { } struct MyIndexedIterator<C : _MyCollection> : IteratorProtocol { var container: C var index: C.Index mutating func next() -> C._Element? { if index == container.myEndIndex { return nil } let result = container[index] index = index.advanced(by: 1) return result } } struct OtherIndexedIterator<C : _MyCollection> : IteratorProtocol { var container: C var index: C.Index mutating func next() -> C._Element? { if index == container.myEndIndex { return nil } let result = container[index] index = index.advanced(by: 1) return result } } extension _MyCollection { func myGenerate() -> MyIndexedIterator<Self> { return MyIndexedIterator(container: self, index: self.myEndIndex) } } struct SomeCollection1 : MyCollection { var myStartIndex: Int { return 0 } var myEndIndex: Int { return 10 } subscript (i: Int) -> String { return "blah" } } struct SomeCollection2 : MyCollection { var myStartIndex: Int { return 0 } var myEndIndex: Int { return 10 } subscript (i: Int) -> String { return "blah" } func myGenerate() -> OtherIndexedIterator<SomeCollection2> { return OtherIndexedIterator(container: self, index: self.myEndIndex) } } func testSomeCollections(_ sc1: SomeCollection1, sc2: SomeCollection2) { var mig = sc1.myGenerate() mig = MyIndexedIterator(container: sc1, index: sc1.myStartIndex) _ = mig var ig = sc2.myGenerate() ig = MyIndexedIterator(container: sc2, index: sc2.myStartIndex) // expected-error {{cannot assign value of type 'MyIndexedIterator<SomeCollection2>' to type 'OtherIndexedIterator<SomeCollection2>'}} _ = ig } public protocol PConforms3 {} extension PConforms3 { public var z: Int { return 0 } } public protocol PConforms4 : PConforms3 { var z: Int { get } } struct PConforms4Impl : PConforms4 {} let pc4z = PConforms4Impl().z // rdar://problem/20608438 protocol PConforms5 { func f() -> Int } protocol PConforms6 : PConforms5 {} extension PConforms6 { func f() -> Int { return 42 } } func test<T: PConforms6>(_ x: T) -> Int { return x.f() } struct PConforms6Impl : PConforms6 { } // Extensions of a protocol that directly satisfy requirements (i.e., // default implementations hack N+1). protocol PConforms7 { func method() var property: Int { get } subscript (i: Int) -> Int { get } } extension PConforms7 { func method() { } var property: Int { return 5 } subscript (i: Int) -> Int { return i } } struct SConforms7a : PConforms7 { } protocol PConforms8 { associatedtype Assoc func method() -> Assoc var property: Assoc { get } subscript (i: Assoc) -> Assoc { get } } extension PConforms8 { func method() -> Int { return 5 } var property: Int { return 5 } subscript (i: Int) -> Int { return i } } struct SConforms8a : PConforms8 { } struct SConforms8b : PConforms8 { func method() -> String { return "" } var property: String { return "" } subscript (i: String) -> String { return i } } func testSConforms8b() { let s: SConforms8b.Assoc = "hello" _ = s } struct SConforms8c : PConforms8 { func method() -> String { return "" } } func testSConforms8c() { let s: SConforms8c.Assoc = "hello" // expected-error{{cannot convert value of type 'String' to specified type 'SConforms8c.Assoc' (aka 'Int')}} _ = s let i: SConforms8c.Assoc = 5 _ = i } protocol DefaultInitializable { init() } extension String : DefaultInitializable { } extension Int : DefaultInitializable { } protocol PConforms9 { associatedtype Assoc : DefaultInitializable // expected-note{{protocol requires nested type 'Assoc'}} func method() -> Assoc var property: Assoc { get } subscript (i: Assoc) -> Assoc { get } } extension PConforms9 { func method() -> Self.Assoc { return Assoc() } var property: Self.Assoc { return Assoc() } subscript (i: Self.Assoc) -> Self.Assoc { return Assoc() } } struct SConforms9a : PConforms9 { // expected-error{{type 'SConforms9a' does not conform to protocol 'PConforms9'}} } struct SConforms9b : PConforms9 { typealias Assoc = Int } func testSConforms9b(_ s9b: SConforms9b) { var p = s9b.property p = 5 _ = p } struct SConforms9c : PConforms9 { typealias Assoc = String } func testSConforms9c(_ s9c: SConforms9c) { var p = s9c.property p = "hello" _ = p } struct SConforms9d : PConforms9 { func method() -> Int { return 5 } } func testSConforms9d(_ s9d: SConforms9d) { var p = s9d.property p = 6 _ = p } protocol PConforms10 {} extension PConforms10 { func f() {} } protocol PConforms11 { func f() } struct SConforms11 : PConforms10, PConforms11 {} // ---------------------------------------------------------------------------- // Typealiases in protocol extensions. // ---------------------------------------------------------------------------- // Basic support protocol PTypeAlias1 { associatedtype AssocType1 } extension PTypeAlias1 { typealias ArrayOfAssocType1 = [AssocType1] } struct STypeAlias1a: PTypeAlias1 { typealias AssocType1 = Int } struct STypeAlias1b<T>: PTypeAlias1 { typealias AssocType1 = T } func testPTypeAlias1() { var a: STypeAlias1a.ArrayOfAssocType1 = [] a.append(1) var b: STypeAlias1b<String>.ArrayOfAssocType1 = [] b.append("hello") } // Defaulted implementations to satisfy a requirement. struct TypeAliasHelper<T> { } protocol PTypeAliasSuper2 { } extension PTypeAliasSuper2 { func foo() -> TypeAliasHelper<Self> { return TypeAliasHelper() } } protocol PTypeAliasSub2 : PTypeAliasSuper2 { associatedtype Helper func foo() -> Helper } struct STypeAliasSub2a : PTypeAliasSub2 { } struct STypeAliasSub2b<T, U> : PTypeAliasSub2 { } // ---------------------------------------------------------------------------- // Partial ordering of protocol extension members // ---------------------------------------------------------------------------- // Partial ordering between members of protocol extensions and members // of concrete types. struct S1b : P1 { func reqP1a() -> Bool { return true } func extP1a() -> Int { return 0 } } func useS1b(_ s1b: S1b) { var x = s1b.extP1a() // uses S1b.extP1a due to partial ordering x = 5 // checks that "x" deduced to "Int" above _ = x var _: Bool = s1b.extP1a() // still uses P1.ext1Pa due to type annotation } // Partial ordering between members of protocol extensions for // different protocols. protocol PInherit1 { } protocol PInherit2 : PInherit1 { } protocol PInherit3 : PInherit2 { } protocol PInherit4 : PInherit2 { } extension PInherit1 { func order1() -> Int { return 0 } } extension PInherit2 { func order1() -> Bool { return true } } extension PInherit3 { func order1() -> Double { return 1.0 } } extension PInherit4 { func order1() -> String { return "hello" } } struct SInherit1 : PInherit1 { } struct SInherit2 : PInherit2 { } struct SInherit3 : PInherit3 { } struct SInherit4 : PInherit4 { } func testPInherit(_ si2 : SInherit2, si3: SInherit3, si4: SInherit4) { var b1 = si2.order1() // PInherit2.order1 b1 = true // check that the above returned Bool _ = b1 var d1 = si3.order1() // PInherit3.order1 d1 = 3.14159 // check that the above returned Double _ = d1 var s1 = si4.order1() // PInherit4.order1 s1 = "hello" // check that the above returned String _ = s1 // Other versions are still visible, since they may have different // types. b1 = si3.order1() // PInherit2.order1 var _: Int = si3.order1() // PInherit1.order1 } protocol PConstrained1 { associatedtype AssocTypePC1 } extension PConstrained1 { func pc1() -> Int { return 0 } } extension PConstrained1 where AssocTypePC1 : PInherit2 { func pc1() -> Bool { return true } } extension PConstrained1 where Self.AssocTypePC1 : PInherit3 { func pc1() -> String { return "hello" } } struct SConstrained1 : PConstrained1 { typealias AssocTypePC1 = SInherit1 } struct SConstrained2 : PConstrained1 { typealias AssocTypePC1 = SInherit2 } struct SConstrained3 : PConstrained1 { typealias AssocTypePC1 = SInherit3 } func testPConstrained1(_ sc1: SConstrained1, sc2: SConstrained2, sc3: SConstrained3) { var i = sc1.pc1() // PConstrained1.pc1 i = 17 // checks type of above _ = i var b = sc2.pc1() // PConstrained1 (with PInherit2).pc1 b = true // checks type of above _ = b var s = sc3.pc1() // PConstrained1 (with PInherit3).pc1 s = "hello" // checks type of above _ = s } protocol PConstrained2 { associatedtype AssocTypePC2 } protocol PConstrained3 : PConstrained2 { } extension PConstrained2 where Self.AssocTypePC2 : PInherit1 { func pc2() -> Bool { return true } } extension PConstrained3 { func pc2() -> String { return "hello" } } struct SConstrained3a : PConstrained3 { typealias AssocTypePC2 = Int } struct SConstrained3b : PConstrained3 { typealias AssocTypePC2 = SInherit3 } func testSConstrained3(_ sc3a: SConstrained3a, sc3b: SConstrained3b) { var s = sc3a.pc2() // PConstrained3.pc2 s = "hello" _ = s _ = sc3b.pc2() s = sc3b.pc2() var _: Bool = sc3b.pc2() } extension PConstrained3 where AssocTypePC2 : PInherit1 { } // Extending via a superclass constraint. class Superclass { func foo() { } static func bar() { } typealias Foo = Int } protocol PConstrained4 { } extension PConstrained4 where Self : Superclass { func testFoo() -> Foo { foo() self.foo() return Foo(5) } static func testBar() { bar() self.bar() } } protocol PConstrained5 { } protocol PConstrained6 { associatedtype Assoc func foo() } protocol PConstrained7 { } extension PConstrained6 { var prop1: Int { return 0 } var prop2: Int { return 0 } // expected-note{{'prop2' previously declared here}} subscript (key: Int) -> Int { return key } subscript (key: Double) -> Double { return key } // expected-note{{'subscript' previously declared here}} } extension PConstrained6 { var prop2: Int { return 0 } // expected-error{{invalid redeclaration of 'prop2'}} subscript (key: Double) -> Double { return key } // expected-error{{invalid redeclaration of 'subscript'}} } extension PConstrained6 where Assoc : PConstrained5 { var prop1: Int { return 0 } // okay var prop3: Int { return 0 } // expected-note{{'prop3' previously declared here}} subscript (key: Int) -> Int { return key } // ok subscript (key: String) -> String { return key } // expected-note{{'subscript' previously declared here}} func foo() { } // expected-note{{'foo()' previously declared here}} } extension PConstrained6 where Assoc : PConstrained5 { var prop3: Int { return 0 } // expected-error{{invalid redeclaration of 'prop3'}} subscript (key: String) -> String { return key } // expected-error{{invalid redeclaration of 'subscript'}} func foo() { } // expected-error{{invalid redeclaration of 'foo()'}} } extension PConstrained6 where Assoc : PConstrained7 { var prop1: Int { return 0 } // okay subscript (key: Int) -> Int { return key } // okay func foo() { } // okay } extension PConstrained6 where Assoc == Int { var prop4: Int { return 0 } subscript (key: Character) -> Character { return key } func foo() { } // okay } extension PConstrained6 where Assoc == Double { var prop4: Int { return 0 } // okay subscript (key: Character) -> Character { return key } // okay func foo() { } // okay } // Interaction between RawRepresentable and protocol extensions. public protocol ReallyRaw : RawRepresentable { } public extension ReallyRaw where RawValue: SignedInteger { public init?(rawValue: RawValue) { self = unsafeBitCast(rawValue, to: Self.self) } } enum Foo : Int, ReallyRaw { case a = 0 } // ---------------------------------------------------------------------------- // Semantic restrictions // ---------------------------------------------------------------------------- // Extension cannot have an inheritance clause. protocol BadProto1 { } protocol BadProto2 { } extension BadProto1 : BadProto2 { } // expected-error{{extension of protocol 'BadProto1' cannot have an inheritance clause}} extension BadProto2 { struct S { } // expected-error{{type 'S' cannot be nested in protocol extension of 'BadProto2'}} class C { } // expected-error{{type 'C' cannot be nested in protocol extension of 'BadProto2'}} enum E { } // expected-error{{type 'E' cannot be nested in protocol extension of 'BadProto2'}} } extension BadProto1 { func foo() { } var prop: Int { return 0 } subscript (i: Int) -> String { return "hello" } } protocol BadProto3 { } typealias BadProto4 = BadProto3 extension BadProto4 { } // expected-error{{protocol 'BadProto3' in the module being compiled cannot be extended via a type alias}}{{11-20=BadProto3}} typealias RawRepresentableAlias = RawRepresentable extension RawRepresentableAlias { } // okay extension AnyObject { } // expected-error{{'AnyObject' protocol cannot be extended}} // Members of protocol extensions cannot be overridden. // rdar://problem/21075287 class BadClass1 : BadProto1 { func foo() { } override var prop: Int { return 5 } // expected-error{{property does not override any property from its superclass}} } protocol BadProto5 { associatedtype T1 // expected-note{{protocol requires nested type 'T1'}} associatedtype T2 // expected-note{{protocol requires nested type 'T2'}} associatedtype T3 // expected-note{{protocol requires nested type 'T3'}} } class BadClass5 : BadProto5 {} // expected-error{{type 'BadClass5' does not conform to protocol 'BadProto5'}} typealias A = BadProto1 typealias B = BadProto1 extension A & B { // expected-error{{protocol 'BadProto1' in the module being compiled cannot be extended via a type alias}} }
fabd0ceffca3cb684d079faefdf24d52
22.373557
200
0.623165
false
false
false
false
4taras4/giphyVIP
refs/heads/develop
ActionableScreenshots/Pods/RealmSwift/RealmSwift/Migration.swift
apache-2.0
32
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm import Realm.Private /** The type of a migration block used to migrate a Realm. - parameter migration: A `Migration` object used to perform the migration. The migration object allows you to enumerate and alter any existing objects which require migration. - parameter oldSchemaVersion: The schema version of the Realm being migrated. */ public typealias MigrationBlock = (_ migration: Migration, _ oldSchemaVersion: UInt64) -> Void /// An object class used during migrations. public typealias MigrationObject = DynamicObject /** A block type which provides both the old and new versions of an object in the Realm. Object properties can only be accessed using subscripting. - parameter oldObject: The object from the original Realm (read-only). - parameter newObject: The object from the migrated Realm (read-write). */ public typealias MigrationObjectEnumerateBlock = (_ oldObject: MigrationObject?, _ newObject: MigrationObject?) -> Void /** Returns the schema version for a Realm at a given local URL. - parameter fileURL: Local URL to a Realm file. - parameter encryptionKey: 64-byte key used to encrypt the file, or `nil` if it is unencrypted. - throws: An `NSError` that describes the problem. */ public func schemaVersionAtURL(_ fileURL: URL, encryptionKey: Data? = nil) throws -> UInt64 { var error: NSError? let version = RLMRealm.__schemaVersion(at: fileURL, encryptionKey: encryptionKey, error: &error) guard version != RLMNotVersioned else { throw error! } return version } extension Realm { /** Performs the given Realm configuration's migration block on a Realm at the given path. This method is called automatically when opening a Realm for the first time and does not need to be called explicitly. You can choose to call this method to control exactly when and how migrations are performed. - parameter configuration: The Realm configuration used to open and migrate the Realm. */ public static func performMigration(for configuration: Realm.Configuration = Realm.Configuration.defaultConfiguration) throws { try RLMRealm.performMigration(for: configuration.rlmConfiguration) } } /** `Migration` instances encapsulate information intended to facilitate a schema migration. A `Migration` instance is passed into a user-defined `MigrationBlock` block when updating the version of a Realm. This instance provides access to the old and new database schemas, the objects in the Realm, and provides functionality for modifying the Realm during the migration. */ public struct Migration { // MARK: Properties /// The old schema, describing the Realm before applying a migration. public var oldSchema: Schema { return Schema(rlmMigration.oldSchema) } /// The new schema, describing the Realm after applying a migration. public var newSchema: Schema { return Schema(rlmMigration.newSchema) } internal var rlmMigration: RLMMigration // MARK: Altering Objects During a Migration /** Enumerates all the objects of a given type in this Realm, providing both the old and new versions of each object. Properties on an object can be accessed using subscripting. - parameter objectClassName: The name of the `Object` class to enumerate. - parameter block: The block providing both the old and new versions of an object in this Realm. */ public func enumerateObjects(ofType typeName: String, _ block: MigrationObjectEnumerateBlock) { rlmMigration.enumerateObjects(typeName) { oldObject, newObject in block(unsafeBitCast(oldObject, to: MigrationObject.self), unsafeBitCast(newObject, to: MigrationObject.self)) } } /** Creates and returns an `Object` of type `className` in the Realm being migrated. The `value` argument is used to populate the object. It can be a key-value coding compliant object, an array or dictionary returned from the methods in `NSJSONSerialization`, or an `Array` containing one element for each managed property. An exception will be thrown if any required properties are not present and those properties were not defined with default values. When passing in an `Array` as the `value` argument, all properties must be present, valid and in the same order as the properties defined in the model. - parameter className: The name of the `Object` class to create. - parameter value: The value used to populate the created object. - returns: The newly created object. */ @discardableResult public func create(_ typeName: String, value: Any = [:]) -> MigrationObject { return unsafeBitCast(rlmMigration.createObject(typeName, withValue: value), to: MigrationObject.self) } /** Deletes an object from a Realm during a migration. It is permitted to call this method from within the block passed to `enumerate(_:block:)`. - parameter object: An object to be deleted from the Realm being migrated. */ public func delete(_ object: MigrationObject) { rlmMigration.delete(object.unsafeCastToRLMObject()) } /** Deletes the data for the class with the given name. All objects of the given class will be deleted. If the `Object` subclass no longer exists in your program, any remaining metadata for the class will be removed from the Realm file. - parameter objectClassName: The name of the `Object` class to delete. - returns: A Boolean value indicating whether there was any data to delete. */ @discardableResult public func deleteData(forType typeName: String) -> Bool { return rlmMigration.deleteData(forClassName: typeName) } /** Renames a property of the given class from `oldName` to `newName`. - parameter className: The name of the class whose property should be renamed. This class must be present in both the old and new Realm schemas. - parameter oldName: The old name for the property to be renamed. There must not be a property with this name in the class as defined by the new Realm schema. - parameter newName: The new name for the property to be renamed. There must not be a property with this name in the class as defined by the old Realm schema. */ public func renameProperty(onType typeName: String, from oldName: String, to newName: String) { rlmMigration.renameProperty(forClass: typeName, oldName: oldName, newName: newName) } internal init(_ rlmMigration: RLMMigration) { self.rlmMigration = rlmMigration } } // MARK: Private Helpers internal func accessorMigrationBlock(_ migrationBlock: @escaping MigrationBlock) -> RLMMigrationBlock { return { migration, oldVersion in // set all accessor classes to MigrationObject for objectSchema in migration.oldSchema.objectSchema { objectSchema.accessorClass = MigrationObject.self // isSwiftClass is always `false` for object schema generated // from the table, but we need to pretend it's from a swift class // (even if it isn't) for the accessors to be initialized correctly. objectSchema.isSwiftClass = true } for objectSchema in migration.newSchema.objectSchema { objectSchema.accessorClass = MigrationObject.self } // run migration migrationBlock(Migration(migration), oldVersion) } }
0337939cca11187aeda5ad7b8d0e6972
41.593909
131
0.700512
false
false
false
false
eurofurence/ef-app_ios
refs/heads/release/4.0.0
Packages/EurofurenceModel/Sources/EurofurenceModel/Public/Default Dependency Implementations/DefaultCollectThemAllRequestFactory.swift
mit
1
import Foundation public struct DefaultCollectThemAllRequestFactory: CollectThemAllRequestFactory { private let conventionIdentifier: ConventionIdentifier public init(conventionIdentifier: ConventionIdentifier) { self.conventionIdentifier = conventionIdentifier } public func makeAnonymousGameURLRequest() -> URLRequest { return URLRequest(url: makeGameURL()) } public func makeAuthenticatedGameURLRequest(credential: Credential) -> URLRequest { return URLRequest(url: makeGameURL(token: credential.authenticationToken)) } private func makeGameURL(token: String? = nil) -> URL { let cid = conventionIdentifier.identifier var urlString = "https://app.eurofurence.org/\(cid)/companion/#/login?embedded=true&returnPath=/collect&token=" let tokenToSend: String = { if let token = token { return token } else { return "empty" } }() urlString.append(tokenToSend) guard let url = URL(string: urlString) else { fatalError("Error marshalling token into url: \(urlString)") } return url } }
6e19a2f9cabb311a2c58f3ef0115799d
29.8
119
0.635552
false
false
false
false
flodolo/firefox-ios
refs/heads/main
SyncTelemetry/SyncTelemetry.swift
mpl-2.0
2
// 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 SwiftyJSON import Shared private let log = Logger.browserLogger private let ServerURL = "https://incoming.telemetry.mozilla.org".asURL! private let AppName = "Fennec" public enum TelemetryDocType: String { case core = "core" case sync = "sync" } public protocol SyncTelemetryEvent { func record(_ prefs: Prefs) } open class SyncTelemetry { private static var prefs: Prefs? private static var telemetryVersion: Int = 4 open class func initWithPrefs(_ prefs: Prefs) { assert(self.prefs == nil, "Prefs already initialized") self.prefs = prefs } open class func recordEvent(_ event: SyncTelemetryEvent) { guard let prefs = prefs else { assertionFailure("Prefs not initialized") return } event.record(prefs) } open class func send(ping: SyncTelemetryPing, docType: TelemetryDocType) { let docID = UUID().uuidString let appVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String let buildID = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String let channel = AppConstants.BuildChannel.rawValue let path = "/submit/telemetry/\(docID)/\(docType.rawValue)/\(AppName)/\(appVersion)/\(channel)/\(buildID)" let url = ServerURL.appendingPathComponent(path) var request = URLRequest(url: url) log.debug("Ping URL: \(url)") log.debug("Ping payload: \(ping.payload.stringify() ?? "")") // Don't add the common ping format for the mobile core ping. let pingString: String? if docType != .core { var json = JSON(commonPingFormat(forType: docType)) json["payload"] = ping.payload pingString = json.stringify() } else { pingString = ping.payload.stringify() } guard let body = pingString?.data(using: .utf8) else { log.error("Invalid data!") assertionFailure() return } guard channel != "default" else { log.debug("Non-release build; not sending ping") return } request.httpMethod = "POST" request.httpBody = body request.addValue(Date().toRFC822String(), forHTTPHeaderField: "Date") request.setValue("application/json", forHTTPHeaderField: "Content-Type") makeURLSession(userAgent: UserAgent.fxaUserAgent, configuration: URLSessionConfiguration.ephemeral).dataTask(with: request) { (_, response, error) in let code = (response as? HTTPURLResponse)?.statusCode log.debug("Ping response: \(code ?? -1).") }.resume() } private static func commonPingFormat(forType type: TelemetryDocType) -> [String: Any] { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) let date = formatter.string(from: NSDate() as Date) let displayVersion = [ AppInfo.appVersion, "b", AppInfo.buildNumber ].joined() let version = ProcessInfo.processInfo.operatingSystemVersion let osVersion = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" return [ "type": type.rawValue, "id": UUID().uuidString, "creationDate": date, "version": SyncTelemetry.telemetryVersion, "application": [ "architecture": "arm", "buildId": AppInfo.buildNumber, "name": AppInfo.displayName, "version": AppInfo.appVersion, "displayVersion": displayVersion, "platformVersion": osVersion, "channel": AppConstants.BuildChannel.rawValue ] ] } } public protocol SyncTelemetryPing { var payload: JSON { get } }
9efef6f541c8f72c483292eb485a0dca
34.487395
157
0.621359
false
false
false
false
alfishe/mooshimeter-osx
refs/heads/master
mooshimeter-osx/Common/ThreadHelper.swift
mit
1
// // Created by Dev on 8/28/16. // Copyright (c) 2016 alfishe. All rights reserved. // import Foundation func delay(bySeconds seconds: Double, dispatchLevel: DispatchLevel = .main, closure: @escaping () -> Void) { let dispatchTime = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) dispatchLevel.dispatchQueue.asyncAfter(deadline: dispatchTime, execute: closure) } enum DispatchLevel { case main case userInteractive case userInitiated case utility case background var dispatchQueue: DispatchQueue { var result: DispatchQueue switch self { case .main: result = DispatchQueue.main case .userInteractive: result = DispatchQueue.global(qos: DispatchQoS.QoSClass.userInteractive) case .userInitiated: result = DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated) case .utility: result = DispatchQueue.global(qos: DispatchQoS.QoSClass.utility) case .background: result = DispatchQueue.global(qos: DispatchQoS.QoSClass.background) } return result } }
0303ef0d4193af7d8d1430f311b861a1
25.47619
110
0.707734
false
false
false
false
diegoreymendez/CreedShrink
refs/heads/master
CreedShrink/MultiplicationPacker.swift
apache-2.0
1
import Foundation class MultiplicationPacker { // MARK: Multiplication packing func packMultiplyValues(values : [Int], packSize : Int) -> [Int] { guard values.count > 0 else { return [] } var output = [Int]() var multiplication = 0 let maxValue = values.maxElement()! for i in 0...values.count - 1 { let value = values[i] if i % packSize == 0 { if i > 0 { output.append(multiplication) } multiplication = value } else { multiplication *= (maxValue + 1) multiplication += value } } output.append(multiplication) return output } func unpackMultiplyValues(values: [Int], maxValue: Int, packSize: Int, lastPackSize: Int) -> [Int] { guard values.count > 0 else { return [] } var unpackedValues = [Int]() for value in values { var tempValue = value var packValues = [Int]() let isLastPack = (unpackedValues.count / packSize == values.count - 1) for _ in 0...packSize - 1 { let unpackedValue = tempValue % (maxValue + 1) tempValue = tempValue / (maxValue + 1) packValues.append(unpackedValue) if isLastPack && packValues.count == lastPackSize { break } } // We'll need to invert these since the unpacking operation provides the last elements first. // packValues = packValues.reverse() unpackedValues.appendContentsOf(packValues) } return unpackedValues } }
df73f3b59c309da36300c5619a2751ce
27
105
0.455964
false
false
false
false
quire-io/SwiftyChrono
refs/heads/master
Sources/Parsers/EN/ENDeadlineFormatParser.swift
mit
1
// // ENDeadlineFormatParser.swift // SwiftyChrono // // Created by Jerry Chen on 1/19/17. // Copyright © 2017 Potix. All rights reserved. // import Foundation private let PATTERN = "(\\W|^)" + "(within|in)\\s*" + "(\(EN_INTEGER_WORDS_PATTERN)|[0-9]+|an?(?:\\s*few)?|half(?:\\s*an?)?)\\s*" + "(seconds?|min(?:ute)?s?|hours?|days?|weeks?|months?|years?)\\s*" + "(?=\\W|$)" private let STRICT_PATTERN = "(\\W|^)" + "(within|in)\\s*" + "(\(EN_INTEGER_WORDS_PATTERN)|[0-9]+|an?)\\s*" + "(seconds?|minutes?|hours?|days?)\\s*" + "(?=\\W|$)" public class ENDeadlineFormatParser: Parser { override var pattern: String { return strictMode ? STRICT_PATTERN : PATTERN } override public func extract(text: String, ref: Date, match: NSTextCheckingResult, opt: [OptionType: Int]) -> ParsedResult? { let (matchText, index) = matchTextAndIndex(from: text, andMatchResult: match) var result = ParsedResult(ref: ref, index: index, text: matchText) result.tags[.enDeadlineFormatParser] = true let number: Int let numberText = match.string(from: text, atRangeIndex: 3).lowercased() if let number0 = EN_INTEGER_WORDS[numberText] { number = number0 } else if numberText == "a" || numberText == "an" { number = 1 } else if NSRegularExpression.isMatch(forPattern: "few", in: numberText) { number = 3 } else if NSRegularExpression.isMatch(forPattern: "half", in: numberText) { number = HALF } else { number = Int(numberText)! } var date = ref let matchText4 = match.string(from: text, atRangeIndex: 4) func ymdResult() -> ParsedResult { result.start.assign(.year, value: date.year) result.start.assign(.month, value: date.month) result.start.assign(.day, value: date.day) return result } if NSRegularExpression.isMatch(forPattern: "day", in: matchText4) { date = number != HALF ? date.added(number, .day) : date.added(12, .hour) return ymdResult() } else if NSRegularExpression.isMatch(forPattern: "week", in: matchText4) { date = number != HALF ? date.added(number * 7, .day) : date.added(3, .day).added(12, .hour) return ymdResult() } else if NSRegularExpression.isMatch(forPattern: "month", in: matchText4) { date = number != HALF ? date.added(number, .month) : date.added((date.numberOf(.day, inA: .month) ?? 30)/2, .day) return ymdResult() } else if NSRegularExpression.isMatch(forPattern: "year", in: matchText4) { date = number != HALF ? date.added(number, .year) : date.added(6, .month) return ymdResult() } if NSRegularExpression.isMatch(forPattern: "hour", in: matchText4) { date = number != HALF ? date.added(number, .hour) : date.added(30, .minute) } else if NSRegularExpression.isMatch(forPattern: "min", in: matchText4) { date = number != HALF ? date.added(number, .minute) : date.added(30, .second) } else if NSRegularExpression.isMatch(forPattern: "second", in: matchText4) { date = number != HALF ? date.added(number, .second) : date.added(HALF_SECOND_IN_MS, .nanosecond) } result.start.imply(.year, to: date.year) result.start.imply(.month, to: date.month) result.start.imply(.day, to: date.day) result.start.assign(.hour, value: date.hour) result.start.assign(.minute, value: date.minute) result.start.assign(.second, value: date.second) return result } }
43d20f138dcd30b058cb67de494a1e22
41.348315
129
0.586628
false
false
false
false
IDLabs-Gate/enVision
refs/heads/master
enVision/YOLO.swift
mit
2
// // The MIT License (MIT) // // Copyright (c) 2016 ID Labs L.L.C. // // 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 typealias YoloOutput = [(label: String, prob: Double, box: CGRect, object: CIImage)] class YOLO { var threshold = 0.25 private var tfYolo : tfWrap? private var coco = false private var v2 = false private let anchors_voc = [1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52] private let anchors_coco = [0.738768, 0.874946, 2.42204, 2.65704, 4.30971, 7.04493, 10.246, 4.59428, 12.6868, 11.8741] typealias YoloBox = (c: Double, x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat,probs: [Double]) func load(_ model: Int=0){ clean() tfYolo = tfWrap() switch model { //1: YOLO 1 tiny //2: YOLO 1 small //3: YOLO 1.1 tiny //0,4: YOLO 2 case 1: tfYolo?.loadModel("yolo-tiny-opt.pb", labels: "voc-labels.txt", memMapped: true, optEnv: true) coco = false; v2 = false case 2: tfYolo?.loadModel("yolo-small-opt.pb", labels: "voc-labels.txt", memMapped: true, optEnv: true) coco = false; v2 = false case 3: tfYolo?.loadModel("tiny-coco-map.pb" , labels: "coco-labels.txt", memMapped: true, optEnv: true) coco = true; v2 = false default: tfYolo?.loadModel("yolo-map.pb", labels: "coco-labels.txt", memMapped: true, optEnv: true) coco = true; v2 = true } tfYolo?.setInputLayer("input", outputLayer: "output") } func run(image: CIImage)-> YoloOutput { guard let tfYolo = tfYolo else { return [] } //pre-processing let inputEdge = v2 ? 416 : 448 let input = CIImage(cgImage: resizeImage(image, newWidth: CGFloat(inputEdge), newHeight: CGFloat(inputEdge)).cgImage!) var buffer : CVPixelBuffer? CVPixelBufferCreate(kCFAllocatorDefault, inputEdge, inputEdge, kCVPixelFormatType_32BGRA, [String(kCVPixelBufferIOSurfacePropertiesKey) : [:]] as CFDictionary, &buffer) if let buffer = buffer { CIContext().render(input, to: buffer) } //neural network forward run guard let network_output = tfYolo.run(onFrame: buffer) else { return [] } let output = network_output.flatMap{ ($0 as? NSNumber)?.doubleValue } //post-processing var boxes = postProcessYolo(output: output) //suppress redundant boxes boxes = suppressOverlappingYoloBoxes(boxes, classes: coco ? 80 : 20) let labels = tfYolo.getLabels().flatMap{ $0 as? String } return boxes.flatMap { b -> (label: String, prob: Double, box: CGRect, object: CIImage)? in //get probabilities per class guard let max_prob = b.probs.max() else { return nil } guard max_prob>0 else { return nil } guard let max_index = b.probs.index(of: max_prob) else { return nil } guard max_index<labels.count else { return nil } let label = labels[max_index] guard label != "non_object" else{return nil} //convert Yolo boxes to screen let frameWidth = image.extent.width let frameHeight = image.extent.height let screenWidth = UIScreen.main.bounds.width let screenHeight = UIScreen.main.bounds.height let horizontal = frameWidth/frameHeight > screenWidth/screenHeight let seenWidth = horizontal ? screenWidth : screenHeight*frameWidth/frameHeight let seenHeight = horizontal ? screenWidth*frameHeight/frameWidth : screenHeight let biasX = horizontal ? 0 : (screenWidth-seenWidth)/2 let biasY = horizontal ? (screenHeight-seenHeight)/2 : 0 let x = (b.x-b.w/2)*seenWidth + biasX let y = (b.y-b.h/2)*seenHeight + biasY let w = b.w*seenWidth let h = b.h*seenHeight let screenRect = CGRect(x: x, y: y, width: w, height: h) //extract Yolo objects from image let xx = (b.x-b.w/2)*frameWidth let yy = (b.y-b.h/2)*frameHeight let ww = b.w*frameWidth let hh = b.h*frameHeight let rect = CGRect(x: xx, y: yy, width: ww, height: hh) let object = cropImage(image, to: rect, margin: 0.2*(rect.width<rect.height ? rect.width : rect.height)) return (label, max_prob, screenRect, object) } } func postProcessYolo(output:[Double])-> [YoloBox] { return v2 ? postProcessYoloV2(output: output) : postProcessYoloV1(output: output) } func postProcessYoloV1(output: [Double]) -> [YoloBox] { let S = 7 let SS = S*S let B = coco ? 3 : 2 let C = coco ? 80 : 20 let prob_size = SS*C let conf_size = SS*B let probs1 = Array(output.prefix(prob_size)) let confs1 = Array(output[prob_size..<prob_size+conf_size]) let cords1 = Array(output[prob_size+conf_size..<output.count]) //reshape! //zeros in the right dimensions var probs = Tensor([SS,C]) as! [[Double]] var confs = Tensor([SS,B]) as! [[Double]] var cords = Tensor([SS,B,4]) as! [[[Double]]] //var cords = [[[Double]]](repeating:[[Double]](repeating: [Double](repeating: 0, count: 4), count: B), count: SS) //fill in values var i = 0 for ss in 0..<probs.count { for c in 0..<probs[ss].count { probs[ss][c] = probs1[i] i += 1 } } i = 0 for ss in 0..<confs.count { for b in 0..<confs[ss].count { confs[ss][b] = confs1[i] i += 1 } } i = 0 for ss in 0..<cords.count { for b in 0..<cords[ss].count { for g in 0..<cords[ss][b].count { cords[ss][b][g] = cords1[i] i += 1 } } } //evaluate boxes var boxes = [YoloBox]() for grid in 0..<SS { for b in 0..<B{ //The (x, y) coordinates represent the center of the box relative to the bounds of the grid cell. The width and height are predicted relative to the whole image. let biasX = Double(grid%S) let biasY = floor(Double(grid)/Double(S)) let c = confs[grid][b] let x = CGFloat((cords[grid][b][0] + biasX)/Double(S)) let y = CGFloat((cords[grid][b][1] + biasY)/Double(S)) let w = CGFloat(pow(cords[grid][b][2],2)) let h = CGFloat(pow(cords[grid][b][3],2)) let probs = Array(0..<C).map { i in c * probs[grid][i]>self.threshold ? c * probs[grid][i] : 0 }//apply threshold if probs.contains(where: {$0>0}) { boxes.append((c, x, y, w, h, probs )) } } } return boxes } func postProcessYoloV2(output: [Double]) -> [YoloBox] { let B = 5 let W = 13 let H = 13 let R = output.count/(W*H*B) var values = Tensor([H,W,B,R]) as! [[[[Double]]]] var i = 0 for h in 0..<values.count { for w in 0..<values[h].count { for b in 0..<values[h][w].count { for r in 0..<values[h][w][b].count { values[h][w][b][r] = output[i] i += 1 } } } } //print("Shape", values.count, values[0].count, values[0][0].count, values[0][0][0].count) //evaluate boxes var boxes = [YoloBox]() let anchors = coco ? anchors_coco : anchors_voc for row in 0..<H { for col in 0..<W { for b in 0..<B { var x = values[row][col][b][0] var y = values[row][col][b][1] var w = values[row][col][b][2] var h = values[row][col][b][3] var c = values[row][col][b][4] c = expit(c) x = (Double(col)+expit(x))/13 y = (Double(row)+expit(y))/13 w = pow(M_E, w)*anchors[2*b+0]/13 h = pow(M_E, h)*anchors[2*b+1]/13 let classes = Array(values[row][col][b][5..<R]) let probs = softmax(classes).map { $0*c>self.threshold ? $0*c : 0 }//apply threshold if probs.contains(where: {$0>0}) { boxes.append((c,CGFloat(x),CGFloat(y),CGFloat(w),CGFloat(h),probs)) } } } } return boxes } func suppressOverlappingYoloBoxes(_ boxes:[YoloBox], classes: Int)-> [YoloBox] { var boxes = boxes for c in 0..<classes { //for each class boxes.sort{ a, b -> Bool in a.probs[c] < b.probs[c] } for i in 0..<boxes.count { let b = boxes[i] if b.probs[c] == 0 { continue } for j in i+1..<boxes.count { let b2 = boxes[j] let rect1 = CGRect(x: b.x, y: b.y, width: b.w, height: b.h) let rect2 = CGRect(x: b2.x, y: b2.y, width: b2.w, height: b2.h) let intersection = boxIntersection(a: rect1, b: rect2) let area2 = b2.w*b2.h let apart = intersection/area2 if apart >= 0.5 {//suppress with over %50 overlap if b.probs[c] > b2.probs[c] { var jprobs = b2.probs jprobs[c] = 0 boxes[j] = (b2.c, b2.x, b2.y, b2.w, b2.h, jprobs) } else { var iprobs = b.probs iprobs[c] = 0 boxes[i] = (b.c, b.x, b.y, b.w, b.h, iprobs) } } } } } return boxes } func Tensor(_ dim: [Int]) -> [Any] { guard dim.count > 0 else { return [] } var tensor = [Any]() tensor = [Double](repeating:0,count: dim.last!) guard dim.count>1 else { return tensor } for d in (0...dim.count-2).reversed() { tensor = [Any](repeating: tensor,count:dim[d]) } return tensor } func boxIntersection(a: CGRect, b: CGRect)-> CGFloat{ func overlap (x1: CGFloat, w1: CGFloat, x2: CGFloat, w2: CGFloat)-> CGFloat{ let l1 = x1 - w1/2 let l2 = x2 - w2/2 let left = max(l1,l2) let r1 = x1 + w1/2 let r2 = x2 + w2/2 let right = min(r1,r2) return right - left } let w = overlap(x1: a.origin.x, w1: a.width, x2: b.origin.x, w2: b.width) let h = overlap(x1: a.origin.y, w1: a.height, x2: b.origin.y, w2: b.height) if w<0 || h<0 { return 0 } let result = w*h return result } func expit(_ x: Double)-> Double { let result = Double(1)/Double(1+pow(M_E, -x)) return result } func softmax(_ X: [Double])-> [Double] { guard let max = X.max() else { return [] } var result = X.map { x in pow(M_E, x-max) } let sum = result.reduce(0, +) result = result.map { $0/sum } return result } func clean() { tfYolo?.clean() tfYolo = nil } }
003e43aec06bb3410a37cb79e44092a8
33.799499
177
0.475477
false
false
false
false
RemyDCF/tpg-offline
refs/heads/master
tpg offline/Departures/ConnectionsMapViewController.swift
mit
1
// // ConnectionsMapViewController.swift // tpg offline // // Created by Rémy Da Costa Faro on 21/01/2018. // Copyright © 2018 Rémy Da Costa Faro. All rights reserved. // import UIKit import Alamofire import Crashlytics class ConnectionsMapViewController: UIViewController { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var errorLabel: UILabel! @IBOutlet weak var loadingView: UIActivityIndicatorView! var imageView: UIImageView! var stopCode: String = "" var downloadData: Data? var saved = false override func viewDidLoad() { super.viewDidLoad() App.log("Show connections maps") App.logEvent("Show connections maps", attributes: ["appCode": stopCode]) title = "Map".localized errorLabel.text = "Error. You're not connected to internet." errorLabel.textColor = App.textColor errorLabel.isHidden = true loadingView.style = App.darkMode ? .white : .gray loadingView.startAnimating() var path: URL guard let dirString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .allDomainsMask, true).first else { return } let dir = URL(fileURLWithPath: dirString) path = dir.appendingPathComponent("\(stopCode).jpg") do { let data = try Data(contentsOf: path) let image = UIImage(data: data) self.saved = true self.imageView = UIImageView(image: image) loadingView.isHidden = true self.adjustScrollView() } catch { Alamofire .request(URL.connectionsMap(stopCode: stopCode)) .responseData(completionHandler: { (response) in if let data = response.result.value { self.downloadData = data let image = UIImage(data: data) self.imageView = UIImageView(image: image) self.adjustScrollView() } else { self.errorLabel.isHidden = false } self.loadingView.isHidden = true }) } self.view.backgroundColor = App.cellBackgroundColor ColorModeManager.shared.addColorModeDelegate(self) } @objc func reload() { Alamofire .request(URL.connectionsMap(stopCode: stopCode)) .responseData(completionHandler: { (response) in if let data = response.result.value { self.save() self.downloadData = data let image = UIImage(data: data) self.imageView = UIImageView(image: image) self.adjustScrollView() self.save() } else { self.errorLabel.isHidden = false } self.loadingView.isHidden = true }) } func adjustScrollView() { navigationItem.rightBarButtonItems = [UIBarButtonItem(image: self.saved ? #imageLiteral(resourceName: "trash") : #imageLiteral(resourceName: "download"), style: .plain, target: self, action: #selector(self.save), accessbilityLabel: Text.downloadMap), UIBarButtonItem(image: #imageLiteral(resourceName: "reloadNavBar"), style: .plain, target: self, action: #selector(self.reload), accessbilityLabel: Text.reloadMap)] scrollView.delegate = self scrollView.backgroundColor = .white scrollView.contentSize = imageView.bounds.size scrollView.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight] let point = CGPoint(x: (scrollView.contentSize.width - scrollView.bounds.size.width) / 2, y: (scrollView.contentSize.height - scrollView.bounds.size.height) / 2) scrollView.setContentOffset(point, animated: false) scrollView.addSubview(imageView) setZoomScale() } deinit { ColorModeManager.shared.removeColorModeDelegate(self) } override func colorModeDidUpdated() { super.colorModeDidUpdated() self.view.backgroundColor = App.cellBackgroundColor errorLabel.textColor = App.textColor loadingView.style = App.darkMode ? .white : .gray } @objc func save() { if !self.saved { guard let downloadData = downloadData else { return } DispatchQueue.global(qos: .utility).async { var fileURL = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .allDomainsMask, true)[0]) fileURL.appendPathComponent("\(self.stopCode).jpg") do { try downloadData.write(to: fileURL) self.saved = true DispatchQueue.main.async { self.navigationItem.rightBarButtonItems = [UIBarButtonItem(image: self.saved ? #imageLiteral(resourceName: "trash") : #imageLiteral(resourceName: "download"), style: .plain, target: self, action: #selector(self.save), accessbilityLabel: Text.downloadMap), UIBarButtonItem(image: #imageLiteral(resourceName: "reloadNavBar"), style: .plain, target: self, action: #selector(self.reload), accessbilityLabel: Text.reloadMap)] } } catch let error { print(error) } } } else { DispatchQueue.global(qos: .utility).async { var fileURL = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .allDomainsMask, true)[0]) fileURL.appendPathComponent("\(self.stopCode).jpg") do { try FileManager.default.removeItem(at: fileURL) self.saved = false DispatchQueue.main.async { self.navigationItem.rightBarButtonItems = [UIBarButtonItem(image: self.saved ? #imageLiteral(resourceName: "trash") : #imageLiteral(resourceName: "download"), style: .plain, target: self, action: #selector(self.save), accessbilityLabel: Text.downloadMap), UIBarButtonItem(image: #imageLiteral(resourceName: "reloadNavBar"), style: .plain, target: self, action: #selector(self.reload), accessbilityLabel: Text.reloadMap)] } } catch let error { print(error) } } } } } extension ConnectionsMapViewController: UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } func setZoomScale() { guard let imageView = imageView else { return } let imageViewSize = imageView.bounds.size let scrollViewSize = scrollView.bounds.size let widthScale = scrollViewSize.width / imageViewSize.width let heightScale = scrollViewSize.height / imageViewSize.height scrollView.minimumZoomScale = min(widthScale, heightScale) scrollView.maximumZoomScale = 10.0 scrollView.zoomScale = scrollView.minimumZoomScale * 2 } override func viewWillLayoutSubviews() { setZoomScale() } func scrollViewDidZoom(_ scrollView: UIScrollView) { let imageViewSize = imageView.frame.size let scrollViewSize = scrollView.bounds.size let verticalPadding = imageViewSize.height < scrollViewSize.height ? (scrollViewSize.height - imageViewSize.height) / 2 : 0 let horizontalPadding = imageViewSize.width < scrollViewSize.width ? (scrollViewSize.width - imageViewSize.width) / 2 : 0 scrollView.contentInset = UIEdgeInsets(top: verticalPadding, left: horizontalPadding, bottom: verticalPadding, right: horizontalPadding) } }
2d772b0a24862ddedb11bf4aab7342dc
36.511111
130
0.57737
false
false
false
false
SomeSimpleSolutions/MemorizeItForever
refs/heads/Development
MemorizeItForeverCore/MemorizeItForeverCore/BusinessLayer/Word Management/WordManager.swift
mit
1
// // WordManager.swift // MemorizeItForever // // Created by Hadi Zamani on 5/1/16. // Copyright © 2016 SomeSimpleSolution. All rights reserved. // import Foundation final public class WordManager: WordManagerProtocol { private var wordDataAccess: WordDataAccessProtocol private var wordHistoryDataAccess: WordHistoryDataAccessProtocol? public init(wordDataAccess: WordDataAccessProtocol, wordHistoryDataAccess: WordHistoryDataAccessProtocol? = nil){ self.wordDataAccess = wordDataAccess self.wordHistoryDataAccess = wordHistoryDataAccess } public func save(_ phrase: String, meaninig: String, setId: UUID) throws{ do{ var word = WordModel() word.phrase = phrase word.meaning = meaninig word.setId = setId try wordDataAccess.save(word) } catch{ throw error } } public func edit(_ wordModel: WordModel, phrase: String, meaninig: String){ do{ var word = WordModel() word.phrase = phrase word.meaning = meaninig word.status = wordModel.status word.order = wordModel.order word.setId = wordModel.setId word.wordId = wordModel.wordId try wordDataAccess.edit(word) } catch{ } } public func delete(_ wordModel: WordModel) -> Bool{ do{ try wordDataAccess.delete(wordModel) } catch{ return false } return true } public func fetchWords(phrase: String, status: WordStatus, fetchLimit: Int, fetchOffset: Int) -> [WordModel] { do{ if phrase.trim().isEmpty{ return try wordDataAccess.fetchWords(status: status, fetchLimit: fetchLimit, fetchOffset: fetchOffset) } else{ return try wordDataAccess.fetchWords(phrase: phrase, status: status, fetchLimit: fetchLimit, fetchOffset: fetchOffset) } } catch{ return [] } } public func fetchWordHistoryByWord(wordModel: WordModel) -> [WordHistoryModel] { guard let wordHistoryDataAccess = wordHistoryDataAccess else { fatalError("wordHistoryDataAccess is not initialized") } var wordHistoryModel = WordHistoryModel() wordHistoryModel.word = wordModel do{ return try wordHistoryDataAccess.fetchByWordId(wordHistoryModel) } catch{ } return [] } }
8a3edaba833f829ab0136709e5bb4b55
29.418605
134
0.595183
false
false
false
false
nodes-vapor/admin-panel
refs/heads/master
Sources/AdminPanel/routes.swift
mit
1
import Authentication import Flash import Routing import Sugar import Vapor public struct AdminPanelEndpoints { public let login: String public let logout: String public let dashboard: String public let adminPanelUserBasePath: String public let createSlug: String public let deleteSlug: String public let editSlug: String public let meSlug: String public init( adminPanelUserBasePath: String = "/admin/users", dashboard: String = "/admin", login: String = "/admin/login", logout: String = "/admin/logout", createSlug: String = "create", deleteSlug: String = "delete", editSlug: String = "edit", meSlug: String = "me" ) { self.login = login self.logout = logout self.dashboard = dashboard self.adminPanelUserBasePath = adminPanelUserBasePath self.createSlug = createSlug self.deleteSlug = deleteSlug self.editSlug = editSlug self.meSlug = meSlug } public static var `default`: AdminPanelEndpoints { return .init() } } public struct AdminPanelMiddlewares: Service { public let secure: [Middleware] public let unsecure: [Middleware] } public extension Router { func useAdminPanelRoutes<U: AdminPanelUserType>( _ type: U.Type, on container: Container ) throws { let config: AdminPanelConfig<U> = try container.make() let middlewares: AdminPanelMiddlewares = try container.make() let unprotected = grouped(middlewares.unsecure) let protected = grouped(middlewares.secure) let endpoints = config.endpoints let controllers = config.controllers let loginController = controllers.loginController let dashboardController = controllers.dashboardController let adminPanelUserController = controllers.adminPanelUserController // MARK: Login routes unprotected.get(endpoints.login) { req in try loginController.renderLogin(req) } unprotected.post(endpoints.login) { req in try loginController.login(req) } unprotected.get(endpoints.logout) { req in try loginController.logout(req) } // MARK: Dashboard routes protected.get(endpoints.dashboard) { req in try dashboardController.renderDashboard(req) } // MARK: Admin Panel User routes protected.get(endpoints.adminPanelUserBasePath) { req in try adminPanelUserController.renderList(req) } protected.get(endpoints.adminPanelUserBasePath, endpoints.createSlug) { req in try adminPanelUserController.renderCreate(req) } protected.post(endpoints.adminPanelUserBasePath, endpoints.createSlug) { req in try adminPanelUserController.create(req) } protected.get(endpoints.adminPanelUserBasePath, U.parameter, endpoints.editSlug) { req in try adminPanelUserController.renderEditUser(req) } protected.post(endpoints.adminPanelUserBasePath, U.parameter, endpoints.editSlug) { req in try adminPanelUserController.editUser(req) } protected.post(endpoints.adminPanelUserBasePath, U.parameter, endpoints.deleteSlug) { req in try adminPanelUserController.delete(req) } protected.get(endpoints.adminPanelUserBasePath, endpoints.meSlug, endpoints.editSlug) { req in try adminPanelUserController.renderEditMe(req) } protected.post(endpoints.adminPanelUserBasePath, endpoints.meSlug, endpoints.editSlug) { req in try adminPanelUserController.editMe(req) } // MARK: Reset routes try unprotected.useResetRoutes(type, on: container) } }
45d5fc3fd700778e31a31d84f8235ecf
31.854701
103
0.664672
false
false
false
false
Ben21hao/edx-app-ios-enterprise-new
refs/heads/master
Source/UIGestureRecognizer+BlockActions.swift
apache-2.0
3
// // UIGestureRecognizer+BlockActions.swift // edX // // Created by Akiva Leffert on 6/22/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation private class GestureListener : Removable { let token = malloc(1) var action : (UIGestureRecognizer -> Void)? var removeAction : (GestureListener -> Void)? deinit { free(token) } @objc func gestureFired(gesture : UIGestureRecognizer) { self.action?(gesture) } func remove() { removeAction?(self) } } protocol GestureActionable { init(target : AnyObject?, action : Selector) } extension UIGestureRecognizer : GestureActionable {} extension GestureActionable where Self : UIGestureRecognizer { init(action : Self -> Void) { self.init(target: nil, action: nil) addAction(action) } func addAction(action : Self -> Void) -> Removable { let listener = GestureListener() listener.action = {(gesture : UIGestureRecognizer) in if let gesture = gesture as? Self { action(gesture) } } objc_setAssociatedObject(self, listener.token, listener, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) listener.removeAction = {[weak self] (listener : GestureListener) in self?.removeTarget(listener, action: nil) objc_setAssociatedObject(self, listener.token, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } self.addTarget(listener, action: #selector(GestureListener.gestureFired(_:))) return listener } }
031031ada45a159741a63301c90ea337
26.830508
122
0.640073
false
false
false
false
curia007/UserSample
refs/heads/master
UserSample/UserSample/ViewController.swift
apache-2.0
1
// // ViewController.swift // UserSample // // Created by Carmelo Uria on 7/17/17. // Copyright © 2017 Carmelo Uria. All rights reserved. // import UIKit import CoreLocation class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var firstNameTextField: UITextField! @IBOutlet weak var lastNameTextField: UITextField! @IBOutlet weak var addressTextField: UITextField! @IBOutlet weak var countryTextField: UITextField! @IBOutlet weak var cityTextField: UITextField! @IBOutlet weak var stateTextField: UITextField! @IBOutlet weak var zipCodeTextField: UITextField! @IBOutlet weak var resultsTextView: UITextView! @IBOutlet weak var submitButton: UIButton! fileprivate var json: [Any] = [] fileprivate var coordinate : [AnyHashable : Any] = [:] fileprivate var address : [AnyHashable : Any] = [:] fileprivate var activeField: UITextField? fileprivate let services: GenericServices = GenericServices() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.hideKeyboardWhenTapped() firstNameTextField.delegate = self lastNameTextField.delegate = self addressTextField.delegate = self cityTextField.delegate = self stateTextField.delegate = self zipCodeTextField.delegate = self countryTextField.delegate = self registerForKeyboardNotifications() NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: LOCATION_ADDRESS_RETRIEVED), object: nil, queue: OperationQueue.main) { (notification) in let placemark: CLPlacemark = notification.object as! CLPlacemark debugPrint("[\(#function)] placemark: \(placemark)") let locationProcessor: LocationProcessor = (UIApplication.shared.delegate as! AppDelegate).locationProcessor locationProcessor.stopProcessor() guard let addressDictionary: [AnyHashable : Any] = placemark.addressDictionary else { // enable text fields and start location processor self.addressTextField.isEnabled = true self.cityTextField.isEnabled = true self.stateTextField.isEnabled = true self.zipCodeTextField.isEnabled = true self.countryTextField.isEnabled = true return } self.address = addressDictionary self.coordinate = ["latitude" : placemark.location!.coordinate.latitude, "longitude" : placemark.location!.coordinate.longitude] self.addressTextField.text = addressDictionary["Street"] as? String self.cityTextField.text = addressDictionary["City"] as? String self.stateTextField.text = addressDictionary["State"] as? String self.zipCodeTextField.text = addressDictionary["ZIP"] as? String self.countryTextField.text = addressDictionary["Country"] as? String self.submitButton.isEnabled = true } } override func viewDidDisappear(_ animated: Bool) { deregisterFromKeyboardNotifications() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if (CLLocationManager.locationServicesEnabled() == false) { // create the alert let alert = UIAlertController(title: "Location Services", message: "Location Services is not Available.", preferredStyle: UIAlertControllerStyle.alert) // add an action (button) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) // show the alert self.present(alert, animated: true, completion: nil) } } // MAKRK: - Action functions @IBAction func submitAction(_ sender: Any) { let jsonProcessor: JSONProcessor = (UIApplication.shared.delegate as! AppDelegate).jsonProcessor let user: [String : Any] = ["firstName" : firstNameTextField.text ?? " ", "lastName" : lastNameTextField.text ?? " ", "coordinate" : coordinate, "addressDictionary" : address] json = [user] guard let jsonData: Data = jsonProcessor.generateJSON(json) else { debugPrint("[\(#function)] JSON Data is nil") return } let results : String = String(data: jsonData, encoding: .utf8)! debugPrint("[\(#function)] results: \(results)") resultsTextView.backgroundColor = UIColor.green resultsTextView.alpha = 0.50 resultsTextView.text = results // Generic Service commented out, since the service doesn't exist //services.callService(jsonData) } // MARK: - Keyboard functions func registerForKeyboardNotifications(){ //Adding notifies on keyboard appearing NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func deregisterFromKeyboardNotifications(){ //Removing notifies on keyboard appearing NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func keyboardWasShown(notification: NSNotification){ //Need to calculate keyboard exact size due to Apple suggestions self.scrollView.isScrollEnabled = true var info = notification.userInfo! let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0) self.scrollView.contentInset = contentInsets self.scrollView.scrollIndicatorInsets = contentInsets var aRect : CGRect = self.view.frame aRect.size.height -= keyboardSize!.height if let activeField = self.activeField { if (!aRect.contains(activeField.frame.origin)){ self.scrollView.scrollRectToVisible(activeField.frame, animated: true) } } } func keyboardWillBeHidden(notification: NSNotification){ //Once keyboard disappears, restore original positions var info = notification.userInfo! let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0) self.scrollView.contentInset = contentInsets self.scrollView.scrollIndicatorInsets = contentInsets self.view.endEditing(true) self.scrollView.isScrollEnabled = false } func textFieldDidBeginEditing(_ textField: UITextField){ activeField = textField } func textFieldDidEndEditing(_ textField: UITextField){ activeField = nil } func textFieldShouldReturn(_ textField: UITextField) -> Bool { // Try to find next responder if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField { nextField.becomeFirstResponder() } else { // Not found, so remove keyboard. textField.resignFirstResponder() } // Do not add a line break return false } }
6753d0b35bd381497acc853ba6d6210b
37.901408
175
0.642288
false
false
false
false
MakeAWishFoundation/SwiftyMocky
refs/heads/master
SwiftyMocky-Tests/tvOS/Mocks/ItemsRepositoryMock.swift
mit
1
// // ItemsRepositoryMock.swift // Mocky // // Created by przemyslaw.wosko on 19/05/2017. // Copyright © 2017 MakeAWishFoundation. All rights reserved. // import Foundation import SwiftyMocky import XCTest @testable import Mocky_Example_tvOS // sourcery: mock = "ItemsRepository" class ItemsRepositoryMock: ItemsRepository, Mock { // sourcery:inline:auto:ItemsRepositoryMock.autoMocked var matcher: Matcher = Matcher.default var stubbingPolicy: StubbingPolicy = .wrap var sequencingPolicy: SequencingPolicy = .lastWrittenResolvedFirst private var queue = DispatchQueue(label: "com.swiftymocky.invocations", qos: .userInteractive) private var invocations: [MethodType] = [] private var methodReturnValues: [Given] = [] private var methodPerformValues: [Perform] = [] private var file: StaticString? private var line: UInt? public typealias PropertyStub = Given public typealias MethodStub = Given public typealias SubscriptStub = Given /// Convenience method - call setupMock() to extend debug information when failure occurs public func setupMock(file: StaticString = #file, line: UInt = #line) { self.file = file self.line = line } /// Clear mock internals. You can specify what to reset (invocations aka verify, givens or performs) or leave it empty to clear all mock internals public func resetMock(_ scopes: MockScope...) { let scopes: [MockScope] = scopes.isEmpty ? [.invocation, .given, .perform] : scopes if scopes.contains(.invocation) { invocations = [] } if scopes.contains(.given) { methodReturnValues = [] } if scopes.contains(.perform) { methodPerformValues = [] } } open func storeItems(items: [Item]) { addInvocation(.m_storeItems__items_items(Parameter<[Item]>.value(`items`))) let perform = methodPerformValue(.m_storeItems__items_items(Parameter<[Item]>.value(`items`))) as? ([Item]) -> Void perform?(`items`) } open func storeDetails(details: ItemDetails) { addInvocation(.m_storeDetails__details_details(Parameter<ItemDetails>.value(`details`))) let perform = methodPerformValue(.m_storeDetails__details_details(Parameter<ItemDetails>.value(`details`))) as? (ItemDetails) -> Void perform?(`details`) } open func storedItems() -> [Item]? { addInvocation(.m_storedItems) let perform = methodPerformValue(.m_storedItems) as? () -> Void perform?() var __value: [Item]? = nil do { __value = try methodReturnValue(.m_storedItems).casted() } catch { // do nothing } return __value } open func storedDetails(item: Item) -> ItemDetails? { addInvocation(.m_storedDetails__item_item(Parameter<Item>.value(`item`))) let perform = methodPerformValue(.m_storedDetails__item_item(Parameter<Item>.value(`item`))) as? (Item) -> Void perform?(`item`) var __value: ItemDetails? = nil do { __value = try methodReturnValue(.m_storedDetails__item_item(Parameter<Item>.value(`item`))).casted() } catch { // do nothing } return __value } fileprivate enum MethodType { case m_storeItems__items_items(Parameter<[Item]>) case m_storeDetails__details_details(Parameter<ItemDetails>) case m_storedItems case m_storedDetails__item_item(Parameter<Item>) static func compareParameters(lhs: MethodType, rhs: MethodType, matcher: Matcher) -> Matcher.ComparisonResult { switch (lhs, rhs) { case (.m_storeItems__items_items(let lhsItems), .m_storeItems__items_items(let rhsItems)): var results: [Matcher.ParameterComparisonResult] = [] results.append(Matcher.ParameterComparisonResult(Parameter.compare(lhs: lhsItems, rhs: rhsItems, with: matcher), lhsItems, rhsItems, "items")) return Matcher.ComparisonResult(results) case (.m_storeDetails__details_details(let lhsDetails), .m_storeDetails__details_details(let rhsDetails)): var results: [Matcher.ParameterComparisonResult] = [] results.append(Matcher.ParameterComparisonResult(Parameter.compare(lhs: lhsDetails, rhs: rhsDetails, with: matcher), lhsDetails, rhsDetails, "details")) return Matcher.ComparisonResult(results) case (.m_storedItems, .m_storedItems): return .match case (.m_storedDetails__item_item(let lhsItem), .m_storedDetails__item_item(let rhsItem)): var results: [Matcher.ParameterComparisonResult] = [] results.append(Matcher.ParameterComparisonResult(Parameter.compare(lhs: lhsItem, rhs: rhsItem, with: matcher), lhsItem, rhsItem, "item")) return Matcher.ComparisonResult(results) default: return .none } } func intValue() -> Int { switch self { case let .m_storeItems__items_items(p0): return p0.intValue case let .m_storeDetails__details_details(p0): return p0.intValue case .m_storedItems: return 0 case let .m_storedDetails__item_item(p0): return p0.intValue } } func assertionName() -> String { switch self { case .m_storeItems__items_items: return ".storeItems(items:)" case .m_storeDetails__details_details: return ".storeDetails(details:)" case .m_storedItems: return ".storedItems()" case .m_storedDetails__item_item: return ".storedDetails(item:)" } } } open class Given: StubbedMethod { fileprivate var method: MethodType private init(method: MethodType, products: [StubProduct]) { self.method = method super.init(products) } public static func storedItems(willReturn: [Item]?...) -> MethodStub { return Given(method: .m_storedItems, products: willReturn.map({ StubProduct.return($0 as Any) })) } public static func storedDetails(item: Parameter<Item>, willReturn: ItemDetails?...) -> MethodStub { return Given(method: .m_storedDetails__item_item(`item`), products: willReturn.map({ StubProduct.return($0 as Any) })) } public static func storedItems(willProduce: (Stubber<[Item]?>) -> Void) -> MethodStub { let willReturn: [[Item]?] = [] let given: Given = { return Given(method: .m_storedItems, products: willReturn.map({ StubProduct.return($0 as Any) })) }() let stubber = given.stub(for: ([Item]?).self) willProduce(stubber) return given } public static func storedDetails(item: Parameter<Item>, willProduce: (Stubber<ItemDetails?>) -> Void) -> MethodStub { let willReturn: [ItemDetails?] = [] let given: Given = { return Given(method: .m_storedDetails__item_item(`item`), products: willReturn.map({ StubProduct.return($0 as Any) })) }() let stubber = given.stub(for: (ItemDetails?).self) willProduce(stubber) return given } } public struct Verify { fileprivate var method: MethodType public static func storeItems(items: Parameter<[Item]>) -> Verify { return Verify(method: .m_storeItems__items_items(`items`))} public static func storeDetails(details: Parameter<ItemDetails>) -> Verify { return Verify(method: .m_storeDetails__details_details(`details`))} public static func storedItems() -> Verify { return Verify(method: .m_storedItems)} public static func storedDetails(item: Parameter<Item>) -> Verify { return Verify(method: .m_storedDetails__item_item(`item`))} } public struct Perform { fileprivate var method: MethodType var performs: Any public static func storeItems(items: Parameter<[Item]>, perform: @escaping ([Item]) -> Void) -> Perform { return Perform(method: .m_storeItems__items_items(`items`), performs: perform) } public static func storeDetails(details: Parameter<ItemDetails>, perform: @escaping (ItemDetails) -> Void) -> Perform { return Perform(method: .m_storeDetails__details_details(`details`), performs: perform) } public static func storedItems(perform: @escaping () -> Void) -> Perform { return Perform(method: .m_storedItems, performs: perform) } public static func storedDetails(item: Parameter<Item>, perform: @escaping (Item) -> Void) -> Perform { return Perform(method: .m_storedDetails__item_item(`item`), performs: perform) } } public func given(_ method: Given) { methodReturnValues.append(method) } public func perform(_ method: Perform) { methodPerformValues.append(method) methodPerformValues.sort { $0.method.intValue() < $1.method.intValue() } } public func verify(_ method: Verify, count: Count = Count.moreOrEqual(to: 1), file: StaticString = #file, line: UInt = #line) { let fullMatches = matchingCalls(method, file: file, line: line) let success = count.matches(fullMatches) let assertionName = method.method.assertionName() let feedback: String = { guard !success else { return "" } return Utils.closestCallsMessage( for: self.invocations.map { invocation in matcher.set(file: file, line: line) defer { matcher.clearFileAndLine() } return MethodType.compareParameters(lhs: invocation, rhs: method.method, matcher: matcher) }, name: assertionName ) }() MockyAssert(success, "Expected: \(count) invocations of `\(assertionName)`, but was: \(fullMatches).\(feedback)", file: file, line: line) } private func addInvocation(_ call: MethodType) { self.queue.sync { invocations.append(call) } } private func methodReturnValue(_ method: MethodType) throws -> StubProduct { matcher.set(file: self.file, line: self.line) defer { matcher.clearFileAndLine() } let candidates = sequencingPolicy.sorted(methodReturnValues, by: { $0.method.intValue() > $1.method.intValue() }) let matched = candidates.first(where: { $0.isValid && MethodType.compareParameters(lhs: $0.method, rhs: method, matcher: matcher).isFullMatch }) guard let product = matched?.getProduct(policy: self.stubbingPolicy) else { throw MockError.notStubed } return product } private func methodPerformValue(_ method: MethodType) -> Any? { matcher.set(file: self.file, line: self.line) defer { matcher.clearFileAndLine() } let matched = methodPerformValues.reversed().first { MethodType.compareParameters(lhs: $0.method, rhs: method, matcher: matcher).isFullMatch } return matched?.performs } private func matchingCalls(_ method: MethodType, file: StaticString?, line: UInt?) -> [MethodType] { matcher.set(file: file ?? self.file, line: line ?? self.line) defer { matcher.clearFileAndLine() } return invocations.filter { MethodType.compareParameters(lhs: $0, rhs: method, matcher: matcher).isFullMatch } } private func matchingCalls(_ method: Verify, file: StaticString?, line: UInt?) -> Int { return matchingCalls(method.method, file: file, line: line).count } private func givenGetterValue<T>(_ method: MethodType, _ message: String) -> T { do { return try methodReturnValue(method).casted() } catch { onFatalFailure(message) Failure(message) } } private func optionalGivenGetterValue<T>(_ method: MethodType, _ message: String) -> T? { do { return try methodReturnValue(method).casted() } catch { return nil } } private func onFatalFailure(_ message: String) { guard let file = self.file, let line = self.line else { return } // Let if fail if cannot handle gratefully SwiftyMockyTestObserver.handleFatalError(message: message, file: file, line: line) } // sourcery:end }
1f935c6baccc3230591f5cc6ab87aabb
43.955056
156
0.65442
false
false
false
false
easytargetmixel/micopi_ios
refs/heads/master
micopi/UI/ViewController/MenuTableViewController.swift
gpl-3.0
1
import UIKit class MenuTableViewController: UITableViewController { fileprivate static let toImagePreviewSegue = "MenuToImagePreviewSegue" fileprivate static let toBatchGeneratorSegue = "MenuToBatchGeneratorSegue" fileprivate static let contactPickerCellIdentifier = "ContactPickerCell" var contactPickerWrapper: ContactPickerWrapper = ContactPickerWrapper() override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let imagePreviewViewController = segue.destination as? ImagePreviewViewController { let contactWrapper = sender as! ContactHashWrapper imagePreviewViewController.contactWrapper = contactWrapper } else if let batchGeneratorViewController = segue.destination as? BatchGeneratorViewController { let contactWrappers = sender as! [ContactHashWrapper] batchGeneratorViewController.contactWrappers = contactWrappers } } // MARK: - UITableViewDelegate override func tableView( _ tableView: UITableView, didSelectRowAt indexPath: IndexPath ) { showContactPickerViewController() } // MARK: - Implementations fileprivate func showContactPickerViewController() { contactPickerWrapper.delegate = self contactPickerWrapper.showContactPicker(sourceViewController: self) } fileprivate func showImagePreviewViewController( contactWrapper: ContactHashWrapper ) { performSegue( withIdentifier: MenuTableViewController.toImagePreviewSegue, sender: contactWrapper ) } fileprivate func showBatchGeneratorViewController( contactWrappers: [ContactHashWrapper] ) { performSegue( withIdentifier: MenuTableViewController.toBatchGeneratorSegue, sender: contactWrappers ) } } // MARK: - ContactPickerWrapperDelegate extension MenuTableViewController: ContactPickerWrapperDelegate { func contactPickerWrapperDidCancel(_ pickerWrapper: ContactPickerWrapper) { } func contactPickerWrapper( _ pickerWrapper: ContactPickerWrapper, didSelect contactWrapper: ContactHashWrapper ) { showImagePreviewViewController(contactWrapper: contactWrapper) } func contactPickerWrapper( _ pickerWrapper: ContactPickerWrapper, didSelect contactWrappers: [ContactHashWrapper] ) { showBatchGeneratorViewController(contactWrappers: contactWrappers) } }
da4709819106fbfa7d3a5e6f1da7b1b9
30.190476
79
0.695038
false
false
false
false
mercadopago/px-ios
refs/heads/develop
MercadoPagoSDK/MercadoPagoSDK/Models/BusinessResult/PXBusinessResultViewModel+Tracking.swift
mit
1
import Foundation // MARK: Tracking extension PXBusinessResultViewModel { func getFooterPrimaryActionTrackingPath() -> String { let paymentStatus = businessResult.paymentStatus var screenPath = "" if paymentStatus == PXPaymentStatus.APPROVED.rawValue || paymentStatus == PXPaymentStatus.PENDING.rawValue { screenPath = TrackingPaths.Screens.PaymentResult.getSuccessPrimaryActionPath() } else if paymentStatus == PXPaymentStatus.IN_PROCESS.rawValue { screenPath = TrackingPaths.Screens.PaymentResult.getFurtherActionPrimaryActionPath() } else if paymentStatus == PXPaymentStatus.REJECTED.rawValue { screenPath = TrackingPaths.Screens.PaymentResult.getErrorPrimaryActionPath() } return screenPath } func getFooterSecondaryActionTrackingPath() -> String { let paymentStatus = businessResult.paymentStatus var screenPath = "" if paymentStatus == PXPaymentStatus.APPROVED.rawValue || paymentStatus == PXPaymentStatus.PENDING.rawValue { screenPath = TrackingPaths.Screens.PaymentResult.getSuccessSecondaryActionPath() } else if paymentStatus == PXPaymentStatus.IN_PROCESS.rawValue { screenPath = TrackingPaths.Screens.PaymentResult.getFurtherActionSecondaryActionPath() } else if paymentStatus == PXPaymentStatus.REJECTED.rawValue { screenPath = TrackingPaths.Screens.PaymentResult.getErrorSecondaryActionPath() } return screenPath } func getHeaderCloseButtonTrackingPath() -> String { let paymentStatus = businessResult.paymentStatus var screenPath = "" if paymentStatus == PXPaymentStatus.APPROVED.rawValue || paymentStatus == PXPaymentStatus.PENDING.rawValue { screenPath = TrackingPaths.Screens.PaymentResult.getSuccessAbortPath() } else if paymentStatus == PXPaymentStatus.IN_PROCESS.rawValue { screenPath = TrackingPaths.Screens.PaymentResult.getFurtherActionAbortPath() } else if paymentStatus == PXPaymentStatus.REJECTED.rawValue { screenPath = TrackingPaths.Screens.PaymentResult.getErrorAbortPath() } return screenPath } } // MARK: PXCongratsTrackingDataProtocol Implementation extension PXBusinessResultViewModel: PXCongratsTrackingDataProtocol { func hasBottomView() -> Bool { return businessResult.getBottomCustomView() != nil } func hasTopView() -> Bool { return businessResult.getTopCustomView() != nil } func hasImportantView() -> Bool { return businessResult.getImportantCustomView() != nil } func hasExpenseSplitView() -> Bool { return pointsAndDiscounts?.expenseSplit != nil && MLBusinessAppDataService().isMp() ? true : false } func getScoreLevel() -> Int? { return PXNewResultUtil.getDataForPointsView(points: pointsAndDiscounts?.points)?.getRingNumber() } func getDiscountsCount() -> Int { guard let numberOfDiscounts = PXNewResultUtil.getDataForDiscountsView(discounts: pointsAndDiscounts?.discounts)?.getItems().count else { return 0 } return numberOfDiscounts } func getCampaignsIds() -> String? { guard let discounts = PXNewResultUtil.getDataForDiscountsView(discounts: pointsAndDiscounts?.discounts) else { return nil } var campaignsIdsArray: [String] = [] for item in discounts.getItems() { if let id = item.trackIdForItem() { campaignsIdsArray.append(id) } } return campaignsIdsArray.isEmpty ? "" : campaignsIdsArray.joined(separator: ", ") } func getCampaignId() -> String? { guard let campaignId = amountHelper.campaign?.id else { return nil } return "\(campaignId)" } } extension PXBusinessResultViewModel: PXViewModelTrackingDataProtocol { func getPrimaryButtonTrack() -> PXResultTrackingEvents { .didTapButton(initiative: .checkout, status: businessResult.paymentStatus, action: .primaryButton) } func getSecondaryButtonTrack() -> PXResultTrackingEvents { .didTapButton(initiative: .checkout, status: businessResult.paymentStatus, action: .secondaryButton) } func getDebinProperties() -> [String: Any]? { guard let paymentTypeId = amountHelper.getPaymentData().paymentMethod?.paymentTypeId, let paymentTypeIdEnum = PXPaymentTypes(rawValue: paymentTypeId), paymentTypeIdEnum == .BANK_TRANSFER else { return nil } var debinProperties: [String: Any] = [:] debinProperties["bank_name"] = debinBankName debinProperties["external_account_id"] = amountHelper.getPaymentData().transactionInfo?.bankInfo?.accountId return debinProperties } func getCloseButtonTrack() -> PXResultTrackingEvents { return .didTapOnCloseButton(initiative: .checkout, status: businessResult.paymentStatus) } func getTrackingPath() -> PXResultTrackingEvents? { let paymentStatus = businessResult.paymentStatus var screenPath: PXResultTrackingEvents? var properties = getTrackingProperties() if let debinProperties = getDebinProperties() { properties.merge(debinProperties) { current, _ in current } } if paymentStatus == PXPaymentStatus.APPROVED.rawValue { screenPath = .checkoutPaymentApproved(properties) } else if paymentStatus == PXPaymentStatus.IN_PROCESS.rawValue || paymentStatus == PXPaymentStatus.PENDING.rawValue { screenPath = .checkoutPaymentInProcess(properties) } else if paymentStatus == PXPaymentStatus.REJECTED.rawValue { screenPath = .checkoutPaymentRejected(properties) } else { screenPath = .checkoutPaymentUnknown(properties) } return screenPath } func getFlowBehaviourResult() -> PXResultKey { switch businessResult.getBusinessStatus() { case .APPROVED: return .SUCCESS case .REJECTED: return .FAILURE case .PENDING: return .PENDING case .IN_PROGRESS: return .PENDING } } func getTrackingProperties() -> [String: Any] { var properties: [String: Any] = amountHelper.getPaymentData().getPaymentDataForTracking() properties["style"] = "custom" if let paymentId = getPaymentId() { properties["payment_id"] = Int64(paymentId) } properties["payment_status"] = businessResult.paymentStatus properties["payment_status_detail"] = businessResult.paymentStatusDetail properties["has_split_payment"] = amountHelper.isSplitPayment properties["currency_id"] = SiteManager.shared.getCurrency().id properties["discount_coupon_amount"] = amountHelper.getDiscountCouponAmountForTracking() properties = PXCongratsTracking.getProperties(dataProtocol: self, properties: properties) if let rawAmount = amountHelper.getPaymentData().getRawAmount() { properties["total_amount"] = rawAmount.decimalValue } return properties } func getTrackingRemediesProperties(isFromModal: Bool) -> [String: Any] { var properties: [String: Any] = [:] properties["index"] = 0 properties["type"] = businessResult.getPaymentMethodTypeId() properties["payment_status"] = businessResult.paymentStatus properties["payment_status_detail"] = businessResult.getStatusDetail() properties["from"] = isFromModal == true ? "modal" : "view" return properties } func getViewErrorPaymentResult() -> [String: Any] { var properties: [String: Any] = [:] properties["index"] = 0 properties["type"] = businessResult.getPaymentMethodTypeId() properties["payment_status"] = businessResult.paymentStatus properties["payment_status_detail"] = businessResult.getStatusDetail() return properties } func getDidShowRemedyErrorModal() -> [String: Any] { var properties: [String: Any] = [:] properties["index"] = 0 properties["type"] = businessResult.getPaymentMethodTypeId() properties["payment_status"] = businessResult.paymentStatus properties["payment_status_detail"] = businessResult.getStatusDetail() return properties } }
53b269daf6019dbfe7486fa7f600a750
41.756345
155
0.683248
false
false
false
false
jay18001/brickkit-ios
refs/heads/master
Tests/Behaviors/StickyFooterLayoutBehaviorTests.swift
apache-2.0
1
// // StickyFooterLayoutBehaviorTests.swift // BrickKit // // Created by Ruben Cagnie on 6/2/16. // Copyright © 2016 Wayfair LLC. All rights reserved. // import XCTest @testable import BrickKit class StickyFooterLayoutBehaviorTests: BrickFlowLayoutBaseTests { func testStickyBehavior() { let sectionCount = 20 let indexPath = IndexPath(item: sectionCount - 1, section: 0) let behaviorDataSource = FixedStickyLayoutBehaviorDataSource(indexPaths: [indexPath]) let stickyBehavior = StickyFooterLayoutBehavior(dataSource: behaviorDataSource) self.layout.behaviors.insert(stickyBehavior) setDataSources(SectionsCollectionViewDataSource(sections: [sectionCount]), brickLayoutDataSource: FixedBrickLayoutDataSource(widthRatio: 1, height: 100)) var firstAttributes:UICollectionViewLayoutAttributes! firstAttributes = layout.layoutAttributesForItem(at: indexPath) XCTAssertEqual(firstAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 100, width: 320, height: 100)) layout.collectionView?.contentOffset.y = 500 layout.invalidateLayout(with: BrickLayoutInvalidationContext(type: .scrolling)) firstAttributes = layout.layoutAttributesForItem(at: indexPath) XCTAssertEqual(firstAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 100 + 500, width: 320, height: 100)) layout.collectionView?.contentOffset.y = 3000 layout.invalidateLayout(with: BrickLayoutInvalidationContext(type: .scrolling)) firstAttributes = layout.layoutAttributesForItem(at: indexPath) XCTAssertEqual(firstAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 100 + 3000, width: 320, height: 100)) } func testStackedStickyBehavior() { let sectionCount = 20 let indexPath1 = IndexPath(item: sectionCount - 1, section: 0) let indexPath2 = IndexPath(item: sectionCount - 2, section: 0) let behaviorDataSource = FixedStickyLayoutBehaviorDataSource(indexPaths: [indexPath1, indexPath2]) let stickyBehavior = StickyFooterLayoutBehavior(dataSource: behaviorDataSource) self.layout.behaviors.insert(stickyBehavior) setDataSources(SectionsCollectionViewDataSource(sections: [sectionCount]), brickLayoutDataSource: FixedBrickLayoutDataSource(widthRatio: 1, height: 100)) var firstAttributes: UICollectionViewLayoutAttributes! var secondAttributes: UICollectionViewLayoutAttributes! firstAttributes = layout.layoutAttributesForItem(at: indexPath1) XCTAssertEqual(firstAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 100, width: 320, height: 100)) secondAttributes = layout.layoutAttributesForItem(at: indexPath2) XCTAssertEqual(secondAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 200, width: 320, height: 100)) layout.collectionView?.contentOffset.y = 500 layout.invalidateLayout(with: BrickLayoutInvalidationContext(type: .scrolling)) firstAttributes = layout.layoutAttributesForItem(at: indexPath1) XCTAssertEqual(firstAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 100 + 500, width: 320, height: 100)) secondAttributes = layout.layoutAttributesForItem(at: indexPath2) XCTAssertEqual(secondAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 100 + 500 - 100, width: 320, height: 100)) layout.collectionView?.contentOffset.y = 3000 layout.invalidateLayout(with: BrickLayoutInvalidationContext(type: .scrolling)) firstAttributes = layout.layoutAttributesForItem(at: indexPath1) XCTAssertEqual(firstAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 100 + 3000, width: 320, height: 100)) secondAttributes = layout.layoutAttributesForItem(at: indexPath2) XCTAssertEqual(secondAttributes?.frame, CGRect(x: 0, y: (sectionCount - 2) * 100, width: 320, height: 100)) } func testStickyBehaviorContentInset() { let sectionCount = 20 self.collectionView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 20, right: 0) let indexPath = IndexPath(item: sectionCount - 1, section: 0) let behaviorDataSource = FixedStickyLayoutBehaviorDataSource(indexPaths: [indexPath]) let stickyBehavior = StickyFooterLayoutBehavior(dataSource: behaviorDataSource) self.layout.behaviors.insert(stickyBehavior) setDataSources(SectionsCollectionViewDataSource(sections: [sectionCount]), brickLayoutDataSource: FixedBrickLayoutDataSource(widthRatio: 1, height: 100)) var firstAttributes:UICollectionViewLayoutAttributes! firstAttributes = layout.layoutAttributesForItem(at: indexPath) XCTAssertEqual(firstAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 100 - 40, width: 320, height: 100)) layout.collectionView?.contentOffset.y = 500 layout.invalidateLayout(with: BrickLayoutInvalidationContext(type: .scrolling)) firstAttributes = layout.layoutAttributesForItem(at: indexPath) XCTAssertEqual(firstAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 100 + 500 - 20, width: 320, height: 100)) layout.collectionView?.contentOffset.y = 3000 layout.invalidateLayout(with: BrickLayoutInvalidationContext(type: .scrolling)) firstAttributes = layout.layoutAttributesForItem(at: indexPath) XCTAssertEqual(firstAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 100 + 3000 - 20, width: 320, height: 100)) } func testSectionStickyBehavior() { let firstIndexPath = IndexPath(item: 1, section: 2) let secondIndexPath = IndexPath(item: 1, section: 3) let behaviorDataSource = FixedStickyLayoutBehaviorDataSource(indexPaths: [firstIndexPath, secondIndexPath]) let stickyBehavior = StickyFooterLayoutBehavior(dataSource: behaviorDataSource) self.layout.behaviors.insert(stickyBehavior) setDataSources(SectionsCollectionViewDataSource(sections: [1, 2, 2, 2]), brickLayoutDataSource: SectionsLayoutDataSource(widthRatios: [[1], [1, 1], [1, 1], [1, 1]], heights: [[0], [0, 0], [1000, 100], [1000, 100]], types: [[.section(sectionIndex: 1)], [.section(sectionIndex: 2), .section(sectionIndex: 3)], [.brick, .brick], [.brick, .brick]])) var firstSectionAttributes: UICollectionViewLayoutAttributes! var secondSectionAttributes: UICollectionViewLayoutAttributes! firstSectionAttributes = layout.layoutAttributesForItem(at: firstIndexPath) XCTAssertEqual(firstSectionAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 100, width: 320, height: 100)) secondSectionAttributes = layout.layoutAttributesForItem(at: secondIndexPath) XCTAssertEqual(secondSectionAttributes?.frame, CGRect(x: 0, y: 1100, width: 320, height: 100)) layout.collectionView?.contentOffset.y = 500 layout.invalidateLayout(with: BrickLayoutInvalidationContext(type: .scrolling)) firstSectionAttributes = layout.layoutAttributesForItem(at: firstIndexPath) XCTAssertEqual(firstSectionAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 100 + 500, width: 320, height: 100)) secondSectionAttributes = layout.layoutAttributesForItem(at: secondIndexPath) XCTAssertEqual(secondSectionAttributes?.frame, CGRect(x: 0, y: 1100, width: 320, height: 100)) layout.collectionView?.contentOffset.y = 1100 layout.invalidateLayout(with: BrickLayoutInvalidationContext(type: .scrolling)) firstSectionAttributes = layout.layoutAttributesForItem(at: firstIndexPath) XCTAssertEqual(firstSectionAttributes?.frame, CGRect(x: 0, y: 1000, width: 320, height: 100)) secondSectionAttributes = layout.layoutAttributesForItem(at: secondIndexPath) XCTAssertEqual(secondSectionAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 100 + 1100, width: 320, height: 100)) layout.collectionView?.contentOffset.y = 1600 layout.invalidateLayout(with: BrickLayoutInvalidationContext(type: .scrolling)) firstSectionAttributes = layout.layoutAttributesForItem(at: firstIndexPath) XCTAssertEqual(firstSectionAttributes?.frame, CGRect(x: 0, y: 1000, width: 320, height: 100)) secondSectionAttributes = layout.layoutAttributesForItem(at: secondIndexPath) XCTAssertEqual(secondSectionAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 100 + 1600, width: 320, height: 100)) } func testSectionStickyBehaviorCanStackWithOtherSections() { let sectionCount = 20 let indexPath1 = IndexPath(item: 1, section: 1) let indexPath2 = IndexPath(item: sectionCount - 1, section: 2) let behaviorDataSource = FixedStickyLayoutBehaviorDataSource(indexPaths: [indexPath1, indexPath2]) let stickyBehavior = StickyFooterLayoutBehavior(dataSource: behaviorDataSource) stickyBehavior.canStackWithOtherSections = true self.layout.behaviors.insert(stickyBehavior) setDataSources(SectionsCollectionViewDataSource(sections: [1, 2, sectionCount]), brickLayoutDataSource: SectionsLayoutDataSource(widthRatios: [[1], [1, 1], [1]], heights: [[0], [0, 100], [100]], types: [[.section(sectionIndex: 1)], [.section(sectionIndex: 2), .brick], [.brick]])) var firstAttributes: UICollectionViewLayoutAttributes! var secondAttributes: UICollectionViewLayoutAttributes! firstAttributes = layout.layoutAttributesForItem(at: indexPath1) XCTAssertEqual(firstAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 100, width: 320, height: 100)) secondAttributes = layout.layoutAttributesForItem(at: indexPath2) XCTAssertEqual(secondAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 200, width: 320, height: 100)) layout.collectionView?.contentOffset.y = 500 layout.invalidateLayout(with: BrickLayoutInvalidationContext(type: .scrolling)) firstAttributes = layout.layoutAttributesForItem(at: indexPath1) XCTAssertEqual(firstAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 100 + 500, width: 320, height: 100)) secondAttributes = layout.layoutAttributesForItem(at: indexPath2) XCTAssertEqual(secondAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 100 + 500 - 100, width: 320, height: 100)) layout.collectionView?.contentOffset.y = 3000 layout.invalidateLayout(with: BrickLayoutInvalidationContext(type: .scrolling)) firstAttributes = layout.layoutAttributesForItem(at: indexPath1) XCTAssertEqual(firstAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 100 + 3000, width: 320, height: 100)) secondAttributes = layout.layoutAttributesForItem(at: indexPath2) XCTAssertEqual(secondAttributes?.frame, CGRect(x: 0, y: ((sectionCount - 2) * 100) + 100, width: 320, height: 100)) } func testSectionWithinSectionsStickyBehavior() { let sectionIndexPath = IndexPath(item: 1, section: 1) let firstIndexPath = IndexPath(item: 0, section: 2) let secondIndexPath = IndexPath(item: 1, section: 2) let behaviorDataSource = FixedStickyLayoutBehaviorDataSource(indexPaths: [sectionIndexPath]) let stickyBehavior = StickyFooterLayoutBehavior(dataSource: behaviorDataSource) self.layout.behaviors.insert(stickyBehavior) setDataSources(SectionsCollectionViewDataSource(sections: [1, 2, 2]), brickLayoutDataSource: SectionsLayoutDataSource(widthRatios: [[1], [1, 1], [1, 1]], heights: [[0], [1000, 0], [100, 100]], types: [[.section(sectionIndex: 1)], [.brick, .section(sectionIndex: 2)], [.brick, .brick]])) var sectionAttributes: UICollectionViewLayoutAttributes! var firstSectionAttributes: UICollectionViewLayoutAttributes! var secondSectionAttributes: UICollectionViewLayoutAttributes! sectionAttributes = layout.layoutAttributesForItem(at: sectionIndexPath) XCTAssertEqual(sectionAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 200, width: 320, height: 200)) firstSectionAttributes = layout.layoutAttributesForItem(at: firstIndexPath) XCTAssertEqual(firstSectionAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 200, width: 320, height: 100)) secondSectionAttributes = layout.layoutAttributesForItem(at: secondIndexPath) XCTAssertEqual(secondSectionAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 100, width: 320, height: 100)) layout.collectionView?.contentOffset.y = 500 layout.invalidateLayout(with: BrickLayoutInvalidationContext(type: .scrolling)) sectionAttributes = layout.layoutAttributesForItem(at: sectionIndexPath) XCTAssertEqual(sectionAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 200 + 500, width: 320, height: 200)) firstSectionAttributes = layout.layoutAttributesForItem(at: firstIndexPath) XCTAssertEqual(firstSectionAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 200 + 500, width: 320, height: 100)) secondSectionAttributes = layout.layoutAttributesForItem(at: secondIndexPath) XCTAssertEqual(secondSectionAttributes?.frame, CGRect(x: 0, y: collectionViewFrame.height - 100 + 500, width: 320, height: 100)) } func testThatFooterSectionDoesNotGrowTooLarge() { collectionView.layout.zIndexBehavior = .bottomUp collectionView.registerBrickClass(LabelBrick.self) let stickyDataSource = FixedStickyLayoutBehaviorDataSource(indexPaths: [IndexPath(item: 50, section: 1)]) let behavior = StickyFooterLayoutBehavior(dataSource: stickyDataSource) collectionView.layout.behaviors.insert(behavior) let configureCellBlock: ConfigureLabelBlock = { cell in cell.edgeInsets.top = 10 cell.edgeInsets.bottom = 11 } let footerSection = BrickSection("Footer", bricks: [ LabelBrick("A", text: "Footer Title", configureCellBlock: configureCellBlock), LabelBrick("B", width: .ratio(ratio: 0.5), text: "Footer Label 1", configureCellBlock: configureCellBlock), LabelBrick("C", width: .ratio(ratio: 0.5), text: "Footer Label 2", configureCellBlock: configureCellBlock), ]) let section = BrickSection(bricks: [ LabelBrick("BRICK", width: .ratio(ratio: 0.5), height: .fixed(size: 38), text: "Brick"), footerSection ]) let repeatCountDataSource = FixedRepeatCountDataSource(repeatCountHash: ["BRICK" : 50]) section.repeatCountDataSource = repeatCountDataSource collectionView.setSection(section) collectionView.layoutSubviews() let attributes = collectionView.collectionViewLayout.layoutAttributesForItem(at: IndexPath(item: 50, section: 1)) XCTAssertEqual(attributes?.frame, CGRect(x: 0, y: 404, width: 320, height: 76)) let footerAttributes1 = collectionView.collectionViewLayout.layoutAttributesForItem(at: IndexPath(item: 0, section: 2)) XCTAssertEqual(footerAttributes1?.frame, CGRect(x: 0, y: 404, width: 320, height: 38)) let footerAttributes2 = collectionView.collectionViewLayout.layoutAttributesForItem(at: IndexPath(item: 1, section: 2)) XCTAssertEqual(footerAttributes2?.frame, CGRect(x: 0, y: 442, width: 160, height: 38)) let footerAttributes3 = collectionView.collectionViewLayout.layoutAttributesForItem(at: IndexPath(item: 2, section: 2)) XCTAssertEqual(footerAttributes3?.frame, CGRect(x: 160, y: 442, width: 160, height: 38)) } }
f617e8f1cec030b5b57187e1153ae3c9
58.357143
353
0.729812
false
false
false
false
madbat/Surge
refs/heads/master
Source/Trigonometric.swift
mit
2
// Trigonometric.swift // // Copyright (c) 2014–2015 Mattt Thompson (http://mattt.me) // // 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 Accelerate // MARK: Sine-Cosine public func sincos(x: [Float]) -> (sin: [Float], cos: [Float]) { var sin = [Float](count: x.count, repeatedValue: 0.0) var cos = [Float](count: x.count, repeatedValue: 0.0) vvsincosf(&sin, &cos, x, [Int32(x.count)]) return (sin, cos) } public func sincos(x: [Double]) -> (sin: [Double], cos: [Double]) { var sin = [Double](count: x.count, repeatedValue: 0.0) var cos = [Double](count: x.count, repeatedValue: 0.0) vvsincos(&sin, &cos, x, [Int32(x.count)]) return (sin, cos) } // MARK: Sine public func sin(x: [Float]) -> [Float] { var results = [Float](count: x.count, repeatedValue: 0.0) vvsinf(&results, x, [Int32(x.count)]) return results } public func sin(x: [Double]) -> [Double] { var results = [Double](count: x.count, repeatedValue: 0.0) vvsin(&results, x, [Int32(x.count)]) return results } // MARK: Cosine public func cos(x: [Float]) -> [Float] { var results = [Float](count: x.count, repeatedValue: 0.0) vvcosf(&results, x, [Int32(x.count)]) return results } public func cos(x: [Double]) -> [Double] { var results = [Double](count: x.count, repeatedValue: 0.0) vvcos(&results, x, [Int32(x.count)]) return results } // MARK: Tangent public func tan(x: [Float]) -> [Float] { var results = [Float](count: x.count, repeatedValue: 0.0) vvtanf(&results, x, [Int32(x.count)]) return results } public func tan(x: [Double]) -> [Double] { var results = [Double](count: x.count, repeatedValue: 0.0) vvtan(&results, x, [Int32(x.count)]) return results } // MARK: Arcsine public func asin(x: [Float]) -> [Float] { var results = [Float](count: x.count, repeatedValue: 0.0) vvasinf(&results, x, [Int32(x.count)]) return results } public func asin(x: [Double]) -> [Double] { var results = [Double](count: x.count, repeatedValue: 0.0) vvasin(&results, x, [Int32(x.count)]) return results } // MARK: Arccosine public func acos(x: [Float]) -> [Float] { var results = [Float](count: x.count, repeatedValue: 0.0) vvacosf(&results, x, [Int32(x.count)]) return results } public func acos(x: [Double]) -> [Double] { var results = [Double](count: x.count, repeatedValue: 0.0) vvacos(&results, x, [Int32(x.count)]) return results } // MARK: Arctangent public func atan(x: [Float]) -> [Float] { var results = [Float](count: x.count, repeatedValue: 0.0) vvatanf(&results, x, [Int32(x.count)]) return results } public func atan(x: [Double]) -> [Double] { var results = [Double](count: x.count, repeatedValue: 0.0) vvatan(&results, x, [Int32(x.count)]) return results } // MARK: - // MARK: Radians to Degrees func rad2deg(x: [Float]) -> [Float] { var results = [Float](count: x.count, repeatedValue: 0.0) let divisor = [Float](count: x.count, repeatedValue: Float(M_PI / 180.0)) vvdivf(&results, x, divisor, [Int32(x.count)]) return results } func rad2deg(x: [Double]) -> [Double] { var results = [Double](count: x.count, repeatedValue: 0.0) let divisor = [Double](count: x.count, repeatedValue: M_PI / 180.0) vvdiv(&results, x, divisor, [Int32(x.count)]) return results } // MARK: Degrees to Radians func deg2rad(x: [Float]) -> [Float] { var results = [Float](count: x.count, repeatedValue: 0.0) let divisor = [Float](count: x.count, repeatedValue: Float(180.0 / M_PI)) vvdivf(&results, x, divisor, [Int32(x.count)]) return results } func deg2rad(x: [Double]) -> [Double] { var results = [Double](count: x.count, repeatedValue: 0.0) let divisor = [Double](count: x.count, repeatedValue: 180.0 / M_PI) vvdiv(&results, x, divisor, [Int32(x.count)]) return results }
4c034b8cf8c2d0ff5903766d2da812e0
27.188571
80
0.65376
false
false
false
false
Red-Analyzer/red-analyzer
refs/heads/master
red-analyzer/ChartsTableViewController.swift
mit
1
// // ChartsTableViewController.swift // red-analyzer // // Created by Arvind Jagesser on 31/10/15. // Copyright © 2015 Arvind Jagesser. All rights reserved. // import UIKit import Charts import ChameleonFramework class MockChartData { let name: String let xVals: [String] let yVals: [Int] init(name: String, xVals: [String], yVals: [Int]) { self.name = name self.xVals = xVals self.yVals = yVals } func pieChart() -> PieChartData { let pyVals = processYVals() var dataSet : [ChartDataSet] = [] let dataPie = PieChartDataSet(yVals: pyVals, label: "") dataPie.sliceSpace = 2.0 dataPie.colors = [FlatRed(), FlatOrange(), FlatYellow(), FlatGreen(), FlatBlue(), FlatPurple()] dataSet.append(dataPie) let pieChartData = PieChartData(xVals: xVals, dataSets: dataSet) let pFormatter: NSNumberFormatter = NSNumberFormatter() pFormatter.numberStyle = NSNumberFormatterStyle.PercentStyle pFormatter.maximumFractionDigits = 1 pFormatter.multiplier = 1.0 pFormatter.percentSymbol = "%" pieChartData.setValueFormatter(pFormatter) pieChartData.setValueTextColor(UIColor.blackColor()) return pieChartData } private func processYVals() -> [ChartDataEntry] { var pyVals: [ChartDataEntry] = [] for i in 0 ..< xVals.count { pyVals.append(ChartDataEntry.init(value: Double(self.yVals[i]), xIndex: i)) } return pyVals } } class ChartsTableViewController: UITableViewController { let data = [MockChartData(name: "Access to Water", xVals: ["<1km", "<2km", "<5km", "+5km"], yVals: [25, 35, 10, 30]), MockChartData(name: "Clean Water Education", xVals: ["Yes", "No"], yVals: [65, 35]), MockChartData(name: "Making Water Safe", xVals: ["Boil", "Cloth", "Solar", "Chlorine", "Settle", "Other"], yVals: [16, 16, 16, 16, 16, 20])] override func viewDidLoad() { super.viewDidLoad() super.view.backgroundColor = UIColor(red: (81/255.0), green: (166/255.0), blue: (220/255.0), alpha: 1) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifierLabel", forIndexPath: indexPath) let dataChart = self.data[indexPath.row] let chartView: PieChartView = cell.contentView.viewWithTag(99) as! PieChartView let titleView: UILabel = cell.contentView.viewWithTag(98) as! UILabel titleView.text = dataChart.name chartView.usePercentValuesEnabled = true chartView.holeTransparent = true chartView.holeRadiusPercent = 0.4 chartView.transparentCircleRadiusPercent = 0.4 chartView.descriptionText = "" chartView.rotationAngle = 0.0 chartView.data = dataChart.pieChart() chartView.highlightValues(nil) chartView.drawSliceTextEnabled = false return cell } }
432ef5c22c0cfd896ac44f8b1910d484
32.25
148
0.63234
false
false
false
false
respan/ChainableSwift
refs/heads/master
ChainableSwift/Classes/CALayerExtensions.swift
mit
1
// // CALayerExtensions.swift // Pods // // Created by Denis Sushko on 17.04.16. // // public extension CALayer { /// ChainableSwift @discardableResult final func bounds(_ bounds: CGRect) -> Self { self.bounds = bounds return self } /// ChainableSwift @discardableResult final func position(_ position: CGPoint) -> Self { self.position = position return self } /// ChainableSwift @discardableResult final func zPosition(_ zPosition: CGFloat) -> Self { self.zPosition = zPosition return self } /// ChainableSwift @discardableResult final func anchorPoint(_ anchorPoint: CGPoint) -> Self { self.anchorPoint = anchorPoint return self } /// ChainableSwift @discardableResult final func anchorPointZ(_ anchorPointZ: CGFloat) -> Self { self.anchorPointZ = anchorPointZ return self } /// ChainableSwift @discardableResult final func transform(_ transform: CATransform3D) -> Self { self.transform = transform return self } /// ChainableSwift @discardableResult final func frame(_ frame: CGRect) -> Self { self.frame = frame return self } /// ChainableSwift @discardableResult final func hidden(_ hidden: Bool) -> Self { self.isHidden = hidden return self } /// ChainableSwift @discardableResult final func doubleSided(_ doubleSided: Bool) -> Self { self.isDoubleSided = doubleSided return self } /// ChainableSwift @discardableResult final func geometryFlipped(_ geometryFlipped: Bool) -> Self { self.isGeometryFlipped = geometryFlipped return self } /// ChainableSwift @discardableResult final func mask(_ mask: CALayer?) -> Self { self.mask = mask return self } /// ChainableSwift @discardableResult final func masksToBounds(_ masksToBounds: Bool) -> Self { self.masksToBounds = masksToBounds return self } /// ChainableSwift @discardableResult final func opaque(_ opaque: Bool) -> Self { self.isOpaque = opaque return self } /// ChainableSwift @discardableResult final func allowsEdgeAntialiasing(_ allowsEdgeAntialiasing: Bool) -> Self { self.allowsEdgeAntialiasing = allowsEdgeAntialiasing return self } /// ChainableSwift @discardableResult final func backgroundColor(_ backgroundColor: CGColor?) -> Self { self.backgroundColor = backgroundColor return self } /// ChainableSwift @discardableResult final func cornerRadius(_ cornerRadius: CGFloat) -> Self { self.cornerRadius = cornerRadius return self } /// ChainableSwift @discardableResult final func borderWidth(_ borderWidth: CGFloat) -> Self { self.borderWidth = borderWidth return self } /// ChainableSwift @discardableResult final func borderColor(_ borderColor: CGColor?) -> Self { self.borderColor = borderColor return self } /// ChainableSwift @discardableResult final func opacity(_ opacity: Float) -> Self { self.opacity = opacity return self } /// ChainableSwift @discardableResult final func allowsGroupOpacity(_ allowsGroupOpacity: Bool) -> Self { self.allowsGroupOpacity = allowsGroupOpacity return self } /// ChainableSwift @discardableResult final func compositingFilter(_ compositingFilter: Any?) -> Self { self.compositingFilter = compositingFilter return self } /// ChainableSwift @discardableResult final func shouldRasterize(_ shouldRasterize: Bool) -> Self { self.shouldRasterize = shouldRasterize return self } /// ChainableSwift @discardableResult final func rasterizationScale(_ rasterizationScale: CGFloat) -> Self { self.rasterizationScale = rasterizationScale return self } /// ChainableSwift @discardableResult final func shadowColor(_ shadowColor: CGColor?) -> Self { self.shadowColor = shadowColor return self } /// ChainableSwift @discardableResult final func shadowOpacity(_ shadowOpacity: Float) -> Self { self.shadowOpacity = shadowOpacity return self } /// ChainableSwift @discardableResult final func shadowOffset(_ shadowOffset: CGSize) -> Self { self.shadowOffset = shadowOffset return self } /// ChainableSwift @discardableResult final func shadowRadius(_ shadowRadius: CGFloat) -> Self { self.shadowRadius = shadowRadius return self } /// ChainableSwift @discardableResult final func shadowPath(_ shadowPath: CGPath?) -> Self { self.shadowPath = shadowPath return self } }
c4e7e46b7025bdd740a9653a2a305e51
23.209756
98
0.634697
false
false
false
false
mlibai/XZKit
refs/heads/master
XZKit/Code/Networking/XZAPIConcurrency.swift
mit
1
// // APIConcurrency.swift // XZKit // // Created by Xezun on 2018/2/27. // Copyright © 2018年 XEZUN INC. All rights reserved. // import Foundation /// 接口并发。 public enum APIConcurrency { /// 并发策略。 public enum Policy: Equatable { /// 默认并发策略,所有请求之间互不影响。 case `default` /// 当发送新的请求时,先取消目前所有的请求。 /// - Note: 被取消的请求会收到 APIError.canceled 错误。 case cancelOthers /// 发送请求时,如果当前已有请求,那么忽略本次请求。 /// - Note: 如果请求因为策略被忽略,将产生 .ignored 错误,以解决发送了请求却没有着陆点的问题。 case ignoreCurrent /// 当发送新请求时,如果当前有正在进行的请求,则按并发优先级等待执行。 /// 优先级改变不会影响已经列队的请求。 case wait(priority: Priority) } /// API 并发优先级。 public struct Priority: RawRepresentable { public typealias RawValue = Int public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } } } extension APIConcurrency.Policy { /// API 并发优先级。 public var priority: APIConcurrency.Priority { if case let .wait(priority) = self { return priority } return .default } } extension APIConcurrency.Priority { /// 最低优先级 Int.min 。 public static let low = APIConcurrency.Priority.init(rawValue: .min) /// 默认优先级 0 。 public static let `default` = APIConcurrency.Priority.init(rawValue: 0) /// 最高优先级 Int.max 。 public static let high = APIConcurrency.Priority.init(rawValue: .max) } extension APIConcurrency.Priority: ExpressibleByIntegerLiteral, Comparable, CustomStringConvertible { public static func < (lhs: APIConcurrency.Priority, rhs: APIConcurrency.Priority) -> Bool { return lhs.rawValue < rhs.rawValue } public static func <= (lhs: APIConcurrency.Priority, rhs: APIConcurrency.Priority) -> Bool { return lhs.rawValue <= rhs.rawValue } public static func >= (lhs: APIConcurrency.Priority, rhs: APIConcurrency.Priority) -> Bool { return lhs.rawValue >= rhs.rawValue } public static func > (lhs: APIConcurrency.Priority, rhs: APIConcurrency.Priority) -> Bool { return lhs.rawValue > rhs.rawValue } public typealias IntegerLiteralType = Int public init(integerLiteral value: Int) { self.rawValue = value } public var description: String { return rawValue.description } }
9cbc413dffad4ba0879200bbc58dc091
25.615385
101
0.622626
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Banking
refs/heads/master
HatchReadyApp/apps/Hatch/iphone/native/Hatch/Models/Watson/Problem/TradeoffObjectiveDefinition.swift
epl-1.0
1
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ public enum TradeoffType: String { case NUMERIC = "NUMERIC" case TEXT = "TEXT" } public enum TradeoffGoal: String { case MIN = "MIN" case MAX = "MAX" } struct TradeoffValueRange { var low : Int = 0 var hi : Int = 0 } /** This class represents objective of a Watson Problem */ class TradeoffObjectiveDefinition { /// TradeoffGoal - either MIN or MAX var goal : TradeoffGoal /// Whether it is objective var objective : Bool /// Insignificant loss var insignificant_loss : Int? /// Significant gain var significant_gain : Int? /// Significant loss var significant_loss : Int? /// Key for objective var key : String /// Type of objective : NUMERIC or TEXT var type : TradeoffType /// Range of tradeoffvalue var range : TradeoffValueRange? /// Enum values var enum_vals : [String]? /// Format of objective var format : String? /// Full name of Objective var full_name : String? /// Description of Objective var description : String? /** Initializes TradeoffObjectiveDefinition with TradeoffGoal, key, TradeoffType, and objective value (whether it is objective or not) - parameter goal: TradeoffGoal object - parameter key: key string - parameter type: TradeoffType object - parameter objective: whether goal is objective or not (true or false) - returns: <#return value description#> */ init(goal : TradeoffGoal, key : String, type : TradeoffType, objective : Bool) { self.goal = goal self.key = key self.type = type self.objective = objective } /** This method will return a dictionary object of a TradeoffObjectiveDefinition - returns: Dictionary object */ func convertToDictionary() -> [NSObject : AnyObject] { return ["goal" : self.goal.rawValue as String, "key" : self.key, "type" : self.type.rawValue as String, "is_objective" : self.objective] } }
30b9f3a7ac031057b01d378b20e7c55c
22.891304
144
0.622667
false
false
false
false
byu-oit-appdev/ios-byuSuite
refs/heads/dev
byuSuite/Classes/Reusable/UI/Toast/ToastView.swift
apache-2.0
1
// // ToastView.swift // byuSuite // // Created by Erik Brady on 8/14/18. // Copyright © 2018 Brigham Young University. All rights reserved. // //TODO: Implement in Y-Time with the following message: "Your punch was submitted successfully.\nIt may take a few minutes for these changes to reflect in your timesheet." class ToastView: UIView { private struct UI { static let maxWidth: CGFloat = 345 static let widthRatio: CGFloat = 0.9 static let hideHeight: CGFloat = 180 static let verticalMargin: CGFloat = 10 static let dismissDuration = 0.1 static let showDuration = 0.3 static let springDamping: CGFloat = 0.63 static let initialSpringVelocity: CGFloat = 0.1 static let cornerRadius: CGFloat = 5 static let shadowRadius: CGFloat = 5 static let shadowOpacity: Float = 0.25 } enum ToastType { case success case error case info var backgroundColor: UIColor { switch self { case .success: return .byuGreen case .error: return .byuRed default: return .lightGray } } } //MARK: IBOutlets @IBOutlet private weak var messageLabel: UILabel! //MARK: Private Properties private var bottomConstraint: NSLayoutConstraint! private var completion: () -> () = {} required init?(coder aDecoder:NSCoder) { super.init(coder: aDecoder) } static func show(in superView: UIView, message: String, type: ToastType = .success, dismissDelay: TimeInterval = 3.5, completion: @escaping () -> () = {}) { //Inflate from the Nib let toast = UINib(nibName: "ToastView", bundle: nil).instantiate(withOwner: nil).first as! ToastView toast.translatesAutoresizingMaskIntoConstraints = false //Save all internal variables toast.messageLabel.text = message toast.backgroundColor = type.backgroundColor toast.completion = completion toast.setupLayer() toast.setupGestureRecognizers() //Set up Timer Timer.scheduledTimer(timeInterval: dismissDelay, target: toast, selector: #selector(dismissNotification), userInfo: nil, repeats: false) //Add to SuperView superView.addSubview(toast) //Set up Constraints toast.bottomConstraint = toast.bottomAnchor.constraint(equalTo: superView.bottomAnchor, constant: UI.hideHeight) NSLayoutConstraint.activate([ toast.widthAnchor.constraint(equalTo: superView.widthAnchor, multiplier: UI.widthRatio, priority: 999), toast.widthAnchor.constraint(lessThanOrEqualToConstant: UI.maxWidth), toast.centerXAnchor.constraint(equalTo: superView.centerXAnchor), toast.bottomConstraint ]) superView.layoutIfNeeded() //Animate display toast.showNotification() } private func setupLayer() { layer.cornerRadius = UI.cornerRadius layer.shadowRadius = UI.shadowRadius layer.shadowOpacity = UI.shadowOpacity layer.shadowColor = UIColor.lightGray.cgColor } private func setupGestureRecognizers() { let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissNotification)) let swipeRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(self.dismissNotification)) swipeRecognizer.direction = .down addGestureRecognizer(tapRecognizer) addGestureRecognizer(swipeRecognizer) } func showNotification() { bottomConstraint.constant = -UI.verticalMargin UIView.animate(withDuration: UI.showDuration, delay: 0.0, usingSpringWithDamping: UI.springDamping, initialSpringVelocity: UI.initialSpringVelocity, options: UIViewAnimationOptions(), animations: { self.superview?.layoutIfNeeded() }) } @objc func dismissNotification() { bottomConstraint.constant = UI.hideHeight UIView.animate(withDuration: UI.dismissDuration, animations: { self.superview?.layoutIfNeeded() }) { (_) in self.completion() self.removeFromSuperview() } } }
506d46e78a10d98fc75d90149bd33428
30.173554
199
0.746819
false
false
false
false
AlesTsurko/DNMKit
refs/heads/master
DNM_iOS/DNM_iOS/MasterViewController.swift
gpl-2.0
1
// // MasterViewController.swift // DNM_iOS // // Created by James Bean on 11/26/15. // Copyright © 2015 James Bean. All rights reserved. // import UIKit import DNMModel import Parse import Bolts // TODO: manage signed in / signed out: tableview.reloadData public class MasterViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate { // MARK: - UI @IBOutlet weak var scoreSelectorTableView: UITableView! @IBOutlet weak var colorModeLabel: UILabel! @IBOutlet weak var colorModeLightLabel: UILabel! @IBOutlet weak var colorModeDarkLabel: UILabel! @IBOutlet weak var loginStatusLabel: UILabel! @IBOutlet weak var signInOrOutOrUpButton: UIButton! @IBOutlet weak var signInOrUpButton: UIButton! @IBOutlet weak var dnmLogoLabel: UILabel! @IBOutlet weak var usernameField: UITextField! @IBOutlet weak var passwordField: UITextField! // MARK: - Model private var scoreModelSelected: DNMScoreModel? // MARK: - Views // change to PerformerInterfaceView private var viewByID: [String: ScoreView] = [:] private var currentView: ScoreView? // MARK: - Score Object Management private var scoreObjects: [PFObject] = [] private var loginState: LoginState = .SignIn // MARK: - Startup public override func viewDidLoad() { super.viewDidLoad() setupView() setupScoreSelectorTableView() setupTextFields() } public override func viewDidAppear(animated: Bool) { manageLoginStatus() // necessary to wait until viewDidAppear? fetchAllObjectsFromLocalDatastore() fetchAllObjects() } private func setupView() { updateUIForColorMode() } private func setupScoreSelectorTableView() { scoreSelectorTableView.delegate = self scoreSelectorTableView.dataSource = self } private func setupTextFields() { usernameField.delegate = self passwordField.delegate = self } // MARK: - UI @IBAction func didEnterUsername(sender: AnyObject) { // move on to password field passwordField.becomeFirstResponder() } @IBAction func didEnterPassword(sender: AnyObject) { if let username = usernameField.text, password = passwordField.text { // make sure the username and password is legit legit if username.characters.count > 0 && password.characters.count >= 8 { // disable keyboard passwordField.resignFirstResponder() // don't do this by the text of the button: enum LoginState { } switch signInOrOutOrUpButton.currentTitle! { case "SIGN UP": let user = PFUser() user.username = username user.password = password do { try user.signUp() enterSignedInMode() } catch { print("could not sign up user") // manage this in the UI } case "SIGN IN": do { try PFUser.logInWithUsername(username, password: password) enterSignedInMode() } catch { print(error) } default: break } } } } @IBAction func didPressSignInOrOutOrUpButton(sender: AnyObject) { // don't do this with the text if let title = signInOrOutOrUpButton.currentTitle { if title == "SIGN OUT?" { if PFUser.currentUser() != nil { PFUser.logOutInBackground() scoreObjects = [] scoreSelectorTableView.reloadData() enterSignInMode() } } } } @IBAction func didPressSignInOrUpButton(sender: AnyObject) { // don't do this with text! if let title = signInOrUpButton.currentTitle { if title == "SIGN UP?" { enterSignUpmMode() } else if title == "SIGN IN?" { enterSignInMode() } } } @IBAction func didChangeValueOfSwitch(sender: UISwitch) { // state on = dark, off = light switch sender.on { case true: DNMColorManager.colorMode = ColorMode.Dark case false: DNMColorManager.colorMode = ColorMode.Light } updateUIForColorMode() } private func updateUIForColorMode() { view.backgroundColor = DNMColorManager.backgroundColor scoreSelectorTableView.reloadData() // enscapsulate let bgView = UIView() bgView.backgroundColor = DNMColorManager.backgroundColor scoreSelectorTableView.backgroundView = bgView loginStatusLabel.textColor = UIColor.grayscaleColorWithDepthOfField(.MiddleForeground) colorModeLabel.textColor = UIColor.grayscaleColorWithDepthOfField(.Foreground) colorModeLightLabel.textColor = UIColor.grayscaleColorWithDepthOfField(.Foreground) colorModeDarkLabel.textColor = UIColor.grayscaleColorWithDepthOfField(.Foreground) // textfields usernameField.backgroundColor = UIColor.grayscaleColorWithDepthOfField(.Background) usernameField.textColor = UIColor.grayscaleColorWithDepthOfField(.Foreground) passwordField.backgroundColor = UIColor.grayscaleColorWithDepthOfField(.Background) passwordField.textColor = UIColor.grayscaleColorWithDepthOfField(.Foreground) dnmLogoLabel.textColor = UIColor.grayscaleColorWithDepthOfField(.Foreground) } func updateLoginStatusLabel() { if let username = PFUser.currentUser()?.username { loginStatusLabel.hidden = false loginStatusLabel.text = "logged in as \(username)" } else { loginStatusLabel.hidden = true } } private func showScoreSelectorTableView() { scoreSelectorTableView.hidden = false } private func hideScoreSelectorTableView() { scoreSelectorTableView.hidden = true } // MARK: - Parse Management func manageLoginStatus() { PFUser.currentUser() == nil ? enterSignInMode() : enterSignedInMode() } func enterSignInMode() { // hide score selector table view -- later: animate offscreen left hideScoreSelectorTableView() signInOrOutOrUpButton.hidden = false signInOrOutOrUpButton.setTitle("SIGN IN", forState: .Normal) signInOrUpButton.hidden = false signInOrUpButton.setTitle("SIGN UP?", forState: .Normal) loginStatusLabel.hidden = true usernameField.hidden = false passwordField.hidden = false } // signed in func enterSignedInMode() { fetchAllObjectsFromLocalDatastore() fetchAllObjects() showScoreSelectorTableView() updateLoginStatusLabel() // hide username field, clear contents usernameField.hidden = true usernameField.text = nil // hide password field, clear contents passwordField.hidden = true passwordField.text = nil signInOrUpButton.hidden = true signInOrOutOrUpButton.hidden = false signInOrOutOrUpButton.setTitle("SIGN OUT?", forState: .Normal) } // need to sign up func enterSignUpmMode() { signInOrOutOrUpButton.setTitle("SIGN UP", forState: .Normal) signInOrUpButton.setTitle("SIGN IN?", forState: .Normal) } // MARK: - UITableViewDelegate Methods public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath ) as! ScoreSelectorTableViewCell // text cell.textLabel?.text = scoreObjects[indexPath.row]["title"] as? String // color cell.textLabel?.textColor = UIColor.grayscaleColorWithDepthOfField(.Foreground) cell.backgroundColor = UIColor.grayscaleColorWithDepthOfField(DepthOfField.Background) // make cleaner let selBGView = UIView() selBGView.backgroundColor = UIColor.grayscaleColorWithDepthOfField(.Middleground) cell.selectedBackgroundView = selBGView return cell } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let scoreString = scoreObjects[indexPath.row]["text"] { let scoreModel = makeScoreModelWithString(scoreString as! String) scoreModelSelected = scoreModel performSegueWithIdentifier("showScore", sender: self) } } public override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let id = segue.identifier where id == "showScore" { let scoreViewController = segue.destinationViewController as! ScoreViewController if let scoreModel = scoreModelSelected { scoreViewController.showScoreWithScoreModel(scoreModel) } } } public func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView(frame: CGRectZero) } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return scoreObjects.count } public override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Parse private func fetchAllObjectsFromLocalDatastore() { if let username = PFUser.currentUser()?.username { let query = PFQuery(className: "Score") query.fromLocalDatastore() query.whereKey("username", equalTo: username) query.findObjectsInBackgroundWithBlock { (objects, error) -> () in if let error = error { print(error) } else if let objects = objects { self.scoreObjects = objects self.scoreSelectorTableView.reloadData() } } } } private func fetchAllObjects() { if let username = PFUser.currentUser()?.username { PFObject.unpinAllObjectsInBackground() let query = PFQuery(className: "Score") query.whereKey("username", equalTo: username) query.findObjectsInBackgroundWithBlock { (objects, error) -> () in if let objects = objects where error == nil { self.scoreObjects = objects do { try PFObject.pinAll(objects) } catch { print("couldnt pin") } self.fetchAllObjectsFromLocalDatastore() } } } } // MARK: - Model public func makeScoreModelWithString(string: String) -> DNMScoreModel { let tokenizer = Tokenizer() let tokenContainer = tokenizer.tokenizeString(string) let parser = Parser() let scoreModel = parser.parseTokenContainer(tokenContainer) return scoreModel } } private enum LoginState { case SignedIn, SignIn, SignUp }
91b4128cc5b3652c657e2f61a17850f8
32.038781
99
0.597133
false
false
false
false
kykim/SwiftCheck
refs/heads/master
Sources/Gen.swift
mit
1
// // Gen.swift // SwiftCheck // // Created by Robert Widmann on 7/31/14. // Copyright (c) 2015 TypeLift. All rights reserved. // /// `Gen` represents a generator for random arbitrary values of type `A`. /// /// `Gen` wraps a function that, when given a random number generator and a /// size, can be used to control the distribution of resultant values. A /// generator relies on its size to help control aspects like the length of /// generated arrays and the magnitude of integral values. public struct Gen<A> { /// The function underlying the receiver. /// /// +--- An RNG /// | +--- The size of generated values. /// | | /// v v let unGen : (StdGen, Int) -> A /// Generates a value. /// /// This property exists as a convenience mostly to test generators. In /// practice, you should never use this property because it hinders the /// replay functionality and the robustness of tests in general. public var generate : A { let r = newStdGen() return unGen(r, 30) } /// Generates some example values. /// /// This property exists as a convenience mostly to test generators. In /// practice, you should never use this property because it hinders the /// replay functionality and the robustness of tests in general. public var sample : [A] { return sequence((2...20).map(self.resize)).generate } /// Constructs a Generator that selects a random value from the given /// collection and produces only that value. /// /// The input collection is required to be non-empty. public static func fromElementsOf<S : Collection>(_ xs : S) -> Gen<S._Element> where S.Index : Comparable & RandomType { return Gen.fromElementsIn(xs.startIndex...xs.index(xs.endIndex, offsetBy: -1)).map { i in return xs[i] } } /// Constructs a Generator that selects a random value from the given /// interval and produces only that value. /// /// The input interval is required to be non-empty. public static func fromElementsIn<R : RandomType>(_ xs : ClosedRange<R>) -> Gen<R> { assert(!xs.isEmpty, "Gen.fromElementsOf used with empty interval") return choose((xs.lowerBound, xs.upperBound)) } /// Constructs a Generator that uses a given array to produce smaller arrays /// composed of its initial segments. The size of each initial segment /// increases with the receiver's size parameter. /// /// The input array is required to be non-empty. public static func fromInitialSegmentsOf<S>(_ xs : [S]) -> Gen<[S]> { assert(!xs.isEmpty, "Gen.fromInitialSegmentsOf used with empty list") return Gen<[S]>.sized { n in let ss = xs[xs.startIndex..<max((xs.startIndex + 1), size(xs.endIndex, n))] return Gen<[S]>.pure([S](ss)) } } /// Constructs a Generator that produces permutations of a given array. public static func fromShufflingElementsOf<S>(_ xs : [S]) -> Gen<[S]> { return choose((Int.min + 1, Int.max)).proliferateSized(xs.count).flatMap { ns in return Gen<[S]>.pure(Swift.zip(ns, xs).sorted(by: { l, r in l.0 < r.0 }).map { $0.1 }) } } /// Constructs a generator that depends on a size parameter. public static func sized(_ f : @escaping (Int) -> Gen<A>) -> Gen<A> { return Gen(unGen: { r, n in return f(n).unGen(r, n) }) } /// Constructs a random element in the inclusive range of two `RandomType`s. /// /// When using this function, it is necessary to explicitly specialize the /// generic parameter `A`. For example: /// /// Gen<UInt32>.choose((32, 255)).flatMap(Gen<Character>.pure • Character.init • UnicodeScalar.init) public static func choose<A : RandomType>(_ rng : (A, A)) -> Gen<A> { return Gen<A>(unGen: { s, _ in return A.randomInRange(rng, gen: s).0 }) } /// Constructs a random element in the range of a bounded `RandomType`. /// /// When using this function, it is necessary to explicitly specialize the /// generic parameter `A`. For example: /// /// Gen<UInt32>.chooseAny().flatMap(Gen<Character>.pure • Character.init • UnicodeScalar.init) public static func chooseAny<A : RandomType & LatticeType>() -> Gen<A> { return Gen<A>(unGen: { (s, _) in return randomBound(s).0 }) } /// Constructs a Generator that randomly selects and uses a particular /// generator from the given sequence of Generators. /// /// If control over the distribution of generators is needed, see /// `Gen.frequency` or `Gen.weighted`. public static func oneOf<S : BidirectionalCollection>(_ gs : S) -> Gen<A> where S.Iterator.Element == Gen<A>, S.Index : RandomType & Comparable { assert(gs.count != 0, "oneOf used with empty list") return choose((gs.startIndex, gs.index(before: gs.endIndex))).flatMap { x in return gs[x] } } /// Given a sequence of Generators and weights associated with them, this /// function randomly selects and uses a Generator. /// /// Only use this function when you need to assign uneven "weights" to each /// generator. If all generators need to have an equal chance of being /// selected, use `Gen.oneOf`. public static func frequency<S : Sequence>(_ xs : S) -> Gen<A> where S.Iterator.Element == (Int, Gen<A>) { let xs: [(Int, Gen<A>)] = Array(xs) assert(xs.count != 0, "frequency used with empty list") return choose((1, xs.map({ $0.0 }).reduce(0, +))).flatMap { l in return pick(l, xs) } } /// Given a list of values and weights associated with them, this function /// randomly selects and uses a Generator wrapping one of the values. /// /// This function operates in exactly the same manner as `Gen.frequency`, /// `Gen.fromElementsOf`, and `Gen.fromElementsIn` but for any type rather /// than only Generators. It can help in cases where your `Gen.from*` call /// contains only `Gen.pure` calls by allowing you to remove every /// `Gen.pure` in favor of a direct list of values. public static func weighted<S : Sequence>(_ xs : S) -> Gen<A> where S.Iterator.Element == (Int, A) { return frequency(xs.map { ($0, Gen.pure($1)) }) } } // MARK: Monoidal Functor methods. extension Gen { /// Zips together two generators and returns a generator of tuples. public static func zip<A1, A2>(_ ga1 : Gen<A1>, _ ga2 : Gen<A2>) -> Gen<(A1, A2)> { return Gen<(A1, A2)> { r, n in let (r1, r2) = r.split return (ga1.unGen(r1, n), ga2.unGen(r2, n)) } } /// Returns a new generator that applies a given function to any outputs the /// given generators produce. public static func map<A1, A2, R>(_ ga1 : Gen<A1>, _ ga2 : Gen<A2>, transform: @escaping (A1, A2) -> R) -> Gen<R> { return zip(ga1, ga2).map(transform) } } // MARK: Generator Modifiers extension Gen { /// Shakes up the receiver's internal Random Number Generator with a seed. public func variant<S : Integer>(_ seed : S) -> Gen<A> { return Gen(unGen: { rng, n in return self.unGen(vary(seed, rng), n) }) } /// Modifies a Generator to always use a given size. public func resize(_ n : Int) -> Gen<A> { return Gen(unGen: { r, _ in return self.unGen(r, n) }) } /// Modifiers a Generator's size parameter by transforming it with the given /// function. public func scale(_ f : @escaping (Int) -> Int) -> Gen<A> { return Gen.sized { n in return self.resize(f(n)) } } /// Modifies a Generator such that it only returns values that satisfy a /// predicate. When the predicate fails the test case is treated as though /// it never occured. /// /// Because the Generator will spin until it reaches a non-failing case, /// executing a condition that fails more often than it succeeds may result /// in a space leak. At that point, it is better to use `suchThatOptional` /// or `.invert` the test case. public func suchThat(_ p : @escaping (A) -> Bool) -> Gen<A> { return self.suchThatOptional(p).flatMap { mx in switch mx { case .some(let x): return Gen.pure(x) case .none: return Gen.sized { n in return self.suchThat(p).resize((n + 1)) } } } } /// Modifies a Generator such that it attempts to generate values that /// satisfy a predicate. All attempts are encoded in the form of an /// `Optional` where values satisfying the predicate are wrapped in `.Some` /// and failing values are `.None`. public func suchThatOptional(_ p : @escaping (A) -> Bool) -> Gen<Optional<A>> { return Gen<Optional<A>>.sized { n in return attemptBoundedTry(self, 0, max(n, 1), p) } } /// Modifies a Generator such that it produces arrays with a length /// determined by the receiver's size parameter. public var proliferate : Gen<[A]> { return Gen<[A]>.sized { n in return Gen.choose((0, n)).flatMap(self.proliferateSized) } } /// Modifies a Generator such that it produces non-empty arrays with a /// length determined by the receiver's size parameter. public var proliferateNonEmpty : Gen<[A]> { return Gen<[A]>.sized { n in return Gen.choose((1, max(1, n))).flatMap(self.proliferateSized) } } /// Modifies a Generator such that it only produces arrays of a given length. public func proliferateSized(_ k : Int) -> Gen<[A]> { return sequence(Array<Gen<A>>(repeating: self, count: k)) } } // MARK: Instances extension Gen /*: Functor*/ { /// Returns a new generator that applies a given function to any outputs the /// receiver creates. /// /// This function is most useful for converting between generators of inter- /// related types. For example, you might have a Generator of `Character` /// values that you then `.proliferate` into an `Array` of `Character`s. You /// can then use `fmap` to convert that generator of `Array`s to a generator of /// `String`s. public func map<B>(_ f : @escaping (A) -> B) -> Gen<B> { return Gen<B>(unGen: { r, n in return f(self.unGen(r, n)) }) } } extension Gen /*: Applicative*/ { /// Lifts a value into a generator that will only generate that value. public static func pure(_ a : A) -> Gen<A> { return Gen(unGen: { _ in return a }) } /// Given a generator of functions, applies any generated function to any /// outputs the receiver creates. public func ap<B>(_ fn : Gen<(A) -> B>) -> Gen<B> { return Gen<B>(unGen: { r, n in let (r1, r2) = r.split return fn.unGen(r1, n)(self.unGen(r2, n)) }) } } extension Gen /*: Monad*/ { /// Applies the function to any generated values to yield a new generator. /// This generator is then given a new random seed and returned. /// /// `flatMap` allows for the creation of Generators that depend on other /// generators. One might, for example, use a Generator of integers to /// control the length of a Generator of strings, or use it to choose a /// random index into a Generator of arrays. public func flatMap<B>(_ fn : @escaping (A) -> Gen<B>) -> Gen<B> { return Gen<B>(unGen: { r, n in let (r1, r2) = r.split let m2 = fn(self.unGen(r1, n)) return m2.unGen(r2, n) }) } } /// Creates and returns a Generator of arrays of values drawn from each /// generator in the given array. /// /// The array that is created is guaranteed to use each of the given Generators /// in the order they were given to the function exactly once. Thus all arrays /// generated are of the same rank as the array that was given. public func sequence<A>(_ ms : [Gen<A>]) -> Gen<[A]> { return ms.reduce(Gen<[A]>.pure([]), { n, m in return m.flatMap { x in return n.flatMap { xs in return Gen<[A]>.pure(xs + [x]) } } }) } /// Flattens a generator of generators by one level. public func join<A>(_ rs : Gen<Gen<A>>) -> Gen<A> { return rs.flatMap { x in return x } } /// Lifts a function from some A to some R to a function from generators of A to /// generators of R. public func liftM<A, R>(_ f : @escaping (A) -> R, _ m1 : Gen<A>) -> Gen<R> { return m1.flatMap{ x1 in return Gen.pure(f(x1)) } } /// Promotes a rose of generators to a generator of rose values. public func promote<A>(_ x : Rose<Gen<A>>) -> Gen<Rose<A>> { return delay().flatMap { eval in return Gen<Rose<A>>.pure(liftM(eval, x)) } } /// Promotes a function returning generators to a generator of functions. public func promote<A, B>(_ m : @escaping (A) -> Gen<B>) -> Gen<(A) -> B> { return delay().flatMap { eval in return Gen<(A) -> B>.pure(comp(eval, m)) } } // MARK: - Implementation Details private func delay<A>() -> Gen<(Gen<A>) -> A> { return Gen(unGen: { r, n in return { g in return g.unGen(r, n) } }) } private func vary<S : Integer>(_ k : S, _ rng : StdGen) -> StdGen { let s = rng.split let gen = ((k % 2) == 0) ? s.0 : s.1 return (k == (k / 2)) ? gen : vary(k / 2, rng) } private func attemptBoundedTry<A>(_ gen : Gen<A>, _ k : Int, _ bound : Int, _ pred : @escaping (A) -> Bool) -> Gen<Optional<A>> { if bound == 0 { return Gen.pure(.none) } return gen.resize(2 * k + bound).flatMap { x in if pred(x) { return Gen.pure(.some(x)) } return attemptBoundedTry(gen, (k + 1), bound - 1, pred) } } private func size<S : Integer>(_ k : S, _ m : Int) -> Int { let n = Double(m) return Int((log(n + 1)) * Double(k.toIntMax()) / log(100)) } private func selectOne<A>(_ xs : [A]) -> [(A, [A])] { guard let y = xs.first else { return [] } let ys = Array(xs[1..<xs.endIndex]) let rec : [(A, Array<A>)] = selectOne(ys).map({ t in (t.0, [y] + t.1) }) return [(y, ys)] + rec } private func pick<A>(_ n : Int, _ lst : [(Int, Gen<A>)]) -> Gen<A> { let (k, x) = lst[0] let tl = Array<(Int, Gen<A>)>(lst[1..<lst.count]) if n <= k { return x } return pick(n - k, tl) } #if os(Linux) import Glibc #else import Darwin #endif
31f691c8c7b455c4d39562cbd5503148
31.774818
129
0.650931
false
false
false
false
mortorqrobotics/MorTeam-ios
refs/heads/master
MorTeam/FeedViewController.swift
mit
1
// // MapViewController.swift // MorTeam // // Created by arvin zadeh on 6/21/16. // Copyright © 2016 MorTorq. All rights reserved. // import UIKit import Foundation import GoogleMaps import Kingfisher class FeedViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { @IBOutlet var announcementCollectionView: UICollectionView! @IBOutlet var postButton: UIBarButtonItem! var storage = UserDefaults.standard var announcements = [Announcement]() let cellIdentifier = "AnnouncementCell" // var imageCache = [String:UIImage]() let screenSize: CGRect = UIScreen.main.bounds var page = 0; var isRefreshing = false; var refreshControl: UIRefreshControl! var didLoadOnce = false var cellHeights = [CGFloat]() var isSecond = false let morTeamURL = "http://www.morteam.com/api" override func viewDidLoad() { super.viewDidLoad() self.setup(); //Change later //self.getAnnouncements() ref() } override func viewDidAppear(_ animated: Bool) { } func setup() { self.announcementCollectionView.backgroundColor = UIColorFromHex("#E9E9E9"); self.refreshControl = UIRefreshControl(); self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh"); self.refreshControl.addTarget(self, action: #selector(FeedViewController.refresh(_:)), for: UIControlEvents.valueChanged) self.announcementCollectionView.addSubview(refreshControl) } func getAnnouncements() { httpRequest(self.morTeamURL+"/announcements?skip="+String(self.page*20), type: "GET"){ responseText2, responseCode in let newAnnouncements = parseJSON(responseText2) for(_, json):(String, JSON) in newAnnouncements { self.announcements.append(Announcement(announcementJSON: json)) } DispatchQueue.main.async(execute: { self.announcementCollectionView.reloadData() //self.refreshFeed() }) self.page += 1; } } func refreshFeed(){ } func refresh(_ sender: AnyObject){ ref() } func ref(){ if (!isRefreshing){ isRefreshing = true httpRequest(self.morTeamURL+"/announcements?skip=0", type: "GET"){ responseText2, responseCode in let newAnnouncements = parseJSON(responseText2) self.announcements = [] for(_, json):(String, JSON) in newAnnouncements { self.announcements.append(Announcement(announcementJSON: json)) } DispatchQueue.main.async(execute: { self.cellHeights = [] self.announcementCollectionView.reloadData() self.isRefreshing = false self.refreshControl.endRefreshing() }) self.page = 1 } } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.announcements.count } @IBAction func teamButtonClicked(_ sender: AnyObject) { DispatchQueue.main.async(execute: { let vc: TeamViewVC! = self.storyboard!.instantiateViewController(withIdentifier: "TeamView") as! TeamViewVC self.show(vc as UITableViewController, sender: vc) }) } @IBAction func postButtonClicked(_ sender: AnyObject) { DispatchQueue.main.async(execute: { let vc: PostAnnouncementVC! = self.storyboard!.instantiateViewController(withIdentifier: "PostAnnouncement") as! PostAnnouncementVC self.show(vc as UIViewController, sender: vc) }) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = announcementCollectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! AnnouncementCell if (!isRefreshing){ cell.layer.shouldRasterize = true; cell.layer.rasterizationScale = UIScreen.main.scale; let announcementAtIndex = self.announcements[(indexPath as NSIndexPath).item] cell.name.text = String(describing: announcementAtIndex.author["firstname"]) + " " + String(describing: announcementAtIndex.author["lastname"]) let formatter = DateFormatter() formatter.locale = Locale(identifier: "UTC") formatter.timeZone = TimeZone(abbreviation: "UTC") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" let date = formatter.date(from: announcementAtIndex.timestamp) formatter.dateStyle = .long formatter.timeStyle = .medium formatter.timeZone = NSTimeZone.local cell.date.text = formatter.string(from: date!) let content = announcementAtIndex.content.data(using: String.Encoding.unicode, allowLossyConversion: true) let attrStr = try! NSMutableAttributedString( data: content!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) attrStr.addAttribute(NSFontAttributeName, value: UIFont( name: "Exo2-Light", size: 15.0)!, range: NSRange( location: 0, length: (attrStr.length)) ) cell.content.attributedText = attrStr cell.profilePic.image = UIImage(named: "user") cell.backgroundColor = UIColor.white let imagePath = String(describing: announcementAtIndex.author["profpicpath"]).replacingOccurrences(of: " ", with: "%20") + "-60" var profPicUrl = URL(string: "http://www.morteam.com"+imagePath) if (imagePath != "/images/user.jpg-60"){ profPicUrl = URL(string: "http://profilepics.morteam.com.s3.amazonaws.com"+imagePath.substring(from: (imagePath.index((imagePath.startIndex), offsetBy: 3)))) } cell.profilePic.kf.setImage(with: profPicUrl) // if let img = imageCache[profPicUrlString] { // cell.profilePic.image = img // }else{ // let request: NSMutableURLRequest = NSMutableURLRequest(url: profPicUrl!) // if let sid = storage.string(forKey: "connect.sid"){ // request.addValue("connect.sid=\(sid)", forHTTPHeaderField: "Cookie") // } // let mainQueue = OperationQueue.main // NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: mainQueue, completionHandler: { (response, data, error) -> Void in // if error == nil { // // let image = UIImage(data: data!) // // self.imageCache[profPicUrlString] = image // // DispatchQueue.main.async(execute: { // if let cellToUpdate = self.announcementCollectionView.cellForItem(at: indexPath) as? AnnouncementCell { // cellToUpdate.profilePic.image = image // } // }) // } // else { // print("Error: \(error!.localizedDescription)") // } // }) // } cell.layer.shadowColor = UIColor.black.cgColor cell.layer.shadowOffset = CGSize(width: 0, height: 2.0) cell.layer.shadowRadius = 2.0 cell.layer.shadowOpacity = 0.2 cell.layer.masksToBounds = false cell.profilePic.layer.cornerRadius = 4.2 cell.profilePic.clipsToBounds = true //For some reason, contentHeight can't be set up here to be used down there, ignore the repetition if (!self.cellHeights.indices.contains(indexPath.row)){ DispatchQueue.main.async(execute: { let contentHeight = cell.content.sizeThatFits(cell.content.contentSize).height self.cellHeights.append(contentHeight) self.announcementCollectionView.reloadItems(at: [indexPath]) }) } else { //Fixes the oddity if (cell.content.sizeThatFits(cell.content.contentSize).height != self.cellHeights[indexPath.row]){ DispatchQueue.main.async(execute: { let contentHeight = cell.content.sizeThatFits(cell.content.contentSize).height self.cellHeights[indexPath.row] = contentHeight self.announcementCollectionView.reloadItems(at: [indexPath]) }) } } } //self.announcementCollectionView.reloadItems(at: [indexPath]) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize{ if (cellHeights.indices.contains(indexPath.row)){ return CGSize(width: self.screenSize.width-10, height: cellHeights[indexPath.row]+57.0) } return CGSize(width: self.screenSize.width-10, height: 200.0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
961800c5fb7464fd3267f688376e62ef
36.241135
173
0.553704
false
false
false
false
joshpar/Lyrebird
refs/heads/master
LyrebirdSynth/Lyrebird/UGens/EnvelopeUGens.swift
artistic-2.0
1
// // EnvelopeUGens.swift // Lyrebird // // Created by Joshua Parmenter on 7/12/16. // Copyright © 2016 Op133Studios. All rights reserved. // public enum EnvelopeGenDoneAction: Int { case nothing, freeNode, loop } open class EnvelopeGen : LyrebirdUGen { let envelope: Envelope var gate: Bool = false var doneAction: EnvelopeGenDoneAction let releaseSegment: LyrebirdInt let levelScale: LyrebirdFloat let levelBias: LyrebirdFloat let timeScale: LyrebirdFloat let totalDur: LyrebirdFloat fileprivate var timeKeeper: LyrebirdFloat = 0.0 fileprivate let timeInc: LyrebirdFloat fileprivate let gateTime: LyrebirdFloat public required init(rate: LyrebirdUGenRate, envelope: Envelope, levelScale: LyrebirdFloat = 1.0, levelBias: LyrebirdFloat = 0.0, timeScale: LyrebirdFloat = 1.0, releaseSegment: LyrebirdInt = -1, doneAction: EnvelopeGenDoneAction = .nothing){ self.envelope = envelope self.levelScale = levelScale self.levelBias = levelBias self.timeScale = timeScale self.releaseSegment = releaseSegment var timeInc = Lyrebird.engine.iSampleRate var gateTime = -1.0 if releaseSegment >= 0 { gateTime = 0.0 for (index, segment) in envelope.segments.enumerated() { if index <= releaseSegment { gateTime = gateTime + segment.duration } else { break } } } var totalDur: LyrebirdFloat = 0.0 for (index, segment) in envelope.segments.enumerated() { totalDur = totalDur + segment.duration } self.gateTime = gateTime if timeScale != 1.0 && timeScale > 0.0 { totalDur = totalDur * timeScale timeInc = timeInc / timeScale } self.totalDur = totalDur self.doneAction = doneAction self.timeInc = timeInc super.init(rate: rate) } override final public func next(numSamples: LyrebirdInt) -> Bool { var success: Bool = super.next(numSamples: numSamples) for sampleIdx in 0 ..< numSamples { samples[sampleIdx] = (envelope.poll(atTime: timeKeeper) * levelScale) + levelBias timeKeeper = timeKeeper + timeInc // test release if (timeKeeper > totalDur) && (doneAction == .loop) { timeKeeper = 0.0 } } if (timeKeeper > totalDur) && (doneAction == .freeNode) { self.graph?.shouldRemoveFromTree = true } return success } }
51df54924f80e112fa9b437ac7de674d
34.12
246
0.609339
false
false
false
false
Pluto-Y/SwiftyEcharts
refs/heads/master
SwiftyEchartsTest_iOS/SingleAxisSpec.swift
mit
1
// // SingleAxisSpec.swift // SwiftyEcharts // // Created by Pluto Y on 08/08/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // import Quick import Nimble @testable import SwiftyEcharts class SingleAxisSpec: QuickSpec { override func spec() { let valueDataValue = "singAxisDataValue" let textStyleDataValue = TextStyle( .fontSize(18), .fontFamily("singleAxisDataTextStyleFontFamily"), .fontStyle(.italic) ) let data = SingleAxis.Data() data.value = valueDataValue data.textStyle = textStyleDataValue describe("For SingleAxis.Data") { it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "value": valueDataValue, "textStyle": textStyleDataValue ] expect(data.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let dataByEnums = SingleAxis.Data( .value(valueDataValue), .textStyle(textStyleDataValue) ) expect(dataByEnums.jsonString).to(equal(data.jsonString)) } } describe("For SingleAxis") { let zlevelValue: Float = 7562.4746 let zValue: Float = 0.000003476734 let leftValue = Position.value(28%) let topValue = Position.value(20) let rightValue = Position.point([20, 0.0%]) let bottomValue = Position.bottom let widthValue: Float = 20 let heightValue: Float = 0.0 let orientValue = Orient.vertical let typeValue = AxisType.log let nameValue = "singleAxisValue" let nameLocationValue = Location.start let nameTextStyleValue = TextStyle( .align(.right), .fontStyle(FontStyle.oblique) ) let nameGapValue: Float = 25 let nameRotateValue: Float = 90.0 let inverseValue = true let boundaryGapValue: BoundaryGap = false let minValue = "类C" let maxValue = 100.9999999 let scaleValue = false let splitNumberValue: UInt8 = 0 let minIntervalValue: UInt8 = 255 let intervalValue = Int.min let logBaseValue: Float = 0.057235 let silentValue = true let triggerEventValue = true let axisLineValue = AxisLine( .lineStyle(LineStyle( .curveness(99999.11111111), .opacity(0.99999999999) )) ) let axisTickValue = AxisTick( .alignWithLabel(true), .interval(1), .inside(false) ) let axisLabelValue = AxisLabel( .margin(75.46), .formatter(.string("")), .rotate(90.989) ) let splitLineValue = SplitLine( .show(false) ) let splitAreaValue = SplitArea( .interval(2) ) let dataValue: [Jsonable] = [ data, "周二", ["value": "周三", "textStyle": TextStyle()] ] let singleAxis = SingleAxis() singleAxis.zlevel = zlevelValue singleAxis.z = zValue singleAxis.left = leftValue singleAxis.top = topValue singleAxis.right = rightValue singleAxis.bottom = bottomValue singleAxis.width = widthValue singleAxis.height = heightValue singleAxis.orient = orientValue singleAxis.type = typeValue singleAxis.name = nameValue singleAxis.nameLocation = nameLocationValue singleAxis.nameTextStyle = nameTextStyleValue singleAxis.nameGap = nameGapValue singleAxis.nameRotate = nameRotateValue singleAxis.inverse = inverseValue singleAxis.boundaryGap = boundaryGapValue singleAxis.min = minValue singleAxis.max = maxValue singleAxis.scale = scaleValue singleAxis.splitNumber = splitNumberValue singleAxis.minInterval = minIntervalValue singleAxis.interval = intervalValue singleAxis.logBase = logBaseValue singleAxis.silent = silentValue singleAxis.triggerEvent = triggerEventValue singleAxis.axisLine = axisLineValue singleAxis.axisTick = axisTickValue singleAxis.axisLabel = axisLabelValue singleAxis.splitLine = splitLineValue singleAxis.splitArea = splitAreaValue singleAxis.data = dataValue it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "zlevel": zlevelValue, "z": zValue, "left": leftValue, "top": topValue, "right": rightValue, "bottom": bottomValue, "width": widthValue, "height": heightValue, "orient": orientValue, "type": typeValue, "name": nameValue, "nameLocation": nameLocationValue, "nameTextStyle": nameTextStyleValue, "nameGap": nameGapValue, "nameRotate": nameRotateValue, "inverse": inverseValue, "boundaryGap": boundaryGapValue, "min": minValue, "max": maxValue, "scale": scaleValue, "splitNumber": splitNumberValue, "minInterval": minIntervalValue, "interval": intervalValue, "logBase": logBaseValue, "silent": silentValue, "triggerEvent": triggerEventValue, "axisLine": axisLineValue, "axisTick": axisTickValue, "axisLabel": axisLabelValue, "splitLine": splitLineValue, "splitArea": splitAreaValue, "data": dataValue ] expect(singleAxis.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let singleAxisByEnums = SingleAxis( .zlevel(zlevelValue), .z(zValue), .left(leftValue), .top(topValue), .right(rightValue), .bottom(bottomValue), .width(widthValue), .height(heightValue), .orient(orientValue), .type(typeValue), .name(nameValue), .nameLocation(nameLocationValue), .nameTextStyle(nameTextStyleValue), .nameGap(nameGapValue), .nameRotate(nameRotateValue), .inverse(inverseValue), .boundaryGap(boundaryGapValue), .min(minValue), .max(maxValue), .scale(scaleValue), .splitNumber(splitNumberValue), .minInterval(minIntervalValue), .interval(intervalValue), .logBase(logBaseValue), .silent(silentValue), .triggerEvent(triggerEventValue), .axisLine(axisLineValue), .axisTick(axisTickValue), .axisLabel(axisLabelValue), .splitLine(splitLineValue), .splitArea(splitAreaValue), .data(dataValue) ) expect(singleAxisByEnums.jsonString).to(equal(singleAxis.jsonString)) } } } }
1c677b3f0da7bd105eb9f73c465fac06
37.428571
85
0.494424
false
false
false
false
sunflash/SwiftHTTPClient
refs/heads/master
HTTPClient/Classes/Mappable/Mappable.swift
mit
1
// // Mappable.swift // Mappable // // Created by Min Wu on 22/05/2017. // Copyright © 2017 Min Wu. All rights reserved. // import Foundation // MARK: - Mappable Protocol /// Mappable protocol that provides extra functionality to mapped object. public protocol Mappable: Codable { /// `Mappable` object's property value. var propertyValues: [String: Any] {get} /// Default requirement as part of the `Mappable` protocol, it's necessary when expose `Mappable` object through SDK framework. init() } // MARK: - Mappable Property Raw Data extension Mappable { /// `Mappable` object property names that is not included computed property. public var propertyNamesRaw: [String] { Mirror(reflecting: self).children.compactMap {$0.label} } /// `Mappable` property name value pair that is not included computed property. public var propertyValuesRaw: [String: Any] { var values = [String: Any]() let properties = Mirror(reflecting: self).children for property in properties { guard let propertyName = property.label else {continue} values[propertyName] = property.value } return values } /// `Mappable` super class property name value pair that is not included computed property. /// - Note: Only work with class and not sturct. public var superClassPropertyValuesRaw: [String: Any] { var values = [String: Any]() guard let superClassMirror = Mirror(reflecting: self).superclassMirror else { return values } let properties = superClassMirror.children for property in properties { guard let propertyName = property.label else {continue} values[propertyName] = property.value } return values } /// `Mappable` property name value pair with `Optional` value unwrapped, doesn't included computed property. public var propertyUnwrappedDataRaw: [String: Any] { unwrapPropertyValues(propertyValuesRaw, true) } /// `Mappable` property value without computed property in description, /// can either print out to console for debugging, logs to file or sendt out to log collection system. public var objectDescriptionRaw: String { generateObjectDescription(showRawDescription: true) } } // MARK: - Mappable Property Data extension Mappable { /// Description of `Mappable` object, contain object name and object type info. public var objectInfo: String { let mirror = Mirror(reflecting: self) if let styleDescription = mirror.displayStyle?.description { return "\(mirror.subjectType): \(styleDescription)" } else { return "\(mirror.subjectType)" } } /// `Mappable` property names which is included computed property. public var propertyNames: [String] { propertyValues.map {$0.key} } /// `Mappable` property name value pair with `Optional` value unwrapped, is included computed property. public var propertyUnwrappedData: [String: Any] { unwrapPropertyValues(propertyValues, false) } /// `Mappable` property value with computed property as part of the description, /// can either print out to console for debugging, logs to file or sendt out to log collection system. public var objectDescription: String { generateObjectDescription(showRawDescription: false) } } // MARK: - Mappable Property Methods extension Mappable { /// Subscript to access `Mappable` object's property value. /// /// - Parameter key: name of the property public subscript (key: String) -> Any? { propertyValues[key] ?? propertyValuesRaw[key] } /// Create a new property values dictionary with some property values filter out. /// /// - Parameters: /// - propertyToAdjust: Sepecifiy property need adjustment. /// - property: Array of property names that should be filter out. /// - Returns: New property values dictionary with some property values filter out. private func excludePropertyValues(propertyNeedAdjust: [String: Any], excluded property: [String]) -> [String: Any] { var values = [String: Any]() propertyNeedAdjust.filter {property.contains($0.key) == false}.forEach {values[$0.key] = $0.value} return values } /// Adjust property values presentation for 'Mappable' object. /// - Note: For example, we want to hide some private, fileprivate, or raw properties values from json, and added some computed property values to the representation. /// In this way, we can shape what data we want consumer to see with `propertyValues`. /// - Parameters: /// - propertyToAdjust: Sepecifiy property need adjustment, default to `propertyValuesRaw` if unspecified. /// - property: Property values that we want to remove from presentation, for example private, fileprivate, or raw properties values from json. /// - propertyInfo: Property values that we want to added to presentation, /// that should include computed property values which is not part of the raw `Mappable` object. /// - Returns: A new dictionary with some raw property values removed and some computed property values added to the presentation. public func adjustPropertyValues(_ propertyToAdjust: [String: Any] = [String: Any](), excluded property: [String] = [""], additional propertyInfo: [String: Any] = [String: Any]()) -> [String: Any] { let propertyNeedAdjust = propertyToAdjust.isEmpty ? propertyValuesRaw : propertyToAdjust var values = excludePropertyValues(propertyNeedAdjust: propertyNeedAdjust, excluded: property) values += propertyInfo return values } } // MARK: - Mappable Nested Object extension Mappable { /// Process data in nested data structure, if object contain another object or an array of objects. /// /// - Parameters: /// - type: Type of nested object we looking after. /// - value: Object that we want to do processing with. /// - action: A closure with action we want to preform. /// - Returns: Result of the nested data structure processing. fileprivate func processDataInNestedStructure<T>(type: T.Type, value: Any, action: (T) -> Any) -> (isNestedObject: Bool, data: Any?) { if let nestedObject = value as? T { let results = action(nestedObject) return (true, results) } if let nestedObjectArray = value as? [T] { var results = [Any]() for nestedObject in nestedObjectArray { let result = action(nestedObject) results.append(result) } return (true, results) } return (false, nil) } } // MARK: - Mappable Property JSON Representation extension Mappable { /// Show raw `Mappable` object in json representation. /// /// - Parameter dateFormatter: Date formatter that convert `Date` to `String`. /// - Returns: Formatted JSON representation as `String`. public func propertyJSONRepresentation(dateFormatter: DateFormatter) -> String { generateObjectJsonRepresentation(propertyUnwrappedDataRaw, dateFormatter) } /// Generate `Mappable` object's JSON representation. /// /// - Parameters: /// - unwrappedPropertyValues: Unwrapped `Mappable` property values. /// - dateFormatter: Date formatter that convert `Date` to `String`. /// - Returns: Formatted JSON representation as `String`. private func generateObjectJsonRepresentation(_ unwrappedPropertyValues: [String: Any], _ dateFormatter: DateFormatter) -> String { let errorMessage = "Can't generate \(objectInfo) json representation." do { let jsonObject = formatDateToString(unwrappedPropertyValues, dateFormatter) let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted) return String(data: jsonData, encoding: .utf8) ?? errorMessage } catch { logCoder(.JSONDecode, errorMessage) return errorMessage } } /// Format date to string /// /// - Parameters: /// - dictionary: Unwrapped `Mappable` property values. /// - dateFormatter: Date formatter that convert `Date` to `String`. /// - Returns: Formatted property values with `Date` converts to `String` private func formatDateToString(_ dictionary: [String: Any], _ dateFormatter: DateFormatter) -> [String: Any] { var results = [String: Any]() for (key, value) in dictionary { let type = Mirror(reflecting: value).subjectType let isDate = (type == Date.self) || (type == Optional<Date>.self) if isDate == true, let date = value as? Date { let dateString = dateFormatter.string(from: date) results[key] = dateString as Any continue } let result = processDataInNestedStructure(type: [String: Any].self, value: value) { nestedDictionary in formatDateToString(nestedDictionary, dateFormatter) } if result.isNestedObject == true { results[key] = result.data continue } results[key] = value } return results } } // MARK: - Mappable Description Methods extension Mappable { /// Generate `Mappable` object to description. /// /// - Parameter showRawDescription: Flag whether what values to show, `propertyValuesRaw` or `propertyValues` /// - Returns: Description of property values. fileprivate func generateObjectDescription(showRawDescription: Bool) -> String { let values = (showRawDescription == true) ? propertyValuesRaw : propertyValues let sortedValues = values.sorted(by: {$0.key < $1.key}) let propertyInfo = sortedValues.reduce("") {$0 + "\n\($1.key) = \(unwrappedDescription($1.value, showRawDescription))"} var descriptionString = separatorWithNewLine() descriptionString += objectInfo if showRawDescription == true { descriptionString += "\n" + "RAW" } descriptionString += separatorWithNewLine() descriptionString += propertyInfo descriptionString += separatorWithNewLine("=") return descriptionString } /// Get property description with optional values unwrapped. /// /// - Parameters: /// - value: Value of the property, could be a nested `Mappable` object or `Mappable` object array. /// - useRawValue: Flag whether what values to show, `propertyValuesRaw` or `propertyValues` with nested `Mappable` object. /// - Returns: Property description with optional values unwrapped. private func unwrappedDescription(_ value: Any, _ useRawValue: Bool) -> String { var value = value let mirror = Mirror(reflecting: value) if let style = mirror.displayStyle, style == .optional, let newValue = mirror.children.first?.value { value = newValue } let result = processDataInNestedStructure(type: Mappable.self, value: value) { mappable in let nestedValues = (useRawValue == true) ? mappable.propertyValuesRaw : mappable.propertyValues let sortedValues = nestedValues.sorted(by: {$0.key < $1.key}) let nestedUnwrapDescriptions = sortedValues.map {"\($0.key) = \(unwrappedDescription($0.value, useRawValue))"} let nestedObjectDescription = nestedUnwrapDescriptions.joined(separator: ", ") return "{ \(nestedObjectDescription) }" } if result.isNestedObject == true { if let description = result.data as? String { return description } else if let descriptions = result.data as? [String] { return "[ \(descriptions.joined(separator: ",\n\t\t")) ]" } } return String(describing: value) } } // MARK: - Mappabel Unwrap Values Methods extension Mappable { /// Unwrapped property values, remove `Optional` from property values. /// /// - Parameters: /// - values: Property values to unwrap. /// - useRawValue: Flag whether what values to unwrap, `propertyValuesRaw` or `propertyValues` with nested `Mappable` object. /// - Returns: Unwrapped property values. fileprivate func unwrapPropertyValues(_ values: [String: Any], _ useRawValue: Bool) -> [String: Any] { var unwrappedValues = [String: Any]() for (key, value) in values { guard let validValue = unwrapPropertyValue(value, useRawValue) else {continue} unwrappedValues[key] = validValue } return unwrappedValues } /// Unwrapped property value, remove `Optional` from property value. /// /// - Parameters: /// - value: Property value to unwrap. /// - useRawValue: Flag whether what values to unwrap, `propertyValuesRaw` or `propertyValues` with nested `Mappable` object. /// - Returns: Unwrapped property value. private func unwrapPropertyValue(_ value: Any, _ useRawValue: Bool) -> Any? { var value = value let mirror = Mirror(reflecting: value) if let style = mirror.displayStyle, style == .optional { if let newValue = mirror.children.first?.value { value = newValue } else { return nil } } let result = processDataInNestedStructure(type: Mappable.self, value: value) { mappable in let values = (useRawValue == true) ? mappable.propertyValuesRaw : mappable.propertyValues let nestedValues = unwrapPropertyValues(values, useRawValue) return nestedValues } if result.isNestedObject == true {return result.data} return value } } // MARK: - Mirror Types Extension extension Mirror.DisplayStyle { /// Show `Mirror.DisplayStyle` as string. public var description: String { switch self { case .class: return "Class" case .collection: return "Collection" case .dictionary: return "Dictionary" case .enum: return "Enum" case .optional: return "Optional" case .set: return "Set" case .struct: return "Struct" case .tuple: return "Tuple" @unknown default: return "" } } }
2a32a65bbdcb84386b4acde1b300f619
37.486911
170
0.641001
false
false
false
false
huangboju/Moots
refs/heads/master
算法学习/LeetCode/LeetCode/NSum/FourSum.swift
mit
1
// // FourSum.swift // LeetCode // // Created by 黄伯驹 on 2021/1/26. // Copyright © 2021 伯驹 黄. All rights reserved. // import Foundation // https://leetcode.cn/problems/4sum/submissions/ func fourSum(_ nums: [Int], _ target: Int) -> [[Int]] { if nums.count < 4 { return [] } let sortedNums = nums.sorted() var res = [[Int]]() for j in 0 ..< sortedNums.count { if j > 0 && sortedNums[j] == sortedNums[j - 1] { continue } for i in j + 1 ..< sortedNums.count { if i > j + 1 && sortedNums[i] == sortedNums[i - 1] { continue } var left = i + 1 var right = sortedNums.count - 1 while left < right { let sum = sortedNums[left] + sortedNums[right] + sortedNums[j] + sortedNums[i] if sum == target { res.append([sortedNums[j], sortedNums[i], sortedNums[left], sortedNums[right]]) while left < right && sortedNums[left] == sortedNums[left + 1] { left += 1 } while left < right && sortedNums[right] == sortedNums[right - 1] { right -= 1 } } if sum > target { right -= 1 } else { left += 1 } } } } return res }
20709e39accdbda86c83de0fbb1f00e0
26.87037
99
0.420598
false
false
false
false
Arnoymous/AListViewController
refs/heads/master
Example/AListViewController/CollectionViewCell.swift
mit
1
// // CollectionViewCell.swift // AListViewController // // Created by Arnaud Dorgans on 03/10/2017. // Copyright © 2017 Arnaud Dorgans. All rights reserved. // import UIKit import PureLayout import SDWebImage class CollectionViewCell: UICollectionViewCell { let imageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) self.contentView.clipsToBounds = true self.contentView.layer.cornerRadius = 4 self.contentView.backgroundColor = UIColor.lightGray imageView.contentMode = .scaleAspectFill self.contentView.addSubview(imageView) imageView.autoPinEdgesToSuperviewEdges() } func update(withShot shot: DribbbleShot) { imageView.sd_setImage(with: shot.image) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
e55eae12db93956c6a36c7ebaede1bd5
24.722222
60
0.672786
false
false
false
false
zhaobin19918183/zhaobinCode
refs/heads/master
FamilyShop/FamilyShop/AppDelegate.swift
gpl-3.0
1
// // AppDelegate.swift // FamilyShop // // Created by Zhao.bin on 16/9/26. // Copyright © 2016年 Zhao.bin. All rights reserved. // import UIKit import UIKit.UIGestureRecognizerSubclass @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var button:UIButton? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. initialDirectories() self.perform(#selector(AppDelegate.setNew), with: nil, afterDelay:0.25) self.window?.makeKeyAndVisible() return true } func setNew() { button = UIButton(type:.contactAdd) //设置按钮位置和大小 button?.frame = CGRect(x:(self.window?.bounds.size.width)! - 100, y:(self.window?.bounds.size.height)! - 150, width:60, height:60) //设置按钮文字 button?.backgroundColor = UIColor.red button?.addTarget(self, action: #selector(AppDelegate.test), for: UIControlEvents.touchDown) // let panGesture = UIPanGestureRecognizer(target: self, action:#selector(AppDelegate.handlePanGesture(sender:))) // button?.addGestureRecognizer(panGesture) window?.addSubview(button!) } func test() { print("1111") } //拖手势 func handlePanGesture(sender: UIPanGestureRecognizer){ // //得到拖的过程中的xy坐标 var translation : CGPoint = sender.translation(in: button) //平移图片CGAffineTransformMakeTranslation button?.transform = CGAffineTransform(translationX: translation.x+translation.x, y: translation.y+translation.y) if sender.state == UIGestureRecognizerState.ended{ translation.x += translation.x translation.y += translation.y } } 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 invalidate graphics rendering callbacks. 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 active 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:. } }
ed068a9fd603b76fb34c003a5a0ab6ab
41.2
285
0.705604
false
false
false
false
wyp767363905/GiftSay
refs/heads/master
GiftSay/GiftSay/classes/profile/setUp/controller/SetUpViewController.swift
mit
1
// // SetUpViewController.swift // GiftSay // // Created by qianfeng on 16/8/31. // Copyright © 2016年 qianfeng. All rights reserved. // import UIKit class SetUpViewController: BaseViewController { private var tbView: UITableView? private var imageNames = NSArray() private var titleArray = NSArray() private var descArray = NSArray() private lazy var dataArray = NSMutableArray() private var model: RecommendModel?{ didSet { if model != nil { let appArray = (model?.data?.ios_apps)! for appModel in appArray { dataArray.addObject(appModel) createData() } self.tbView?.reloadData() } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. createMyNav() createTableView() downloaderRecommendData() } func createData(){ imageNames = ["identity","invitation","score","feedback","service","like","pushed","clear_cache","network_test","about","recommended"] titleArray = ["我的身份","邀请好友使用礼物说","给我们评分吧","意见反馈","客服电话","喜欢单品到默认清单","消息推送设置","清除缓存","网络监测","关于礼物说","推荐应用"] descArray = ["男孩 高中生","","奖励5积分","","4009992053","","","","","",""] } func downloaderRecommendData(){ let urlString = kSetUpRecommendedUrl let downloader = WYPDownloader() downloader.delegate = self downloader.downloaderWithUrlString(urlString) } func createTableView(){ automaticallyAdjustsScrollViewInsets = false tbView = UITableView(frame: CGRectZero, style: .Plain) tbView?.delegate = self tbView?.dataSource = self view.addSubview(tbView!) tbView?.snp_makeConstraints(closure: { [weak self] (make) in make.edges.equalTo(self!.view).inset(UIEdgeInsetsMake(64, 0, 0, 0)) }) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.barTintColor = UIColor.redColor() } func createMyNav(){ addNavTitle("更多") addNavBackBtn() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension SetUpViewController : WYPDownloaderDelegate { func downloader(downloader: WYPDownloader, didFailWithError error: NSError) { print(error) } func downloader(downloader: WYPDownloader, didFinishWithData data: NSData?) { if let jsonData = data { let model = RecommendModel.parseModel(jsonData) dispatch_async(dispatch_get_main_queue(), { [weak self] in self!.model = model }) } } } extension SetUpViewController : UITableViewDelegate,UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var rowNum = 0 if imageNames != "" && titleArray != "" && descArray != "" && dataArray != "" { rowNum = imageNames.count + dataArray.count } return rowNum } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var height: CGFloat = 0 if indexPath.row >= (imageNames.count - 1) && indexPath.row <= (imageNames.count+dataArray.count-2){ height = 100 }else{ height = 50 } return height } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row >= (imageNames.count - 1) && indexPath.row <= (imageNames.count+dataArray.count-2){ let cellId = "setCellId" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? SetCell if nil == cell { cell = NSBundle.mainBundle().loadNibNamed("SetUpCell", owner: nil, options: nil)[1] as? SetCell } let model = dataArray[indexPath.row-imageNames.count+1] cell?.configModel(model as! RecommendAppsModel) return cell! }else{ let cellId = "setUpCellId" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? SetUpCell if nil == cell { cell = NSBundle.mainBundle().loadNibNamed("SetUpCell", owner: nil, options: nil)[0] as? SetUpCell } if indexPath.row < (imageNames.count - 1) { cell?.smallBgImageView.image = UIImage(named: imageNames[indexPath.row] as! String) cell?.smallTitleLabel.text = titleArray[indexPath.row] as? String cell?.smallDescLabel.text = descArray[indexPath.row] as? String }else{ cell?.smallBgImageView.image = UIImage(named: imageNames[indexPath.row-dataArray.count] as! String) cell?.smallTitleLabel.text = titleArray[indexPath.row-dataArray.count] as? String cell?.smallDescLabel.text = descArray[indexPath.row-dataArray.count] as? String } if indexPath.row == 5 { let sw = UISwitch() cell?.addSubview(sw) sw.snp_makeConstraints(closure: { (make) in make.right.equalTo(cell!).offset(-20) make.top.equalTo(cell!).offset(10) make.width.equalTo(60) make.height.equalTo(40) }) } if indexPath.row == 0 || indexPath.row == 3 || indexPath.row == 6 || indexPath.row == 7 || indexPath.row == 8 || indexPath.row == 9 { cell?.smallImageView.image = UIImage(named: "category_arrow_right") }else{ cell?.smallImageView.image = nil } return cell! } } }
6b064cd46a91fdaf88a6be18c4b980d5
27.592742
145
0.535326
false
false
false
false
dreamsxin/swift
refs/heads/master
test/IRGen/protocol_metadata.swift
apache-2.0
3
// RUN: %target-swift-frontend -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop protocol A { func a() } protocol B { func b() } protocol C : class { func c() } @objc protocol O { func o() } @objc protocol OPT { @objc optional func opt() @objc optional static func static_opt() @objc optional var prop: O { get } @objc optional subscript (x: O) -> O { get } } protocol AB : A, B { func ab() } protocol ABO : A, B, O { func abo() } // CHECK: @_TMp17protocol_metadata1A = hidden constant %swift.protocol { // -- size 72 // -- flags: 1 = Swift | 2 = Not Class-Constrained | 4 = Needs Witness Table // CHECK: i32 72, i32 7, // CHECK: i16 0, i16 0 // CHECK: } // CHECK: @_TMp17protocol_metadata1B = hidden constant %swift.protocol { // CHECK: i32 72, i32 7, // CHECK: i16 0, i16 0 // CHECK: } // CHECK: @_TMp17protocol_metadata1C = hidden constant %swift.protocol { // -- flags: 1 = Swift | 4 = Needs Witness Table // CHECK: i32 72, i32 5, // CHECK: i16 0, i16 0 // CHECK: } // -- @objc protocol O uses ObjC symbol mangling and layout // CHECK: @_PROTOCOL__TtP17protocol_metadata1O_ = private constant { {{.*}} i32, { [1 x i8*] }*, i8*, i8* } { // CHECK: @_PROTOCOL_INSTANCE_METHODS__TtP17protocol_metadata1O_, // -- size, flags: 1 = Swift // CHECK: i32 96, i32 1 // CHECK: } // CHECK: @_PROTOCOL_METHOD_TYPES__TtP17protocol_metadata1O_ // CHECK: } // -- @objc protocol OPT uses ObjC symbol mangling and layout // CHECK: @_PROTOCOL__TtP17protocol_metadata3OPT_ = private constant { {{.*}} i32, { [4 x i8*] }*, i8*, i8* } { // CHECK: @_PROTOCOL_INSTANCE_METHODS_OPT__TtP17protocol_metadata3OPT_, // CHECK: @_PROTOCOL_CLASS_METHODS_OPT__TtP17protocol_metadata3OPT_, // -- size, flags: 1 = Swift // CHECK: i32 96, i32 1 // CHECK: } // CHECK: @_PROTOCOL_METHOD_TYPES__TtP17protocol_metadata3OPT_ // CHECK: } // -- inheritance lists for refined protocols // CHECK: [[AB_INHERITED:@.*]] = private constant { {{.*}}* } { // CHECK: i64 2, // CHECK: %swift.protocol* @_TMp17protocol_metadata1A, // CHECK: %swift.protocol* @_TMp17protocol_metadata1B // CHECK: } // CHECK: @_TMp17protocol_metadata2AB = hidden constant %swift.protocol { // CHECK: [[AB_INHERITED]] // CHECK: i32 72, i32 7, // CHECK: i16 0, i16 0 // CHECK: } // CHECK: [[ABO_INHERITED:@.*]] = private constant { {{.*}}* } { // CHECK: i64 3, // CHECK: %swift.protocol* @_TMp17protocol_metadata1A, // CHECK: %swift.protocol* @_TMp17protocol_metadata1B, // CHECK: {{.*}}* @_PROTOCOL__TtP17protocol_metadata1O_ // CHECK: } func reify_metadata<T>(_ x: T) {} // CHECK: define hidden void @_TF17protocol_metadata14protocol_types func protocol_types(_ a: A, abc: protocol<A, B, C>, abco: protocol<A, B, C, O>) { // CHECK: store %swift.protocol* @_TMp17protocol_metadata1A // CHECK: call %swift.type* @rt_swift_getExistentialTypeMetadata(i64 1, %swift.protocol** {{%.*}}) reify_metadata(a) // CHECK: store %swift.protocol* @_TMp17protocol_metadata1A // CHECK: store %swift.protocol* @_TMp17protocol_metadata1B // CHECK: store %swift.protocol* @_TMp17protocol_metadata1C // CHECK: call %swift.type* @rt_swift_getExistentialTypeMetadata(i64 3, %swift.protocol** {{%.*}}) reify_metadata(abc) // CHECK: store %swift.protocol* @_TMp17protocol_metadata1A // CHECK: store %swift.protocol* @_TMp17protocol_metadata1B // CHECK: store %swift.protocol* @_TMp17protocol_metadata1C // CHECK: [[O_REF:%.*]] = load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP17protocol_metadata1O_" // CHECK: [[O_REF_BITCAST:%.*]] = bitcast i8* [[O_REF]] to %swift.protocol* // CHECK: store %swift.protocol* [[O_REF_BITCAST]] // CHECK: call %swift.type* @rt_swift_getExistentialTypeMetadata(i64 4, %swift.protocol** {{%.*}}) reify_metadata(abco) }
1ab10fb3038907e6cb1ae9651240b694
37.475248
117
0.645394
false
false
false
false
Acidburn0zzz/firefox-ios
refs/heads/main
Client/Frontend/Browser/TopTabsViews.swift
mpl-2.0
1
/* 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 Shared struct TopTabsSeparatorUX { static let Identifier = "Separator" static let Width: CGFloat = 1 } class TopTabsSeparator: UICollectionReusableView { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.theme.topTabs.separator } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class TopTabsHeaderFooter: UICollectionReusableView { let line = UIView() override init(frame: CGRect) { super.init(frame: frame) line.semanticContentAttribute = .forceLeftToRight addSubview(line) line.backgroundColor = UIColor.theme.topTabs.separator } func arrangeLine(_ kind: String) { line.snp.removeConstraints() switch kind { case UICollectionView.elementKindSectionHeader: line.snp.makeConstraints { make in make.trailing.equalTo(self) } case UICollectionView.elementKindSectionFooter: line.snp.makeConstraints { make in make.leading.equalTo(self) } default: break } line.snp.makeConstraints { make in make.height.equalTo(TopTabsUX.SeparatorHeight) make.width.equalTo(TopTabsUX.SeparatorWidth) make.top.equalTo(self).offset(TopTabsUX.SeparatorYOffset) } } override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) { layer.zPosition = CGFloat(layoutAttributes.zIndex) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class TopTabCell: UICollectionViewCell, PrivateModeUI { static let Identifier = "TopTabCellIdentifier" static let ShadowOffsetSize: CGFloat = 2 //The shadow is used to hide the tab separator var selectedTab = false { didSet { backgroundColor = selectedTab ? UIColor.theme.topTabs.tabBackgroundSelected : UIColor.theme.topTabs.tabBackgroundUnselected titleText.textColor = selectedTab ? UIColor.theme.topTabs.tabForegroundSelected : UIColor.theme.topTabs.tabForegroundUnselected highlightLine.isHidden = !selectedTab closeButton.tintColor = selectedTab ? UIColor.theme.topTabs.closeButtonSelectedTab : UIColor.theme.topTabs.closeButtonUnselectedTab closeButton.backgroundColor = backgroundColor closeButton.layer.shadowColor = backgroundColor?.cgColor if selectedTab { drawShadow() } else { self.layer.shadowOpacity = 0 } } } let titleText: UILabel = { let titleText = UILabel() titleText.textAlignment = .left titleText.isUserInteractionEnabled = false titleText.numberOfLines = 1 titleText.lineBreakMode = .byCharWrapping titleText.font = DynamicFontHelper.defaultHelper.DefaultSmallFont titleText.semanticContentAttribute = .forceLeftToRight return titleText }() let favicon: UIImageView = { let favicon = UIImageView() favicon.layer.cornerRadius = 2.0 favicon.layer.masksToBounds = true favicon.semanticContentAttribute = .forceLeftToRight return favicon }() let closeButton: UIButton = { let closeButton = UIButton() closeButton.setImage(UIImage.templateImageNamed("menu-CloseTabs"), for: []) closeButton.tintColor = UIColor.Photon.Grey40 closeButton.imageEdgeInsets = UIEdgeInsets(top: 15, left: TopTabsUX.TabTitlePadding, bottom: 15, right: TopTabsUX.TabTitlePadding) closeButton.layer.shadowOpacity = 0.8 closeButton.layer.masksToBounds = false closeButton.layer.shadowOffset = CGSize(width: -TopTabsUX.TabTitlePadding, height: 0) closeButton.semanticContentAttribute = .forceLeftToRight return closeButton }() let highlightLine: UIView = { let line = UIView() line.backgroundColor = UIColor.Photon.Blue60 line.isHidden = true line.semanticContentAttribute = .forceLeftToRight return line }() weak var delegate: TopTabCellDelegate? override init(frame: CGRect) { super.init(frame: frame) closeButton.addTarget(self, action: #selector(closeTab), for: .touchUpInside) contentView.addSubview(titleText) contentView.addSubview(closeButton) contentView.addSubview(favicon) contentView.addSubview(highlightLine) favicon.snp.makeConstraints { make in make.centerY.equalTo(self).offset(TopTabsUX.TabNudge) make.size.equalTo(TabTrayControllerUX.FaviconSize) make.leading.equalTo(self).offset(TopTabsUX.TabTitlePadding) } titleText.snp.makeConstraints { make in make.centerY.equalTo(self) make.height.equalTo(self) make.trailing.equalTo(closeButton.snp.leading).offset(TopTabsUX.TabTitlePadding) make.leading.equalTo(favicon.snp.trailing).offset(TopTabsUX.TabTitlePadding) } closeButton.snp.makeConstraints { make in make.centerY.equalTo(self).offset(TopTabsUX.TabNudge) make.height.equalTo(self) make.width.equalTo(self.snp.height).offset(-TopTabsUX.TabTitlePadding) make.trailing.equalTo(self.snp.trailing) } highlightLine.snp.makeConstraints { make in make.top.equalTo(self) make.leading.equalTo(self).offset(-TopTabCell.ShadowOffsetSize) make.trailing.equalTo(self).offset(TopTabCell.ShadowOffsetSize) make.height.equalTo(TopTabsUX.HighlightLineWidth) } self.clipsToBounds = false applyUIMode(isPrivate: false) } func applyUIMode(isPrivate: Bool) { highlightLine.backgroundColor = UIColor.theme.topTabs.tabSelectedIndicatorBar(isPrivate) } func configureWith(tab: Tab, isSelected: Bool) { applyUIMode(isPrivate: tab.isPrivate) self.titleText.text = tab.displayTitle if tab.displayTitle.isEmpty { if let url = tab.webView?.url, let internalScheme = InternalURL(url) { self.titleText.text = Strings.AppMenuNewTabTitleString self.accessibilityLabel = internalScheme.aboutComponent } else { self.titleText.text = tab.webView?.url?.absoluteDisplayString } self.closeButton.accessibilityLabel = String(format: Strings.TopSitesRemoveButtonAccessibilityLabel, self.titleText.text ?? "") } else { self.accessibilityLabel = tab.displayTitle self.closeButton.accessibilityLabel = String(format: Strings.TopSitesRemoveButtonAccessibilityLabel, tab.displayTitle) } self.selectedTab = isSelected if let siteURL = tab.url?.displayURL { self.favicon.contentMode = .center self.favicon.setImageAndBackground(forIcon: tab.displayFavicon, website: siteURL) { [weak self] in guard let self = self else { return } self.favicon.image = self.favicon.image?.createScaled(CGSize(width: 15, height: 15)) if self.favicon.backgroundColor == .clear { self.favicon.backgroundColor = .white } } } else { self.favicon.image = UIImage(named: "defaultFavicon") self.favicon.tintColor = UIColor.theme.tabTray.faviconTint self.favicon.contentMode = .scaleAspectFit self.favicon.backgroundColor = .clear } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() self.layer.shadowOpacity = 0 } @objc func closeTab() { delegate?.tabCellDidClose(self) } // When a tab is selected the shadow prevents the tab separators from showing. func drawShadow() { self.layer.masksToBounds = false self.layer.shadowColor = backgroundColor?.cgColor self.layer.shadowOpacity = 1 self.layer.shadowRadius = 0 self.layer.shadowPath = UIBezierPath(roundedRect: CGRect(width: self.frame.size.width + (TopTabCell.ShadowOffsetSize * 2), height: self.frame.size.height), cornerRadius: 0).cgPath self.layer.shadowOffset = CGSize(width: -TopTabCell.ShadowOffsetSize, height: 0) } override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) { layer.zPosition = CGFloat(layoutAttributes.zIndex) } } class TopTabFader: UIView { lazy var hMaskLayer: CAGradientLayer = { let innerColor: CGColor = UIColor.Photon.White100.cgColor let outerColor: CGColor = UIColor(white: 1, alpha: 0.0).cgColor let hMaskLayer = CAGradientLayer() hMaskLayer.colors = [outerColor, innerColor, innerColor, outerColor] hMaskLayer.locations = [0.00, 0.005, 0.995, 1.0] hMaskLayer.startPoint = CGPoint(x: 0, y: 0.5) hMaskLayer.endPoint = CGPoint(x: 1.0, y: 0.5) hMaskLayer.anchorPoint = .zero return hMaskLayer }() init() { super.init(frame: .zero) layer.mask = hMaskLayer } internal override func layoutSubviews() { super.layoutSubviews() let widthA = NSNumber(value: Float(CGFloat(8) / frame.width)) let widthB = NSNumber(value: Float(1 - CGFloat(8) / frame.width)) hMaskLayer.locations = [0.00, widthA, widthB, 1.0] hMaskLayer.frame = CGRect(width: frame.width, height: frame.height) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class TopTabsViewLayoutAttributes: UICollectionViewLayoutAttributes { override func isEqual(_ object: Any?) -> Bool { guard let object = object as? TopTabsViewLayoutAttributes else { return false } return super.isEqual(object) } }
5ea07ad2f29b81d937d346af0b6c462d
36.967153
187
0.657118
false
false
false
false
geng199200/xiaorizi-Gl
refs/heads/master
xiaorizi-Gl/Category/UIBarButtonItem.swift
mit
1
// // UIBarButtonItem+Utils.swift // xiaorizi-Gl // // Created by 66 on 2016/10/25. // Copyright © 2016年 genju. All rights reserved. // import Foundation import UIKit extension UIBarButtonItem { class func barButtonItemWithLeftIcon(icon: String, _ highlightedIcon: String, _ target: Any, _ action: Selector) -> UIBarButtonItem { let leftButton: UIButton = UIButton.init(type: UIButtonType.custom) leftButton.frame = CGRect.init(x: 0, y: 0, width: 44, height: 44) leftButton.setImage(UIImage.init(named: icon), for: UIControlState.normal) leftButton.addTarget(target, action: action, for: UIControlEvents.touchUpInside) return UIBarButtonItem.init(customView: leftButton) } class func barButtonItemWithRightIcons(icon: String, _ highlightedIcon: String, _ target: Any, _ action: Selector, _ secondIcon: String, _ secondHighlightedIcon: String, _ secondTarget: Any, _ secondAction: Selector) -> Array <UIBarButtonItem>{ let firstRightBtn: UIButton = UIButton.init(type: .custom) firstRightBtn.frame = CGRect.init(x: 0, y: 0, width: 44, height: 44) firstRightBtn.setImage(UIImage.init(named: icon), for: .normal) firstRightBtn.addTarget(target, action: action, for: .touchUpInside) let firstItem = UIBarButtonItem.init(customView: firstRightBtn) let secondRightBtn: UIButton = UIButton.init(type: .custom) secondRightBtn.frame = CGRect.init(x: 0, y: 0, width: 44, height: 44) secondRightBtn.setImage(UIImage.init(named: secondIcon), for: .normal) secondRightBtn.addTarget(secondTarget, action: secondAction, for: .touchUpInside) let secondItem = UIBarButtonItem.init(customView: secondRightBtn) return [firstItem, secondItem] } }
f5dac34629963a4707a81590f82d8cad
46.078947
230
0.705422
false
false
false
false
Luccifer/LocationCore
refs/heads/master
LocationCore.swift
mit
1
// // LocationCore.swift // SurpriseMe // // Created by Gleb Karpushkin on 15/09/2016. // Copyright © 2016 SurpriseMe. All rights reserved. // import Foundation import CoreLocation public protocol LocationProtocol { var manager: CLLocationManager { get } var desiredAccuracy: CLLocationAccuracy { get set } var distanceFilter: CLLocationDistance { get set } var pausesLocationUpdates: Bool { get set } var monitoringAlavialbe: Bool {get set} func startUpdating() func stopUpdating() func monitorNewRegion(_ region: CLCircularRegion) func stopMonitorRegion(_ region: CLCircularRegion) func getLocationAccuracy() -> String init() } fileprivate class LocationManagerDelegate: NSObject, CLLocationManagerDelegate { deinit { print("Location Core Deinitialized") } internal func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { } internal func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { NSLog("\(error)") } internal func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) { NSLog("\(error)") } internal func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { } internal func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) { switch state { case .inside: break case .outside: break default: break } } internal func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { switch status { case .authorizedAlways: break case .authorizedWhenInUse: break case .denied : break case .notDetermined: break case .restricted: break } } } struct Location: LocationProtocol { public var desiredAccuracy: CLLocationAccuracy public var distanceFilter: CLLocationDistance public var pausesLocationUpdates: Bool public var monitoringAlavialbe: Bool public static var core: LocationProtocol = Location() public var manager = CLLocationManager() fileprivate var managerDelegate = LocationManagerDelegate() init() { self.desiredAccuracy = kCLLocationAccuracyBestForNavigation self.distanceFilter = kCLDistanceFilterNone self.pausesLocationUpdates = false self.monitoringAlavialbe = CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) manager.delegate = managerDelegate manager.allowsBackgroundLocationUpdates = true manager.requestAlwaysAuthorization() } public func startUpdating() { self.manager.startUpdatingLocation() } public func stopUpdating() { self.manager.stopUpdatingLocation() } public func monitorNewRegion(_ region: CLCircularRegion) { region.notifyOnEntry = true self.manager.startMonitoring(for: region) } public func stopMonitorRegion(_ region: CLCircularRegion) { self.manager.startMonitoring(for: region) } public func getLocationAccuracy() -> String { if (self.manager.location!.horizontalAccuracy < 0) { print("No Signal") return "No Signal".localized } else if (self.manager.location!.horizontalAccuracy > 163) { print("Poor Signal") return "Poor".localized } else if (self.manager.location!.horizontalAccuracy > 48) { print("Average Signal") return "Average".localized } else { print("Full Signal") return "Full".localized } } }
17b21678b881a0acd519338c82b34891
27.408451
129
0.640555
false
false
false
false
digipost/ios
refs/heads/master
Digipost/UploadMenuViewController.swift
apache-2.0
1
// // Copyright (C) Posten Norge AS // // 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 class UploadMenuViewController: UIViewController, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! lazy var menuDataSource = UploadMenuDataSource() lazy var uploadImageController = UploadImageController() override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = menuDataSource tableView.delegate = self tableView.reloadData() tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 1)) navigationItem.title = NSLocalizedString("upload image Controller title", comment: "Upload") // Do any additional setup after loading the view. } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.row { case 0: uploadImageController.showCameraCaptureInViewController(self) case 1: uploadImageController.showPhotoLibraryPickerInViewController(self) default: assert(false) } } }
cbb5f6dc080a597dde39b82f1ce94f0b
33.625
100
0.694946
false
false
false
false
aschwaighofer/swift
refs/heads/master
test/Interpreter/generic_casts.swift
apache-2.0
2
// RUN: %empty-directory(%t) // RUN: %target-build-swift -Onone %s -o %t/a.out // RUN: %target-run %t/a.out | %FileCheck --check-prefix CHECK --check-prefix CHECK-ONONE %s // RUN: %target-build-swift -O %s -o %t/a.out.optimized // RUN: %target-codesign %t/a.out.optimized // RUN: %target-run %t/a.out.optimized | %FileCheck %s // REQUIRES: executable_test // FIXME: rdar://problem/19648117 Needs splitting objc parts out #if canImport(Foundation) import Foundation #endif func allToInt<T>(_ x: T) -> Int { return x as! Int } func allToIntOrZero<T>(_ x: T) -> Int { if x is Int { return x as! Int } return 0 } func anyToInt(_ x: Any) -> Int { return x as! Int } func anyToIntOrZero(_ x: Any) -> Int { if x is Int { return x as! Int } return 0 } protocol Class : class {} class C : Class { func print() { Swift.print("C!") } } class D : C { override func print() { Swift.print("D!") } } class E : C { override func print() { Swift.print("E!") } } class X : Class { } func allToC<T>(_ x: T) -> C { return x as! C } func allToCOrE<T>(_ x: T) -> C { if x is C { return x as! C } return E() } func anyToC(_ x: Any) -> C { return x as! C } func anyToCOrE(_ x: Any) -> C { if x is C { return x as! C } return E() } func allClassesToC<T : Class>(_ x: T) -> C { return x as! C } func allClassesToCOrE<T : Class>(_ x: T) -> C { if x is C { return x as! C } return E() } func anyClassToC(_ x: Class) -> C { return x as! C } func anyClassToCOrE(_ x: Class) -> C { if x is C { return x as! C } return E() } func allToAll<T, U>(_ t: T, _: U.Type) -> Bool { return t is U } func allMetasToAllMetas<T, U>(_: T.Type, _: U.Type) -> Bool { return T.self is U.Type } print(allToInt(22)) // CHECK: 22 print(anyToInt(44)) // CHECK: 44 allToC(C()).print() // CHECK: C! allToC(D()).print() // CHECK: D! anyToC(C()).print() // CHECK: C! anyToC(D()).print() // CHECK: D! allClassesToC(C()).print() // CHECK: C! allClassesToC(D()).print() // CHECK: D! anyClassToC(C()).print() // CHECK: C! anyClassToC(D()).print() // CHECK: D! print(allToIntOrZero(55)) // CHECK: 55 print(allToIntOrZero("fifty-five")) // CHECK: 0 print(anyToIntOrZero(88)) // CHECK: 88 print(anyToIntOrZero("eighty-eight")) // CHECK: 0 allToCOrE(C()).print() // CHECK: C! allToCOrE(D()).print() // CHECK: D! allToCOrE(143).print() // CHECK: E! allToCOrE(X()).print() // CHECK: E! anyToCOrE(C()).print() // CHECK: C! anyToCOrE(D()).print() // CHECK: D! anyToCOrE(143).print() // CHECK: E! anyToCOrE(X()).print() // CHECK: E! allClassesToCOrE(C()).print() // CHECK: C! allClassesToCOrE(D()).print() // CHECK: D! allClassesToCOrE(X()).print() // CHECK: E! anyClassToCOrE(C()).print() // CHECK: C! anyClassToCOrE(D()).print() // CHECK: D! anyClassToCOrE(X()).print() // CHECK: E! protocol P {} struct PS: P {} enum PE: P {} class PC: P {} class PCSub: PC {} // `is` checks func nongenericAnyIsPConforming(type: Any.Type) -> Bool { // `is P.Type` tests whether the argument conforms to `P` // Note: this can only be true for a concrete type, never a protocol return type is P.Type } func nongenericAnyIsPSubtype(type: Any.Type) -> Bool { // `is P.Protocol` tests whether the argument is a subtype of `P` // In particular, it is true for `P.self` return type is P.Protocol } func nongenericAnyIsPAndAnyObjectConforming(type: Any.Type) -> Bool { return type is (P & AnyObject).Type } func nongenericAnyIsPAndPCSubConforming(type: Any.Type) -> Bool { return type is (P & PCSub).Type } func genericAnyIs<T>(type: Any.Type, to: T.Type, expected: Bool) -> Bool { // If we're testing against a runtime that doesn't have the fix this tests, // just pretend we got it right. if #available(macOS 10.15.4, iOS 13.4, watchOS 6.2, tvOS 13.4, *) { return type is T.Type } else { return expected } } // `as?` checks func nongenericAnyAsConditionalPConforming(type: Any.Type) -> Bool { return (type as? P.Type) != nil } func nongenericAnyAsConditionalPSubtype(type: Any.Type) -> Bool { return (type as? P.Protocol) != nil } func nongenericAnyAsConditionalPAndAnyObjectConforming(type: Any.Type) -> Bool { return (type as? (P & AnyObject).Type) != nil } func nongenericAnyAsConditionalPAndPCSubConforming(type: Any.Type) -> Bool { return (type as? (P & PCSub).Type) != nil } func genericAnyAsConditional<T>(type: Any.Type, to: T.Type, expected: Bool) -> Bool { // If we're testing against a runtime that doesn't have the fix this tests, // just pretend we got it right. if #available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) { return (type as? T.Type) != nil } else { return expected } } // `as!` checks func blackhole<T>(_ : T) { } func nongenericAnyAsUnconditionalPConforming(type: Any.Type) -> Bool { blackhole(type as! P.Type) return true } func nongenericAnyAsUnconditionalPSubtype(type: Any.Type) -> Bool { blackhole(type as! P.Protocol) return true } func nongenericAnyAsUnconditionalPAndAnyObjectConforming(type: Any.Type) -> Bool { blackhole(type as! (P & AnyObject).Type) return true } func nongenericAnyAsUnconditionalPAndPCSubConforming(type: Any.Type) -> Bool { blackhole(type as! (P & PCSub).Type) return true } func genericAnyAsUnconditional<T>(type: Any.Type, to: T.Type, expected: Bool) -> Bool { if #available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) { blackhole(type as! T.Type) } return true } // CHECK-LABEL: casting types to protocols with generics: print("casting types to protocols with generics:") print(nongenericAnyIsPConforming(type: P.self)) // CHECK: false print(nongenericAnyIsPSubtype(type: P.self)) // CHECK: true print(genericAnyIs(type: P.self, to: P.self, expected: true)) // CHECK: true print(nongenericAnyIsPConforming(type: PS.self)) // CHECK: true print(genericAnyIs(type: PS.self, to: P.self, expected: true)) // CHECK-ONONE: true print(nongenericAnyIsPConforming(type: PE.self)) // CHECK: true print(genericAnyIs(type: PE.self, to: P.self, expected: true)) // CHECK-ONONE: true print(nongenericAnyIsPConforming(type: PC.self)) // CHECK: true print(genericAnyIs(type: PC.self, to: P.self, expected: true)) // CHECK-ONONE: true print(nongenericAnyIsPConforming(type: PCSub.self)) // CHECK: true print(genericAnyIs(type: PCSub.self, to: P.self, expected: true)) // CHECK-ONONE: true // CHECK-LABEL: conditionally casting types to protocols with generics: print("conditionally casting types to protocols with generics:") print(nongenericAnyAsConditionalPConforming(type: P.self)) // CHECK: false print(nongenericAnyAsConditionalPSubtype(type: P.self)) // CHECK: true print(genericAnyAsConditional(type: P.self, to: P.self, expected: true)) // CHECK: true print(nongenericAnyAsConditionalPConforming(type: PS.self)) // CHECK: true print(genericAnyAsConditional(type: PS.self, to: P.self, expected: true)) // CHECK-ONONE: true print(nongenericAnyAsConditionalPConforming(type: PE.self)) // CHECK: true print(genericAnyAsConditional(type: PE.self, to: P.self, expected: true)) // CHECK-ONONE: true print(nongenericAnyAsConditionalPConforming(type: PC.self)) // CHECK: true print(genericAnyAsConditional(type: PC.self, to: P.self, expected: true)) // CHECK-ONONE: true print(nongenericAnyAsConditionalPConforming(type: PCSub.self)) // CHECK: true print(genericAnyAsConditional(type: PCSub.self, to: P.self, expected: true)) // CHECK-ONONE: true // CHECK-LABEL: unconditionally casting types to protocols with generics: print("unconditionally casting types to protocols with generics:") //print(nongenericAnyAsUnconditionalPConforming(type: P.self)) // expected to trap print(nongenericAnyAsUnconditionalPSubtype(type: P.self)) // CHECK: true print(genericAnyAsUnconditional(type: P.self, to: P.self, expected: true)) // CHECK: true print(nongenericAnyAsUnconditionalPConforming(type: PS.self)) // CHECK: true print(genericAnyAsUnconditional(type: PS.self, to: P.self, expected: true)) // CHECK: true print(nongenericAnyAsUnconditionalPConforming(type: PE.self)) // CHECK: true print(genericAnyAsUnconditional(type: PE.self, to: P.self, expected: true)) // CHECK: true print(nongenericAnyAsUnconditionalPConforming(type: PC.self)) // CHECK: true print(genericAnyAsUnconditional(type: PC.self, to: P.self, expected: true)) // CHECK: true print(nongenericAnyAsUnconditionalPConforming(type: PCSub.self)) // CHECK: true print(genericAnyAsUnconditional(type: PCSub.self, to: P.self, expected: true)) // CHECK: true // CHECK-LABEL: casting types to protocol & AnyObject existentials: print("casting types to protocol & AnyObject existentials:") print(nongenericAnyIsPAndAnyObjectConforming(type: PS.self)) // CHECK: false print(genericAnyIs(type: PS.self, to: (P & AnyObject).self, expected: false)) // CHECK: false print(nongenericAnyIsPAndAnyObjectConforming(type: PE.self)) // CHECK: false print(genericAnyIs(type: PE.self, to: (P & AnyObject).self, expected: false)) // CHECK: false print(nongenericAnyIsPAndAnyObjectConforming(type: PC.self)) // CHECK: true print(genericAnyIs(type: PC.self, to: (P & AnyObject).self, expected: true)) // CHECK-ONONE: true print(nongenericAnyIsPAndAnyObjectConforming(type: PCSub.self)) // CHECK: true print(genericAnyIs(type: PCSub.self, to: (P & AnyObject).self, expected: true)) // CHECK-ONONE: true print(nongenericAnyAsConditionalPAndAnyObjectConforming(type: PS.self)) // CHECK: false print(genericAnyAsConditional(type: PS.self, to: (P & AnyObject).self, expected: false)) // CHECK: false print(nongenericAnyAsConditionalPAndAnyObjectConforming(type: PE.self)) // CHECK: false print(genericAnyAsConditional(type: PE.self, to: (P & AnyObject).self, expected: false)) // CHECK: false print(nongenericAnyAsConditionalPAndAnyObjectConforming(type: PC.self)) // CHECK: true print(genericAnyAsConditional(type: PC.self, to: (P & AnyObject).self, expected: true)) // CHECK-ONONE: true print(nongenericAnyAsConditionalPAndAnyObjectConforming(type: PCSub.self)) // CHECK: true print(genericAnyAsConditional(type: PCSub.self, to: (P & AnyObject).self, expected: true)) // CHECK-ONONE: true // CHECK-LABEL: casting types to protocol & class existentials: print("casting types to protocol & class existentials:") print(nongenericAnyIsPAndPCSubConforming(type: PS.self)) // CHECK: false print(genericAnyIs(type: PS.self, to: (P & PCSub).self, expected: false)) // CHECK: false print(nongenericAnyIsPAndPCSubConforming(type: PE.self)) // CHECK: false print(genericAnyIs(type: PE.self, to: (P & PCSub).self, expected: false)) // CHECK: false //print(nongenericAnyIsPAndPCSubConforming(type: PC.self)) // CHECK-SR-11565: false -- FIXME: reenable this when SR-11565 is fixed print(genericAnyIs(type: PC.self, to: (P & PCSub).self, expected: false)) // CHECK: false print(nongenericAnyIsPAndPCSubConforming(type: PCSub.self)) // CHECK: true print(genericAnyIs(type: PCSub.self, to: (P & PCSub).self, expected: true)) // CHECK-ONONE: true print(nongenericAnyAsConditionalPAndPCSubConforming(type: PS.self)) // CHECK: false print(genericAnyAsConditional(type: PS.self, to: (P & PCSub).self, expected: false)) // CHECK: false print(nongenericAnyAsConditionalPAndPCSubConforming(type: PE.self)) // CHECK: false print(genericAnyAsConditional(type: PE.self, to: (P & PCSub).self, expected: false)) // CHECK: false //print(nongenericAnyAsConditionalPAndPCSubConforming(type: PC.self)) // CHECK-SR-11565: false -- FIXME: reenable this when SR-11565 is fixed print(genericAnyAsConditional(type: PC.self, to: (P & PCSub).self, expected: false)) // CHECK: false print(nongenericAnyAsConditionalPAndPCSubConforming(type: PCSub.self)) // CHECK: true print(genericAnyAsConditional(type: PCSub.self, to: (P & PCSub).self, expected: true)) // CHECK-ONONE: true // CHECK-LABEL: type comparisons: print("type comparisons:\n") print(allMetasToAllMetas(Int.self, Int.self)) // CHECK: true print(allMetasToAllMetas(Int.self, Float.self)) // CHECK: false print(allMetasToAllMetas(C.self, C.self)) // CHECK: true print(allMetasToAllMetas(D.self, C.self)) // CHECK: true print(allMetasToAllMetas(C.self, D.self)) // CHECK: false print(C.self is D.Type) // CHECK: false print((D.self as C.Type) is D.Type) // CHECK: true let t: Any.Type = type(of: 1 as Any) print(t is Int.Type) // CHECK: true print(t is Float.Type) // CHECK: false print(t is C.Type) // CHECK: false let u: Any.Type = type(of: (D() as Any)) print(u is C.Type) // CHECK: true print(u is D.Type) // CHECK: true print(u is E.Type) // CHECK: false print(u is Int.Type) // CHECK: false // FIXME: Can't spell AnyObject.Protocol // CHECK-LABEL: AnyObject casts: print("AnyObject casts:") print(allToAll(C(), AnyObject.self)) // CHECK: true // On Darwin, the object will be the ObjC-runtime-class object; // out of Darwin, this should not succeed. print(allToAll(type(of: C()), AnyObject.self)) // CHECK-objc: true // CHECK-native: false // Bridging // NSNumber on Darwin, __SwiftValue on Linux. print(allToAll(0, AnyObject.self)) // CHECK: true // This will get bridged using __SwiftValue. struct NotBridged { var x: Int } print(allToAll(NotBridged(x: 0), AnyObject.self)) // CHECK: true #if canImport(Foundation) // This requires Foundation (for NSCopying): print(allToAll(NotBridged(x: 0), NSCopying.self)) // CHECK-objc: true #endif // On Darwin, these casts fail (intentionally) even though __SwiftValue does // technically conform to these protocols through NSObject. // Off Darwin, it should not conform at all. print(allToAll(NotBridged(x: 0), CustomStringConvertible.self)) // CHECK: false print(allToAll(NotBridged(x: 0), (AnyObject & CustomStringConvertible).self)) // CHECK: false #if canImport(Foundation) // This requires Foundation (for NSArray): // // rdar://problem/19482567 // func swiftOptimizesThisFunctionIncorrectly() -> Bool { let anArray = [] as NSArray if let whyThisIsNeverExecutedIfCalledFromFunctionAndNotFromMethod = anArray as? [NSObject] { return true } return false } let result = swiftOptimizesThisFunctionIncorrectly() print("Bridge cast result: \(result)") // CHECK-NEXT-objc: Bridge cast result: true #endif
8b054f4aa632e91cb953536fd0c6188f
37.562842
141
0.712767
false
false
false
false
swiftcodex/Swift-Radio-Pro
refs/heads/master
SwiftRadio/UIImageView+Download.swift
mit
1
// // UIImageView+AlbumArtDownload.swift // Swift Radio // // Created by Matthew Fecher on 3/31/15. // Copyright (c) 2015 MatthewFecher.com. All rights reserved. // import UIKit extension UIImageView { func loadImageWithURL(url: URL, callback: @escaping (UIImage) -> ()) { let session = URLSession.shared let downloadTask = session.downloadTask(with: url, completionHandler: { [weak self] url, response, error in if error == nil && url != nil { if let data = NSData(contentsOf: url!) { if let image = UIImage(data: data as Data) { DispatchQueue.main.async(execute: { if let strongSelf = self { strongSelf.image = image callback(image) } }) } } } }) downloadTask.resume() } }
c7f4cba82ad3213e9525a1447bbbf2c1
26.923077
79
0.442608
false
false
false
false
StormXX/STTableBoard
refs/heads/master
STTableBoard/Views/BoardMenuTableViewController.swift
cc0-1.0
1
// // BoardMenuTableViewController.swift // STTableBoard // // Created by DangGu on 16/1/7. // Copyright © 2016年 StormXX. All rights reserved. // import UIKit class BoardMenuTableViewController: UITableViewController { override init(style: UITableViewStyle) { super.init(style: style) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: "MenuCell") tableView.tableFooterView = UIView() tableView.separatorColor = UIColor(white: 221 / 255.0, alpha: 1) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50.0 } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MenuCell", for: indexPath) configCell(cell, indexPath: indexPath) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard let boardMenu = self.navigationController as? BoardMenu, let tableBoard = boardMenu.tableBoard else { return } if isEditBoardTitleCell(indexPath) { if let canEditTitle = tableBoard.delegate?.tableBoard(tableBoard, canEditBoardTitleAt: boardMenu.boardIndex) , canEditTitle { let textViewController = BoardMenuTextViewController() textViewController.boardTitle = boardMenu.boardMenuTitle self.navigationController?.pushViewController(textViewController, animated: true) } else { return } } else if isDeleteBoardCell(indexPath) { boardMenu.boardMenuDelegate?.boardMenu(boardMenu, boardMenuHandleType: BoardMenuHandleType.boardDeleted, userInfo: nil) } else { } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension BoardMenuTableViewController { fileprivate func configCell(_ cell: UITableViewCell, indexPath: IndexPath) { switch (indexPath.section, indexPath.row) { case (0,0): cell.textLabel?.text = localizedString["STTableBoard.EditBoardNameCell.Title"] cell.imageView?.image = UIImage(named: "BoardMenu_Icon_Edit", in: currentBundle, compatibleWith: nil) cell.accessoryType = .disclosureIndicator case (0,1): cell.textLabel?.text = localizedString["STTableBoard.DeleteBoardCell.Title"] cell.imageView?.image = UIImage(named: "BoardMenu_Icon_Delete", in: currentBundle, compatibleWith: nil) cell.accessoryType = .none default: break } } func isEditBoardTitleCell(_ indexPath: IndexPath) -> Bool { return indexPath.section == 0 && indexPath.row == 0 } func isDeleteBoardCell(_ indexPath: IndexPath) -> Bool { return indexPath.section == 0 && indexPath.row == 1 } }
056253396cecd72511b89b839789d1fd
35.808081
137
0.667947
false
false
false
false
huonw/swift
refs/heads/master
stdlib/public/core/StringCharacterView.swift
apache-2.0
1
//===--- StringCharacterView.swift - String's Collection of Characters ----===// // // 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 // //===----------------------------------------------------------------------===// // // String is-not-a Sequence or Collection, but it exposes a // collection of characters. // //===----------------------------------------------------------------------===// // FIXME(ABI)#70 : The character string view should have a custom iterator type // to allow performance optimizations of linear traversals. import SwiftShims extension String { @available(swift, deprecated: 3.2, message: "Please use String or Substring directly") public typealias CharacterView = _CharacterView /// A view of a string's contents as a collection of characters. /// /// In Swift, every string provides a view of its contents as characters. In /// this view, many individual characters---for example, "é", "김", and /// "🇮🇳"---can be made up of multiple Unicode scalar values. These scalar /// values are combined by Unicode's boundary algorithms into *extended /// grapheme clusters*, represented by the `Character` type. Each element of /// a `CharacterView` collection is a `Character` instance. /// /// let flowers = "Flowers 💐" /// for c in flowers.characters { /// print(c) /// } /// // F /// // l /// // o /// // w /// // e /// // r /// // s /// // /// // 💐 /// /// You can convert a `String.CharacterView` instance back into a string /// using the `String` type's `init(_:)` initializer. /// /// let name = "Marie Curie" /// if let firstSpace = name.characters.firstIndex(of: " ") { /// let firstName = String(name.characters[..<firstSpace]) /// print(firstName) /// } /// // Prints "Marie" @_fixed_layout // FIXME(sil-serialize-all) public struct _CharacterView { @usableFromInline internal var _base: String /// The offset of this view's `_guts` from an original guts. This works /// around the fact that `_StringGuts` is always zero-indexed. /// `_baseOffset` should be subtracted from `Index.encodedOffset` before /// that value is used as a `_guts` index. @usableFromInline internal var _baseOffset: Int /// Creates a view of the given string. @inlinable // FIXME(sil-serialize-all) public init(_ text: String) { self._base = text self._baseOffset = 0 } @inlinable // FIXME(sil-serialize-all) public // @testable init(_ _base: String, baseOffset: Int = 0) { self._base = _base self._baseOffset = baseOffset } } /// A view of the string's contents as a collection of characters. @_transparent // FIXME(sil-serialize-all) public var _characters: _CharacterView { get { return _CharacterView(self) } set { self = newValue._base } } /// A view of the string's contents as a collection of characters. @inlinable // FIXME(sil-serialize-all) @available(swift, deprecated: 3.2, message: "Please use String or Substring directly") public var characters: CharacterView { get { return _characters } set { _characters = newValue } } /// Applies the given closure to a mutable view of the string's characters. /// /// Do not use the string that is the target of this method inside the /// closure passed to `body`, as it may not have its correct value. Instead, /// use the closure's `CharacterView` argument. /// /// This example below uses the `withMutableCharacters(_:)` method to /// truncate the string `str` at the first space and to return the remainder /// of the string. /// /// var str = "All this happened, more or less." /// let afterSpace = str.withMutableCharacters { /// chars -> String.CharacterView in /// if let i = chars.firstIndex(of: " ") { /// let result = chars[chars.index(after: i)...] /// chars.removeSubrange(i...) /// return result /// } /// return String.CharacterView() /// } /// /// print(str) /// // Prints "All" /// print(String(afterSpace)) /// // Prints "this happened, more or less." /// /// - Parameter body: A closure that takes a character view as its argument. /// If `body` has a return value, that value is also used as the return /// value for the `withMutableCharacters(_:)` method. The `CharacterView` /// argument is valid only for the duration of the closure's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable // FIXME(sil-serialize-all) @available(swift, deprecated: 3.2, message: "Please mutate String or Substring directly") public mutating func withMutableCharacters<R>( _ body: (inout CharacterView) -> R ) -> R { // Naively mutating self.characters forces multiple references to // exist at the point of mutation. Instead, temporarily move the // guts of this string into a CharacterView. var tmp = _CharacterView("") (_guts, tmp._base._guts) = (tmp._base._guts, _guts) let r = body(&tmp) (_guts, tmp._base._guts) = (tmp._base._guts, _guts) return r } /// Creates a string from the given character view. /// /// Use this initializer to recover a string after performing a collection /// slicing operation on a string's character view. /// /// let poem = """ /// 'Twas brillig, and the slithy toves / /// Did gyre and gimbal in the wabe: / /// All mimsy were the borogoves / /// And the mome raths outgrabe. /// """ /// let excerpt = String(poem.characters.prefix(22)) + "..." /// print(excerpt) /// // Prints "'Twas brillig, and the..." /// /// - Parameter characters: A character view to convert to a string. @inlinable // FIXME(sil-serialize-all) @available(swift, deprecated: 3.2, message: "Please use String or Substring directly") public init(_ characters: CharacterView) { self = characters._base } } extension String._CharacterView : _SwiftStringView { @inlinable // FIXME(sil-serialize-all) internal var _persistentContent : String { return _base } @inlinable // FIXME(sil-serialize-all) internal var _wholeString : String { return _base } @inlinable // FIXME(sil-serialize-all) internal var _encodedOffsetRange : Range<Int> { return _base._encodedOffsetRange } } extension String._CharacterView { @inlinable // FIXME(sil-serialize-all) internal var _guts: _StringGuts { return _base._guts } } extension String._CharacterView { internal typealias UnicodeScalarView = String.UnicodeScalarView @inlinable // FIXME(sil-serialize-all) internal var unicodeScalars: UnicodeScalarView { return UnicodeScalarView(_base._guts, coreOffset: _baseOffset) } } /// `String.CharacterView` is a collection of `Character`. extension String._CharacterView : BidirectionalCollection { public typealias Index = String.Index public typealias IndexDistance = String.IndexDistance /// Translates a view index into an index in the underlying base string using /// this view's `_baseOffset`. @inlinable // FIXME(sil-serialize-all) internal func _toBaseIndex(_ index: Index) -> Index { return String.Index(from: index, adjustingEncodedOffsetBy: -_baseOffset) } /// Translates an index in the underlying base string into a view index using /// this view's `_baseOffset`. @inlinable // FIXME(sil-serialize-all) internal func _toViewIndex(_ index: Index) -> Index { return String.Index(from: index, adjustingEncodedOffsetBy: _baseOffset) } /// The position of the first character in a nonempty character view. /// /// In an empty character view, `startIndex` is equal to `endIndex`. @inlinable // FIXME(sil-serialize-all) public var startIndex: Index { return _toViewIndex(_base.startIndex) } /// A character view's "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// In an empty character view, `endIndex` is equal to `startIndex`. @inlinable // FIXME(sil-serialize-all) public var endIndex: Index { return _toViewIndex(_base.endIndex) } /// Returns the next consecutive position after `i`. /// /// - Precondition: The next position is valid. @inlinable // FIXME(sil-serialize-all) public func index(after i: Index) -> Index { return _toViewIndex(_base.index(after: _toBaseIndex(i))) } /// Returns the previous consecutive position before `i`. /// /// - Precondition: The previous position is valid. @inlinable // FIXME(sil-serialize-all) public func index(before i: Index) -> Index { return _toViewIndex(_base.index(before: _toBaseIndex(i))) } /// Accesses the character at the given position. /// /// The following example searches a string's character view for a capital /// letter and then prints the character at the found index: /// /// let greeting = "Hello, friend!" /// if let i = greeting.characters.firstIndex(where: { "A"..."Z" ~= $0 }) { /// print("First capital letter: \(greeting.characters[i])") /// } /// // Prints "First capital letter: H" /// /// - Parameter position: A valid index of the character view. `position` /// must be less than the view's end index. @inlinable // FIXME(sil-serialize-all) public subscript(i: Index) -> Character { return _base[_toBaseIndex(i)] } } extension String._CharacterView : RangeReplaceableCollection { /// Creates an empty character view. @inlinable // FIXME(sil-serialize-all) public init() { self.init("") } /// Replaces the characters within the specified bounds with the given /// characters. /// /// Invalidates all indices with respect to the string. /// /// - Parameters: /// - bounds: The range of characters to replace. The bounds of the range /// must be valid indices of the character view. /// - newElements: The new characters to add to the view. /// /// - Complexity: O(*m*), where *m* is the combined length of the character /// view and `newElements`. If the call to `replaceSubrange(_:with:)` /// simply removes characters at the end of the view, the complexity is /// O(*n*), where *n* is equal to `bounds.count`. @inlinable // FIXME(sil-serialize-all) public mutating func replaceSubrange<C>( _ bounds: Range<Index>, with newElements: C ) where C : Collection, C.Element == Character { _base.replaceSubrange( _toBaseIndex(bounds.lowerBound) ..< _toBaseIndex(bounds.upperBound), with: newElements) } /// Reserves enough space in the character view's underlying storage to store /// the specified number of ASCII characters. /// /// Because each element of a character view can require more than a single /// ASCII character's worth of storage, additional allocation may be /// necessary when adding characters to the character view after a call to /// `reserveCapacity(_:)`. /// /// - Parameter n: The minimum number of ASCII character's worth of storage /// to allocate. /// /// - Complexity: O(*n*), where *n* is the capacity being reserved. public mutating func reserveCapacity(_ n: Int) { _base.reserveCapacity(n) } /// Appends the given character to the character view. /// /// - Parameter c: The character to append to the character view. public mutating func append(_ c: Character) { _base.append(c) } /// Appends the characters in the given sequence to the character view. /// /// - Parameter newElements: A sequence of characters. @inlinable // FIXME(sil-serialize-all) public mutating func append<S : Sequence>(contentsOf newElements: S) where S.Element == Character { _base.append(contentsOf: newElements) } } // Algorithms extension String._CharacterView { /// Accesses the characters in the given range. /// /// The example below uses this subscript to access the characters up to, but /// not including, the first comma (`","`) in the string. /// /// let str = "All this happened, more or less." /// let i = str.characters.firstIndex(of: ",")! /// let substring = str.characters[str.characters.startIndex ..< i] /// print(String(substring)) /// // Prints "All this happened" /// /// - Complexity: O(*n*) if the underlying string is bridged from /// Objective-C, where *n* is the length of the string; otherwise, O(1). @available(swift, deprecated: 3.2, message: "Please use String or Substring directly") public subscript(bounds: Range<Index>) -> String.CharacterView { let offsetRange: Range<Int> = _toBaseIndex(bounds.lowerBound).encodedOffset ..< _toBaseIndex(bounds.upperBound).encodedOffset return String.CharacterView( String(_base._guts._extractSlice(offsetRange)), baseOffset: bounds.lowerBound.encodedOffset) } }
05eb156814237af085a34ecc5287a0e2
34.762667
81
0.645067
false
false
false
false
6ag/AppScreenshots
refs/heads/master
AppScreenshots/Classes/Module/Home/Controller/JFHomeViewController.swift
mit
1
// // JFHomeViewController.swift // AppScreenshots // // Created by zhoujianfeng on 2017/2/1. // Copyright © 2017年 zhoujianfeng. All rights reserved. // import UIKit import SnapKit fileprivate let HomeItemId = "HomeItemId" class JFHomeViewController: UIViewController { /// 素材模型集合 let materialList = JFMaterial.getMaterialList() override func viewDidLoad() { super.viewDidLoad() prepareUI() } // MARK: - 懒加载UI /// 导航视图 fileprivate lazy var navigationView: UIImageView = { let imageView = UIImageView(image: UIImage(named: "nav_bg")) return imageView }() /// 列表容器视图 fileprivate lazy var containerView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: HomeItemWidth, height: HomeItemHeight) layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = layoutVertical(iPhone6: 8) layout.sectionInset = UIEdgeInsets( top: layoutVertical(iPhone6: 4), left: layoutHorizontal(iPhone6: 4), bottom: layoutVertical(iPhone6: 4), right: layoutHorizontal(iPhone6: 4)) let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.dataSource = self collectionView.delegate = self collectionView.backgroundColor = BACKGROUND_COLOR collectionView.contentInset = UIEdgeInsets( top: layoutVertical(iPhone6: 8), left: layoutHorizontal(iPhone6: 4), bottom: layoutVertical(iPhone6: 4), right: layoutHorizontal(iPhone6: 4)) collectionView.register(JFHomeCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: HomeItemId) return collectionView }() } // MARK: - 准备节目 extension JFHomeViewController { /// 准备UI fileprivate func prepareUI() { view.backgroundColor = BACKGROUND_COLOR view.addSubview(navigationView) view.addSubview(containerView) navigationView.snp.makeConstraints { (make) in make.left.top.right.equalTo(0) make.height.equalTo(layoutVertical(iPhone6: 44) + STATUS_HEIGHT) } containerView.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(0) make.top.equalTo(navigationView.snp.bottom) } } } // MARK: - UICollectionViewDelegate, UICollectionViewDataSource extension JFHomeViewController: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return materialList.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeItemId, for: indexPath) as! JFHomeCollectionViewCell cell.material = materialList[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // 转换坐标系 let item = collectionView.dequeueReusableCell(withReuseIdentifier: HomeItemId, for: indexPath) as! JFHomeCollectionViewCell let rect = item.convert(item.frame, to: view) // 计算item相对于窗口的frame let x = indexPath.item % 2 == 0 ? rect.origin.x : rect.origin.x / 2 + layoutHorizontal(iPhone6: 4) let y = layoutVertical(iPhone6: 44) + STATUS_HEIGHT + CGFloat(indexPath.item / 2) * (rect.size.height + layoutVertical(iPhone6: 8)) - collectionView.contentOffset.y + layoutVertical(iPhone6: 4) let width = rect.size.width let height = rect.size.height let material = materialList[indexPath.item] let tempImageView = UIImageView() tempImageView.image = UIImage(contentsOfFile: Bundle.main.path(forResource: "\(material.listImageName ?? "")_1.\(NSLocalizedString("photo_suffix", comment: ""))", ofType: nil) ?? "") tempImageView.frame = CGRect(x: x, y: y, width: width, height: height) UIApplication.shared.keyWindow?.addSubview(tempImageView) UIView.animate(withDuration: 0.5, animations: { tempImageView.frame = CGRect( x: layoutHorizontal(iPhone6: 79.5), y: layoutVertical(iPhone6: 225) + STATUS_HEIGHT, width: layoutHorizontal(iPhone6: 56), height: layoutVertical(iPhone6: 100)) }) { (_) in tempImageView.removeFromSuperview() } // 素材参数模型集合,创建一个新的集合。防止对原集合修改 var materialParameterList = [JFMaterialParameter]() for materialParameter in material.materialParameterList ?? [JFMaterialParameter]() { materialParameterList.append(materialParameter.copy() as! JFMaterialParameter) } let settingVc = JFSettingViewController() settingVc.materialParameterList = materialParameterList settingVc.transitioningDelegate = self settingVc.modalPresentationStyle = .custom present(settingVc, animated: true) { } } } // MARK: - 栏目管理自定义转场动画事件 extension JFHomeViewController: UIViewControllerTransitioningDelegate { func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { return JFPresentationController(presentedViewController: presented, presenting: presenting) } func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return JFPopoverModalAnimation() } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return JFPopoverDismissAnimation() } }
9b55429cfceca0549ef6571f935d0dec
37.037267
190
0.665741
false
false
false
false
codelynx/silvershadow
refs/heads/master
Silvershadow/Canvas.swift
mit
1
// // Canvas.swift // Silvershadow // // Created by Kaz Yoshikawa on 12/28/16. // Copyright © 2016 Electricwoods LLC. All rights reserved. // import MetalKit import GLKit #if os(iOS) import UIKit #elseif os(macOS) import Cocoa #endif // Canvas // // Canvas is designed for rendering on offscreen bitmap target. Whereas, Scene is for rendering // on screen (MTKView) directly. Beaware of content size affects big impact to the memory usage. // extension MTLTextureDescriptor { static func texture2DDescriptor(size: CGSize, mipmapped: Bool, usage: MTLTextureUsage = []) -> MTLTextureDescriptor { let desc = texture2DDescriptor(pixelFormat: .`default`, width: Int(size.width), height: Int(size.height), mipmapped: mipmapped) desc.usage = usage return desc } } extension MTLDevice { func makeTexture2D(size: CGSize, mipmapped: Bool, usage: MTLTextureUsage) -> MTLTexture { return makeTexture(descriptor: .texture2DDescriptor(size: size, mipmapped: mipmapped, usage: usage))! } } class Canvas: Scene { // master texture of canvas lazy var canvasTexture: MTLTexture = { return self.device.makeTexture2D(size: self.contentSize, mipmapped: self.mipmapped, usage: [.shaderRead, .shaderWrite, .renderTarget]) }() lazy var canvasRenderer: ImageRenderer = { return self.device.renderer() }() fileprivate (set) var canvasLayers: [CanvasLayer] var overlayCanvasLayer: CanvasLayer? { didSet { overlayCanvasLayer?.canvas = self setNeedsDisplay() } } override init?(device: MTLDevice, contentSize: CGSize) { canvasLayers = [] super.init(device: device, contentSize: contentSize) } override func didMove(to renderView: RenderView) { super.didMove(to: renderView) } lazy var sublayerTexture: MTLTexture = { return self.device.makeTexture2D(size: self.contentSize, mipmapped: self.mipmapped, usage: [.shaderRead, .renderTarget]) }() lazy var subcomandQueue: MTLCommandQueue = { return self.device.makeCommandQueue()! }() override func update() { let date = Date() defer { Swift.print("Canvas: update", -date.timeIntervalSinceNow * 1000, " ms") } let commandQueue = subcomandQueue let canvasTexture = self.canvasTexture let renderPassDescriptor = MTLRenderPassDescriptor() renderPassDescriptor.colorAttachments[0].texture = canvasTexture renderPassDescriptor.colorAttachments[0].clearColor = .Red renderPassDescriptor.colorAttachments[0].storeAction = .store // clear canvas texture renderPassDescriptor.colorAttachments[0].loadAction = .clear let commandBuffer = commandQueue.makeCommandBuffer()! let commandEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor)! commandEncoder.endEncoding() commandBuffer.commit() renderPassDescriptor.colorAttachments[0].loadAction = .load // build an image per layer then flatten that image to the canvas texture let subtexture = self.sublayerTexture let subtransform = GLKMatrix4(transform) let subrenderPassDescriptor = MTLRenderPassDescriptor() subrenderPassDescriptor.colorAttachments[0].texture = subtexture subrenderPassDescriptor.colorAttachments[0].clearColor = .init() subrenderPassDescriptor.colorAttachments[0].storeAction = .store for canvasLayer in canvasLayers where !canvasLayer.isHidden { // clear subtexture subrenderPassDescriptor.colorAttachments[0].loadAction = .clear let commandBuffer = commandQueue.makeCommandBuffer()! let commandEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: subrenderPassDescriptor)! commandEncoder.endEncoding() commandBuffer.commit() subrenderPassDescriptor.colorAttachments[0].loadAction = .load let subrenderContext = RenderContext(renderPassDescriptor: subrenderPassDescriptor, commandQueue: commandQueue, contentSize: contentSize, deviceSize: contentSize, transform: subtransform) // render a layer canvasLayer.render(context: subrenderContext) // flatten image let renderContext = RenderContext(renderPassDescriptor: renderPassDescriptor, commandQueue: commandQueue, contentSize: contentSize, deviceSize: contentSize, transform: .identity) renderContext.render(texture: subtexture, in: Rect(-1, -1, 2, 2)) } // let commandBuffer = commandQueue.makeCommandBuffer() // commandBuffer.commit() // commandBuffer.waitUntilCompleted() // drawing in offscreen (canvasTexture) is done, setNeedsDisplay() } var threadSize: MTLSize { var size = 32 while (canvasTexture.width / size) * (canvasTexture.height / size) > 1024 { size *= 2 } return MTLSize(width: size, height: size, depth: 1) } var threadsPerThreadgroup: MTLSize { let threadSize = self.threadSize return MTLSize(width: canvasTexture.width / threadSize.width, height: canvasTexture.height / threadSize.height, depth: 1) } override func render(in context: RenderContext) { let date = Date() defer { Swift.print("Canvas: render", -date.timeIntervalSinceNow * 1000, " ms") } // build rendering overlay canvas layer //let commandBuffer = context.makeCommandBuffer() guard let overlayCanvasLayer = overlayCanvasLayer else { return } print("render: \(Date()), \(String(describing: overlayCanvasLayer.name))") let subtexture = self.sublayerTexture let subtransform = GLKMatrix4(transform) let subrenderPassDescriptor = MTLRenderPassDescriptor() subrenderPassDescriptor.colorAttachments[0].texture = subtexture subrenderPassDescriptor.colorAttachments[0].clearColor = .init() subrenderPassDescriptor.colorAttachments[0].loadAction = .clear subrenderPassDescriptor.colorAttachments[0].storeAction = .store // clear subtexture let commandBuffer = context.makeCommandBuffer() let commandEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: subrenderPassDescriptor)! commandEncoder.endEncoding() commandBuffer.commit() subrenderPassDescriptor.colorAttachments[0].loadAction = .load let subrenderContext = RenderContext(renderPassDescriptor: subrenderPassDescriptor, commandQueue: context.commandQueue, contentSize: contentSize, deviceSize: contentSize, transform: subtransform, zoomScale: 1) overlayCanvasLayer.render(context: subrenderContext) // render canvas texture canvasRenderer.renderTexture(context: context, texture: canvasTexture, in: Rect(bounds)) // render overlay canvas layer context.render(texture: subtexture, in: Rect(bounds)) } func addLayer(_ layer: CanvasLayer) { canvasLayers.append(layer) layer.didMoveTo(canvas: self) setNeedsUpdate() } func bringLayer(toFront: CanvasLayer) { assert(false, "not yet") } func sendLayer(toBack: CanvasLayer) { assert(false, "not yet") } } extension RangeReplaceableCollection where Iterator.Element : Equatable { mutating func remove(_ element: Iterator.Element) -> Index? { return firstIndex(of: element).map { self.remove(at: $0); return $0 } } } extension CanvasLayer { func removeFromCanvas() { _ = canvas?.canvasLayers.remove(self) } }
1bf2ad500127f9d7640eda3fa02c0ec6
29.352697
123
0.725906
false
false
false
false
brentdax/swift
refs/heads/master
stdlib/public/core/StringBridge.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims #if _runtime(_ObjC) // Swift's String bridges NSString via this protocol and these // variables, allowing the core stdlib to remain decoupled from // Foundation. /// Effectively an untyped NSString that doesn't require foundation. public typealias _CocoaString = AnyObject @inlinable // FIXME(sil-serialize-all) public // @testable func _stdlib_binary_CFStringCreateCopy( _ source: _CocoaString ) -> _CocoaString { let result = _swift_stdlib_CFStringCreateCopy(nil, source) as AnyObject return result } @inlinable // FIXME(sil-serialize-all) @_effects(readonly) public // @testable func _stdlib_binary_CFStringGetLength( _ source: _CocoaString ) -> Int { return _swift_stdlib_CFStringGetLength(source) } @inlinable // FIXME(sil-serialize-all) public // @testable func _stdlib_binary_CFStringGetCharactersPtr( _ source: _CocoaString ) -> UnsafeMutablePointer<UTF16.CodeUnit>? { return UnsafeMutablePointer( mutating: _swift_stdlib_CFStringGetCharactersPtr(source)) } /// Loading Foundation initializes these function variables /// with useful values /// Copies the entire contents of a _CocoaString into contiguous /// storage of sufficient capacity. @usableFromInline // FIXME(sil-serialize-all) @inline(never) // Hide the CF dependency internal func _cocoaStringReadAll( _ source: _CocoaString, _ destination: UnsafeMutablePointer<UTF16.CodeUnit> ) { _swift_stdlib_CFStringGetCharacters( source, _swift_shims_CFRange( location: 0, length: _swift_stdlib_CFStringGetLength(source)), destination) } /// Copies a slice of a _CocoaString into contiguous storage of /// sufficient capacity. @usableFromInline // FIXME(sil-serialize-all) @inline(never) // Hide the CF dependency internal func _cocoaStringCopyCharacters( from source: _CocoaString, range: Range<Int>, into destination: UnsafeMutablePointer<UTF16.CodeUnit> ) { _swift_stdlib_CFStringGetCharacters( source, _swift_shims_CFRange(location: range.lowerBound, length: range.count), destination) } @usableFromInline // FIXME(sil-serialize-all) @inline(never) // Hide the CF dependency internal func _cocoaStringSlice( _ target: _CocoaString, _ bounds: Range<Int> ) -> _CocoaString { let cfSelf: _swift_shims_CFStringRef = target _sanityCheck( _swift_stdlib_CFStringGetCharactersPtr(cfSelf) == nil, "Known contiguously stored strings should already be converted to Swift") let cfResult = _swift_stdlib_CFStringCreateWithSubstring( nil, cfSelf, _swift_shims_CFRange( location: bounds.lowerBound, length: bounds.count)) as AnyObject return cfResult } @usableFromInline // FIXME(sil-serialize-all) @inline(never) // Hide the CF dependency internal func _cocoaStringSubscript( _ target: _CocoaString, _ position: Int ) -> UTF16.CodeUnit { let cfSelf: _swift_shims_CFStringRef = target _sanityCheck(_swift_stdlib_CFStringGetCharactersPtr(cfSelf) == nil, "Known contiguously stored strings should already be converted to Swift") return _swift_stdlib_CFStringGetCharacterAtIndex(cfSelf, position) } // // Conversion from NSString to Swift's native representation // @inlinable // FIXME(sil-serialize-all) internal var kCFStringEncodingASCII : _swift_shims_CFStringEncoding { @inline(__always) get { return 0x0600 } } @inlinable // FIXME(sil-serialize-all) internal var kCFStringEncodingUTF8 : _swift_shims_CFStringEncoding { @inline(__always) get { return 0x8000100 } } @usableFromInline // @opaque internal func _bridgeASCIICocoaString( _ cocoa: _CocoaString, intoUTF8 bufPtr: UnsafeMutableRawBufferPointer ) -> Int? { let ptr = bufPtr.baseAddress._unsafelyUnwrappedUnchecked.assumingMemoryBound( to: UInt8.self) let length = _stdlib_binary_CFStringGetLength(cocoa) var count = 0 let numCharWritten = _swift_stdlib_CFStringGetBytes( cocoa, _swift_shims_CFRange(location: 0, length: length), kCFStringEncodingUTF8, 0, 0, ptr, bufPtr.count, &count) return length == numCharWritten ? count : nil } @usableFromInline internal func _bridgeToCocoa(_ small: _SmallUTF8String) -> _CocoaString { return small.withUTF8CodeUnits { bufPtr in return _swift_stdlib_CFStringCreateWithBytes( nil, bufPtr.baseAddress._unsafelyUnwrappedUnchecked, bufPtr.count, small.isASCII ? kCFStringEncodingASCII : kCFStringEncodingUTF8, 0) as AnyObject } } internal func _getCocoaStringPointer( _ cfImmutableValue: _CocoaString ) -> (UnsafeRawPointer?, isUTF16: Bool) { // Look first for null-terminated ASCII // Note: the code in clownfish appears to guarantee // nul-termination, but I'm waiting for an answer from Chris Kane // about whether we can count on it for all time or not. let nulTerminatedASCII = _swift_stdlib_CFStringGetCStringPtr( cfImmutableValue, kCFStringEncodingASCII) // start will hold the base pointer of contiguous storage, if it // is found. var start: UnsafeRawPointer? let isUTF16 = (nulTerminatedASCII == nil) if isUTF16 { let utf16Buf = _swift_stdlib_CFStringGetCharactersPtr(cfImmutableValue) start = UnsafeRawPointer(utf16Buf) } else { start = UnsafeRawPointer(nulTerminatedASCII) } return (start, isUTF16: isUTF16) } @usableFromInline @inline(never) // Hide the CF dependency internal func _makeCocoaStringGuts(_ cocoaString: _CocoaString) -> _StringGuts { if let ascii = cocoaString as? _ASCIIStringStorage { return _StringGuts(_large: ascii) } else if let utf16 = cocoaString as? _UTF16StringStorage { return _StringGuts(_large: utf16) } else if let wrapped = cocoaString as? __NSContiguousString { return wrapped._guts } else if _isObjCTaggedPointer(cocoaString) { guard let small = _SmallUTF8String(_cocoaString: cocoaString) else { fatalError("Internal invariant violated: large tagged NSStrings") } return _StringGuts(small) } // "copy" it into a value to be sure nobody will modify behind // our backs. In practice, when value is already immutable, this // just does a retain. let immutableCopy = _stdlib_binary_CFStringCreateCopy(cocoaString) as AnyObject if _isObjCTaggedPointer(immutableCopy) { guard let small = _SmallUTF8String(_cocoaString: cocoaString) else { fatalError("Internal invariant violated: large tagged NSStrings") } return _StringGuts(small) } let (start, isUTF16) = _getCocoaStringPointer(immutableCopy) let length = _StringGuts.getCocoaLength( _unsafeBitPattern: Builtin.reinterpretCast(immutableCopy)) return _StringGuts( _largeNonTaggedCocoaObject: immutableCopy, count: length, isSingleByte: !isUTF16, start: start) } extension String { public // SPI(Foundation) init(_cocoaString: AnyObject) { self._guts = _makeCocoaStringGuts(_cocoaString) } } // At runtime, this class is derived from `__SwiftNativeNSStringBase`, // which is derived from `NSString`. // // The @_swift_native_objc_runtime_base attribute // This allows us to subclass an Objective-C class and use the fast Swift // memory allocator. // // NOTE: older runtimes called this _SwiftNativeNSString. The two must // coexist, so it was renamed. The old name must not be used in the new // runtime. @_fixed_layout // FIXME(sil-serialize-all) @objc @_swift_native_objc_runtime_base(__SwiftNativeNSStringBase) public class __SwiftNativeNSString { @usableFromInline // FIXME(sil-serialize-all) @objc internal init() {} deinit {} } /// A shadow for the "core operations" of NSString. /// /// Covers a set of operations everyone needs to implement in order to /// be a useful `NSString` subclass. @objc public protocol _NSStringCore : _NSCopying /* _NSFastEnumeration */ { // The following methods should be overridden when implementing an // NSString subclass. @objc(length) var length: Int { get } @objc(characterAtIndex:) func character(at index: Int) -> UInt16 // We also override the following methods for efficiency. @objc(getCharacters:range:) func getCharacters( _ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange) @objc(_fastCharacterContents) func _fastCharacterContents() -> UnsafePointer<UInt16>? } /// An `NSString` built around a slice of contiguous Swift `String` storage. /// /// NOTE: older runtimes called this _NSContiguousString. The two must /// coexist, so it was renamed. The old name must not be used in the new /// runtime. @_fixed_layout // FIXME(sil-serialize-all) public final class __NSContiguousString : __SwiftNativeNSString, _NSStringCore { public let _guts: _StringGuts @inlinable // FIXME(sil-serialize-all) public init(_ _guts: _StringGuts) { _sanityCheck(!_guts._isOpaque, "__NSContiguousString requires contiguous storage") self._guts = _guts super.init() } @inlinable // FIXME(sil-serialize-all) public init(_unmanaged guts: _StringGuts) { _sanityCheck(!guts._isOpaque, "__NSContiguousString requires contiguous storage") if guts.isASCII { self._guts = _StringGuts(_large: guts._unmanagedASCIIView) } else { self._guts = _StringGuts(_large: guts._unmanagedUTF16View) } super.init() } @inlinable // FIXME(sil-serialize-all) public init(_unmanaged guts: _StringGuts, range: Range<Int>) { _sanityCheck(!guts._isOpaque, "__NSContiguousString requires contiguous storage") if guts.isASCII { self._guts = _StringGuts(_large: guts._unmanagedASCIIView[range]) } else { self._guts = _StringGuts(_large: guts._unmanagedUTF16View[range]) } super.init() } @usableFromInline // FIXME(sil-serialize-all) @objc init(coder aDecoder: AnyObject) { _sanityCheckFailure("init(coder:) not implemented for __NSContiguousString") } @inlinable // FIXME(sil-serialize-all) deinit {} @inlinable @objc(length) public var length: Int { return _guts.count } @inlinable @objc(characterAtIndex:) public func character(at index: Int) -> UInt16 { defer { _fixLifetime(self) } return _guts.codeUnit(atCheckedOffset: index) } @inlinable @objc(getCharacters:range:) public func getCharacters( _ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange) { _precondition(aRange.location >= 0 && aRange.length >= 0) let range: Range<Int> = aRange.location ..< aRange.location + aRange.length _precondition(range.upperBound <= Int(_guts.count)) if _guts.isASCII { _guts._unmanagedASCIIView[range]._copy( into: UnsafeMutableBufferPointer(start: buffer, count: range.count)) } else { _guts._unmanagedUTF16View[range]._copy( into: UnsafeMutableBufferPointer(start: buffer, count: range.count)) } _fixLifetime(self) } @inlinable @objc(_fastCharacterContents) public func _fastCharacterContents() -> UnsafePointer<UInt16>? { guard !_guts.isASCII else { return nil } return _guts._unmanagedUTF16View.start } @objc(copyWithZone:) public func copy(with zone: _SwiftNSZone?) -> AnyObject { // Since this string is immutable we can just return ourselves. return self } /// The caller of this function guarantees that the closure 'body' does not /// escape the object referenced by the opaque pointer passed to it or /// anything transitively reachable form this object. Doing so /// will result in undefined behavior. @inlinable // FIXME(sil-serialize-all) @_semantics("self_no_escaping_closure") func _unsafeWithNotEscapedSelfPointer<Result>( _ body: (OpaquePointer) throws -> Result ) rethrows -> Result { let selfAsPointer = unsafeBitCast(self, to: OpaquePointer.self) defer { _fixLifetime(self) } return try body(selfAsPointer) } /// The caller of this function guarantees that the closure 'body' does not /// escape either object referenced by the opaque pointer pair passed to it or /// transitively reachable objects. Doing so will result in undefined /// behavior. @inlinable // FIXME(sil-serialize-all) @_semantics("pair_no_escaping_closure") func _unsafeWithNotEscapedSelfPointerPair<Result>( _ rhs: __NSContiguousString, _ body: (OpaquePointer, OpaquePointer) throws -> Result ) rethrows -> Result { let selfAsPointer = unsafeBitCast(self, to: OpaquePointer.self) let rhsAsPointer = unsafeBitCast(rhs, to: OpaquePointer.self) defer { _fixLifetime(self) _fixLifetime(rhs) } return try body(selfAsPointer, rhsAsPointer) } } extension String { /// Same as `_bridgeToObjectiveC()`, but located inside the core standard /// library. @inlinable // FIXME(sil-serialize-all) public func _stdlib_binary_bridgeToObjectiveCImpl() -> AnyObject { if _guts._isSmall { return _bridgeToCocoa(_guts._smallUTF8String) } if let cocoa = _guts._underlyingCocoaString { return cocoa } return __NSContiguousString(_guts) } @inline(never) // Hide the CF dependency public func _bridgeToObjectiveCImpl() -> AnyObject { return _stdlib_binary_bridgeToObjectiveCImpl() } } // Called by the SwiftObject implementation to get the description of a value // as an NSString. @_silgen_name("swift_stdlib_getDescription") public func _getDescription<T>(_ x: T) -> AnyObject { return String(reflecting: x)._bridgeToObjectiveCImpl() } #else // !_runtime(_ObjC) @_fixed_layout // FIXME(sil-serialize-all) public class __SwiftNativeNSString { @usableFromInline // FIXME(sil-serialize-all) internal init() {} deinit {} } public protocol _NSStringCore: class {} #endif
3c76bc1738237daca9e626bfcdedbf20
31.263761
81
0.712945
false
false
false
false
tbaranes/SwiftyUtils
refs/heads/master
Tests/Protocols/Swift/OccupiableTests.swift
mit
1
// // Created by Tom Baranes on 24/11/15. // Copyright © 2015 Tom Baranes. All rights reserved. // import XCTest import SwiftyUtils final class OccupiableTests: XCTestCase { // MARK: - Life cycle override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } // MARK: - isEmpty func testStringIsEmptySuccess() { let string = "" XCTAssertTrue(string.isEmpty) } func testStringIsEmptyFailure() { let string = "stringNotEmpty" XCTAssertFalse(string.isEmpty) } func testArrayIsEmptySuccess() { let array: [Int] = [] XCTAssertTrue(array.isEmpty) } func testArrayIsEmptyFailure() { let array: [Int] = [1, 2, 3] XCTAssertFalse(array.isEmpty) } func testDictionaryIsEmptySuccess() { let dic: [String: Int] = [:] XCTAssertTrue(dic.isEmpty) } func testDictionaryIsEmptyFailure() { let dic: [String: Int] = ["1": 1, "2": 2, "3": 3] XCTAssertFalse(dic.isEmpty) } // MARK: - isNotEmpty func testStringIsNotEmptySuccess() { let string = "stringIsNotEmpty" XCTAssertTrue(string.isNotEmpty) } func testStringIsNotEmptyFailure() { let string = "" XCTAssertFalse(string.isNotEmpty) } func testArrayIsNotEmptySuccess() { let array: [Int] = [1, 2, 3] XCTAssertTrue(array.isNotEmpty) } func testArrayIsNotEmptyFailure() { let array: [Int] = [] XCTAssertFalse(array.isNotEmpty) } func testDictionaryIsNotEmptySuccess() { let dic: [String: Int] = ["1": 1, "2": 2, "3": 3] XCTAssertTrue(dic.isNotEmpty) } func testDictionaryIsNotEmptyFailure() { let dic: [String: Int] = [:] XCTAssertFalse(dic.isNotEmpty) } // MARK: - Optional isNilOrEmpty func testOptionalIsEmptySuccess() { var string: String? = "" XCTAssertTrue(string.isNilOrEmpty) string = nil XCTAssertTrue(string.isNilOrEmpty) } func testOptionalIsEmptyFailure() { let string: String? = "stringNotEmpty" XCTAssertFalse(string.isNilOrEmpty) } func testIsNotNilNotEmpty() { let string: String? = "stringNotEmpty" XCTAssertTrue(string.isNotNilNotEmpty) } }
6538194508ebfd6a7b9a4eabeca8bacc
21.912621
57
0.602542
false
true
false
false
TBXark/Ruler
refs/heads/master
Ruler/Modules/Ruler/Views/PopButton.swift
mit
1
// // PopButton.swift // Ruler // // Created by Tbxark on 25/09/2017. // Copyright © 2017 Tbxark. All rights reserved. // import UIKit extension UIButton { public convenience init(size: CGSize, image: UIImage?) { self.init(frame: CGRect(origin: CGPoint.zero, size: size)) setImage(image, for: .normal) setImage(image, for: .disabled) } public var disabledImage: UIImage? { get { return image(for: .disabled) } set { setImage(newValue, for: .disabled) } } public var normalImage: UIImage? { get { return image(for: .normal) } set { setImage(newValue, for: .normal) } } } class PopButton: UIControl { private(set) var isOn = false let buttonArray: [UIButton] init(buttons: UIButton...) { buttonArray = buttons let w = buttons.map({ $0.frame.width }).max() let h = buttons.map({ $0.frame.height }).max() super.init(frame: CGRect(x: 0, y: 0, width: w ?? 0, height: h ?? 0)) let p = CGPoint(x: frame.width/2, y: frame.height/2) for b in buttons { addSubview(b) b.center = p } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func show() { guard !isOn else { return } isOn = true var centerY = frame.height/2 var buttons = buttonArray let lastButton = buttons.removeLast() centerY -= lastButton.frame.height / 2 for btn in buttons.reversed() { centerY -= btn.frame.height + 10 UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: { btn.center.y = centerY }, completion: nil) } } func dismiss() { guard isOn else { return } isOn = false let p = CGPoint(x: frame.width/2, y: frame.height/2) for btn in buttonArray { UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: { btn.center = p }, completion: nil) } } override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { guard isOn, point.x >= 0 , point.x <= frame.width else { return super.hitTest(point, with: event) } for btn in buttonArray { guard btn.frame.contains(point) else { continue } return btn } return super.hitTest(point, with: event) } }
a2f635a945050418c9b9a1729b1d8fa0
26.747573
78
0.510847
false
false
false
false
Dagers/macGHCi
refs/heads/master
HaskellEditor/TerminalManager.swift
gpl-3.0
1
// // TerminalManager.swift // macGHCi // // Created by Daniel Strebinger on 21.02.17. // Copyright © 2017 Daniel Strebinger. All rights reserved. // import Foundation /** Represents the interaction with the console of the system. - Author: Daniel Strebinger - Version: 1.0 */ public class TerminalManager { /** Represents the reference to the process of the terminal. */ private let process : Process /** Represents the read pipe object. */ private let readPipe : Pipe /** Represents the write pipe object. */ private let writePipe : Pipe /** Represents the error pipe object. */ private let errorPipe : Pipe /** Represents the read stream. */ private var readStream : FileHandle /** Represents the write stream. */ private var writeStream : FileHandle /** Represents the error stream. */ private var errorStream : FileHandle /** Initializes a new instance of the ProcessInstance class. */ public init() { self.process = Process() self.readPipe = Pipe() self.writePipe = Pipe() self.errorPipe = Pipe() self.readStream = FileHandle() self.writeStream = FileHandle() self.errorStream = FileHandle() } /** Starts a process with command line arguments. */ public func start(_ command: String, args: [String]) { self.process.launchPath = command self.process.arguments = args self.process.standardOutput = self.readPipe self.process.standardInput = self.writePipe self.process.standardError = self.errorPipe self.errorStream = self.errorPipe.fileHandleForReading self.errorStream.waitForDataInBackgroundAndNotify() self.readStream = self.readPipe.fileHandleForReading self.readStream.waitForDataInBackgroundAndNotify() self.writeStream = self.writePipe.fileHandleForWriting NotificationCenter.default.addObserver(self, selector: #selector(receivedTerminalData(notification:)), name: NSNotification.Name.NSFileHandleDataAvailable, object: self.readStream) NotificationCenter.default.addObserver(self, selector: #selector(receivedTerminalData(notification:)), name: NSNotification.Name.NSFileHandleDataAvailable, object: self.errorStream) self.process.launch() } /** Writes to the terminal. */ public func write(_ command: String) { var computeCommand : String = command computeCommand.append("\n") self.writeStream.write(computeCommand.data(using: .utf8)!) } /** Stops the terminal. */ public func stop() { self.process.terminate() self.readStream.closeFile() self.writeStream.closeFile() } /** Interrupts the process for a specific time. */ public func interrupt() { self.process.interrupt() } /** Resumes the process. */ public func resume() { self.process.resume() } /** Represents the get data function for new data of the terminal. */ @objc private func receivedTerminalData(notification: Notification) { let fh : FileHandle = notification.object as! FileHandle var data : Data = fh.availableData if (data.count > 0) { fh.waitForDataInBackgroundAndNotify() let str = NSString(data: data, encoding: String.Encoding.utf8.rawValue) if (fh == self.readStream) { NotificationCenter.default.post(name:Notification.Name(rawValue:"OnNewDataReceived"), object: nil, userInfo: ["message": str!]) return } NotificationCenter.default.post(name:Notification.Name(rawValue:"OnErrorDataReceived"), object: nil, userInfo: ["message": str!]) } } }
78caba316c9aafa97748822776b693a2
26.124183
189
0.600723
false
false
false
false
CesarValiente/CursoSwiftUniMonterrey
refs/heads/master
week1/week1.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play /* This a long comment */ import UIKit var str : String = "Hello, Swift" var name = 10 var concatenation = str + String(name) let immutable = "cesar " var demo = immutable print(demo) print ("lalalla: \(immutable)" ) print(demo, immutable, " saasas ", " fin") print ("Sports list: \n\t1. ⚽️, \n\t2. 🏀, \n\t3. 🚗, \n\t4. 🏊") var x : Int = 35 var y = 3.1415926 print ("x: \(x)") var z : Double = 5.67 var f : Bool = true var numero : Int = 9 print (demo + String(numero)) var width = 1 var height_ = 2 let sum = width + height_ print (sum) let area : Int = width * height_ print ("Area: \(area)") let areaInMeters = Double(area) / 3.200 var chairs : Int = 15 print (chairs % 2) var numOperators = (200 + 200) - (((5 * 2) / 3) % 9) 200 + 200 400 - 5 395 * 2 790 / 3 263 % 9 var lives = 10 --lives -lives var isDaylight : Bool = true !isDaylight 874 % 10 let eur = 10 let dollar = 17.5 let conv : Double = Double(eur) * dollar let a = 5 var a2 = 2 let a3 = 3 print ("Result: \(a % ++a2 * a3)")
898a9eb85c44834cb7dd14aea2241548
11.975904
62
0.599814
false
false
false
false
edragoev1/pdfjet
refs/heads/master
Sources/Example_40/main.swift
mit
1
import Foundation import PDFjet /** * Example_40.swift * */ public class Example_40 { public init() throws { if let stream = OutputStream(toFileAtPath: "Example_40.pdf", append: false) { let pdf = PDF(stream) let page = Page(pdf, Letter.PORTRAIT) let f1 = Font(pdf, CoreFont.HELVETICA_BOLD) f1.setItalic(true) f1.setSize(10.0) let f2 = Font(pdf, CoreFont.HELVETICA_BOLD) f2.setItalic(true) f2.setSize(8.0) let chart = Chart(f1, f2) chart.setLocation(70.0, 50.0) chart.setSize(500.0, 300.0) chart.setTitle("Vertical Bar Chart Example") chart.setXAxisTitle("Bar Chart") chart.setYAxisTitle("Vertical") chart.setData(try getData()) chart.setDrawXAxisLabels(false) chart.drawOn(page) pdf.complete() } } public func getData() throws -> [[Point]] { var chartData = [[Point]]() var path1 = [Point]() var point = Point() point.setDrawPath() point.setX(15.0) point.setY(0.0) point.setShape(Point.INVISIBLE) point.setColor(Color.blue) point.setLineWidth(25.0) point.setText(" Vertical") point.setTextColor(Color.white) point.setTextDirection(90) path1.append(point) point = Point() point.setX(15.0) point.setY(45.0) point.setShape(Point.INVISIBLE) path1.append(point) var path2 = [Point]() point = Point() point.setDrawPath() point.setX(25.0) point.setY(0.0) point.setShape(Point.INVISIBLE) point.setColor(Color.green) point.setLineWidth(25.0) point.setText(" Bar") point.setTextColor(Color.white) point.setTextDirection(90) path2.append(point) point = Point() point.setX(25.0) point.setY(20.0) point.setShape(Point.INVISIBLE) path2.append(point) var path3 = [Point]() point = Point() point.setDrawPath() point.setX(35.0) point.setY(0.0) point.setShape(Point.INVISIBLE) point.setColor(Color.red) point.setLineWidth(25.0) point.setText(" Chart") point.setTextColor(Color.white) point.setTextDirection(90) path3.append(point) point = Point() point.setX(35.0) point.setY(31.0) point.setShape(Point.INVISIBLE) path3.append(point) var path4 = [Point]() point = Point() point.setDrawPath() point.setX(45.0) point.setY(0.0) point.setShape(Point.INVISIBLE) point.setColor(Color.gold) point.setLineWidth(25.0) point.setText(" Example") point.setTextColor(Color.black) point.setTextDirection(90) path4.append(point) point = Point() point.setX(45.0) point.setY(73.0) point.setShape(Point.INVISIBLE) path4.append(point) chartData.append(path1) chartData.append(path2) chartData.append(path3) chartData.append(path4) return chartData } } // End of Example_40.swift let time0 = Int64(Date().timeIntervalSince1970 * 1000) _ = try Example_40() let time1 = Int64(Date().timeIntervalSince1970 * 1000) print("Example_40 => \(time1 - time0)")
5320f737ad54f4536ad3741bb18925a4
23.921429
85
0.564632
false
false
false
false
laurentVeliscek/AudioKit
refs/heads/master
AudioKit/Common/Internals/AKNodeRecorder.swift
mit
1
// // AKAudioNodeRecorder.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Tweaked by Laurent Veliscek // Copyright © 2016 AudioKit. All rights reserved. // import Foundation import Foundation import AVFoundation /// Simple audio recorder class public class AKNodeRecorder { // MARK: - Properties // The node we record from private var node: AKNode? // The file to record to private var internalAudioFile: AKAudioFile private var recording = false /// True if we are recording. public var isRecording: Bool { return recording } /// Duration of recording public var recordedDuration: Double { return internalAudioFile.duration } /// Used for fixing recordings being truncated private var recordBufferDuration: Double = 16384 / AKSettings.sampleRate /// return the AKAudioFile for reading public var audioFile: AKAudioFile? { var internalAudioFileForReading: AKAudioFile do { internalAudioFileForReading = try AKAudioFile(forReading: internalAudioFile.url) return internalAudioFileForReading } catch let error as NSError { print("Cannot create internal audio file for reading") print("Error: \(error.localizedDescription)") return nil } } // MARK: - Initialization /// Initialize the node recorder /// /// Recording buffer size is defaulted to be AKSettings.bufferLength /// You can set a different value by setting an AKSettings.recordingBufferLength /// /// - Parameters: /// - node: Node to record from /// - file: Audio file to record to /// public init(node: AKNode = AudioKit.output!, file: AKAudioFile? = nil) throws { // AVAudioSession buffer setup if file == nil { // We create a record file in temp directory do { self.internalAudioFile = try AKAudioFile() } catch let error as NSError { print("AKNodeRecorder Error: Cannot create an empty audio file") throw error } } else { do { // We initialize AKAudioFile for writing (and check that we can write to) self.internalAudioFile = try AKAudioFile(forWriting: file!.url, settings: file!.processingFormat.settings) } catch let error as NSError { print("AKNodeRecorder Error: cannot write to \(file!.fileNamePlusExtension)") throw error } } self.node = node } // MARK: - Methods /// Start recording public func record() throws { if recording { print("AKNodeRecorder Warning: already recording !") return } #if os(iOS) // requestRecordPermission... var permissionGranted: Bool = false AKSettings.session.requestRecordPermission() { (granted: Bool)-> Void in if granted { permissionGranted = true } else { permissionGranted = false } } if !permissionGranted { print("AKNodeRecorder Error: Permission to record not granted") throw NSError(domain: NSURLErrorDomain, code: NSURLErrorUnknown, userInfo: nil) } // Sets AVAudioSession Category to be Play and Record if (AKSettings.session != AKSettings.SessionCategory.PlayAndRecord.rawValue) { do { try AKSettings.setSessionCategory(AKSettings.SessionCategory.PlayAndRecord) } catch let error as NSError { print("AKNodeRecorder Error: Cannot set AVAudioSession Category to be .PlaybackAndRecord") throw error } } #endif if node != nil { let recordingBufferLength: AVAudioFrameCount = AKSettings.recordingBufferLength.samplesCount recording = true print("recording") node!.avAudioNode.installTapOnBus(0, bufferSize: recordingBufferLength, format: internalAudioFile.processingFormat) { (buffer: AVAudioPCMBuffer!, time: AVAudioTime!) -> Void in do { self.recordBufferDuration = Double(buffer.frameLength) / AKSettings.sampleRate try self.internalAudioFile.writeFromBuffer(buffer) print("writing ( file duration: \(self.internalAudioFile.duration) seconds)") } catch let error as NSError { print("Write failed: error -> \(error.localizedDescription)") } } } else { print("AKNodeRecorder Error: input node is not available") } } /// Stop recording public func stop() { if !recording { print("AKNodeRecorder Warning: Cannot stop recording, already stopped !") return } recording = false if node != nil { if AKSettings.fixTruncatedRecordings { // delay before stopping so the recording is not truncated. let delay = UInt32(recordBufferDuration * 1000000) usleep(delay) } node!.avAudioNode.removeTapOnBus(0) print("Recording Stopped.") } else { print("AKNodeRecorder Error: input node is not available") } } /// Reset the AKAudioFile to clear previous recordings public func reset() throws { // Stop recording if recording { stop() } // Delete the physical recording file let fileManager = NSFileManager.defaultManager() let settings = internalAudioFile.processingFormat.settings let url = internalAudioFile.url do { try fileManager.removeItemAtPath(audioFile!.url.absoluteString) } catch let error as NSError { print("AKNodeRecorder Error: cannot delete Recording file: \(audioFile!.fileNamePlusExtension)") throw error } // Creates a blank new file do { internalAudioFile = try AKAudioFile(forWriting: url, settings: settings) print("AKNodeRecorder: file has been cleared") } catch let error as NSError { print("AKNodeRecorder Error: cannot record to file: \(internalAudioFile.fileNamePlusExtension)") throw error } } }
6fc22bc9dd5c8ce9f9c04520e5452a38
31.032864
110
0.574088
false
false
false
false
nua-schroers/mvvm-frp
refs/heads/master
20_Basic-App/MatchGame/MatchGame/Controller/SettingsViewController.swift
mit
1
// // SettingsViewController.swift // MatchGame // // Created by Dr. Wolfram Schroers on 5/27/16. // Copyright © 2016 Wolfram Schroers. All rights reserved. // import UIKit /// View controller of the second screen responsible for the settings. class SettingsViewController: UIViewController { // MARK: Settings received from the primary game view controller. /// Initial number of matches. var initialMatchCount = 18 /// Initial removal maximum. var removeMax = 3 /// Initial strategy selector value. var strategy = 0 /// Delegate for reporting changes. weak var delegate: CanAcceptSettings? // MARK: Lifecycle/workflow management override func viewDidLoad() { super.viewDidLoad() // Configure the initial state with current settings. self.initivalMatchCountSlider.value = Float(self.initialMatchCount) self.removeMaxSlider.value = Float(self.removeMax) self.strategySelector.selectedSegmentIndex = self.strategy self.updateLabels() } // MARK: User Interface /// Update the labels on this screen. func updateLabels() { self.initialMatchCountLabel.text = NSLocalizedString("Initial number of matches: \(self.initialMatchCount)", comment: "") self.removeMaxLabel.text = NSLocalizedString("Maximum number to remove: \(self.removeMax)", comment: "") } /// User taps the "Done" button. @IBAction func userTapsDone(_ sender: AnyObject) { // Submit the current settings to the delegate. self.delegate?.settingsChanged(self.strategySelector.selectedSegmentIndex, initialMatchOunt: self.initialMatchCount, removeMax: self.removeMax) // Transition back to primary game screen. self.dismiss(animated: true, completion: nil) } /// Label for initial match count. @IBOutlet weak var initialMatchCountLabel: UILabel! /// Slider for initial match count. @IBOutlet weak var initivalMatchCountSlider: UISlider! /// Label for remove maximum count. @IBOutlet weak var removeMaxLabel: UILabel! /// Slider for remove maximum count. @IBOutlet weak var removeMaxSlider: UISlider! /// Segmented control for strategy selection. @IBOutlet weak var strategySelector: UISegmentedControl! /// Reaction to moving the initial count slider. @IBAction func userChangesInitialMatchCount(_ sender: AnyObject) { self.initialMatchCount = Int(self.initivalMatchCountSlider.value) self.updateLabels() } /// Reaction to moving the remove maximum slider. @IBAction func userChangesRemoveMaxCount(_ sender: AnyObject) { self.removeMax = Int(self.removeMaxSlider.value) self.updateLabels() } }
b4959ab4299b1f2593403f4b7a0bdedd
31.186047
129
0.696893
false
false
false
false
imodeveloperlab/ImoTableView
refs/heads/development
Carthage/Carthage/Checkouts/Fakery/Sources/Fakery/Generators/Date.swift
mit
3
import Foundation extension Faker { public final class Date: Generator { public func backward(days: Int) -> Foundation.Date { return todayAddingDays(-days) } public func forward(_ days: Int) -> Foundation.Date { return todayAddingDays(days) } public func between(_ from: Foundation.Date, _ to: Foundation.Date) -> Foundation.Date { let fromInSeconds = from.timeIntervalSince1970 let toInSeconds = to.timeIntervalSince1970 let targetInSeconds = Number().randomDouble(min: fromInSeconds, max: toInSeconds) return Foundation.Date(timeIntervalSince1970: targetInSeconds) } public func birthday(_ minAge: Int, _ maxAge: Int) -> Foundation.Date { let olderAgeBirthDate = todayAddingYears(-maxAge) let earlierAgeBirthDate = todayAddingYears(-minAge) return between(earlierAgeBirthDate, olderAgeBirthDate) } private func todayAddingDays(_ days: Int) -> Foundation.Date { var dateComponents = DateComponents() dateComponents.day = days return todayAdding(dateComponents) } private func todayAddingYears(_ years: Int) -> Foundation.Date { var dateComponents = DateComponents() dateComponents.year = years return todayAdding(dateComponents) } private func todayAdding(_ dateComponents: DateComponents) -> Foundation.Date { let calendar = Calendar.current let todayDate = Foundation.Date() return calendar.date(byAdding: dateComponents, to: todayDate)! } } }
28907388936923878e06fe0fca81aef6
32.844444
92
0.700591
false
false
false
false
Artheyn/WAPullToSwitchSwift
refs/heads/master
WAPullToSwitchIntegrationSwift/ViewController.swift
unlicense
1
// // ViewController.swift // WAPullToSwitchIntegrationSwift // // Created by Alexandre KARST on 15/05/2015. // Copyright (c) 2015 Alexandre KARST. All rights reserved. // import UIKit class ViewController: UIViewController, WAPullToSwitchDataSource, WAPullToSwitchAnimationConfiguration { private var pullToSwitchViewController = WAPullToSwitchViewController() // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Instantiate our component and setup the data source. pullToSwitchViewController.dataSource = self pullToSwitchViewController.animationConfiguration = self } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let componentView = pullToSwitchViewController.view // Add the component view to our current view. self.view.addSubview(componentView) // Setup the component to fit its superview. let fitSuperviewConstraintsHorizontal = NSLayoutConstraint.constraintsWithVisualFormat("H:|[componentView]|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["componentView": componentView]) let fitSuperviewConstraintsVertical = NSLayoutConstraint.constraintsWithVisualFormat("V:|[componentView]|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["componentView": componentView]) self.view.addConstraints(fitSuperviewConstraintsHorizontal) self.view.addConstraints(fitSuperviewConstraintsVertical) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - WAPullToSwitchDataSource func viewForIndex(index: Int) -> UIView { let screenWidth = UIScreen.mainScreen().applicationFrame.size.width let screenHeight = UIScreen.mainScreen().applicationFrame.size.height let view = UIView(frame: CGRectMake(0.0, 0.0, screenWidth, screenHeight + 200.0)) if index % 2 == 0 { view.backgroundColor = UIColor.lightGrayColor() } else { view.backgroundColor = UIColor.brownColor() } return view } // MARK: - WAPullToSwitchAnimationConfiguration func gravityVectorYComponentForHide() -> Float { return Float(4.0) } func gravityVectorYComponentForBounce() -> Float { return Float(-3.0) } func elasticityCoefficientForBounce() -> Float { return Float(0.3) } }
4d9fefbc323d5bb25ff06d0dca2f518a
31.105882
207
0.668377
false
false
false
false
danielsaidi/KeyboardKit
refs/heads/master
Sources/KeyboardKit/Appearance/KeyboardAction+Button.swift
mit
1
// // KeyboardAction+Button.swift // KeyboardKit // // Created by Daniel Saidi on 2020-07-01. // Copyright © 2021 Daniel Saidi. All rights reserved. // import SwiftUI import UIKit public extension KeyboardAction { /** The action's standard button background color. */ func standardButtonBackgroundColor(for context: KeyboardContext, isPressed: Bool = false) -> Color { if let color = standardButtonBackgroundColorForAllStates() { return color } return isPressed ? standardButtonBackgroundColorForPressedState(for: context) : standardButtonBackgroundColorForIdleState(for: context) } /** The action's standard button font. */ var standardButtonFont: UIFont { .preferredFont(forTextStyle: standardButtonTextStyle) } /** The action's standard button font weight, if any. */ var standardButtonFontWeight: UIFont.Weight? { if standardButtonImage != nil { return .light } switch self { case .character(let char): return char.isLowercased ? .light : nil default: return nil } } /** The action's standard button foreground color. */ func standardButtonForegroundColor(for context: KeyboardContext, isPressed: Bool = false) -> Color { return isPressed ? standardButtonForegroundColorForPressedState(for: context) : standardButtonForegroundColorForIdleState(for: context) } /** The action's standard button image. */ var standardButtonImage: Image? { switch self { case .backspace: return .backspace case .command: return .command case .control: return .control case .dictation: return .dictation case .dismissKeyboard: return .keyboardDismiss case .image(_, let imageName, _): return Image(imageName) case .keyboardType(let type): return type.standardButtonImage case .moveCursorBackward: return .moveCursorLeft case .moveCursorForward: return .moveCursorRight case .newLine: return .newLine case .nextKeyboard: return .globe case .option: return .option case .settings: return .settings case .shift(let currentState): return currentState.standardButtonImage case .systemImage(_, let imageName, _): return Image(systemName: imageName) case .tab: return .tab default: return nil } } /** The action's standard button shadow color. */ func standardButtonShadowColor(for context: KeyboardContext) -> Color { if case .none = self { return .clear } if case .emoji = self { return .clear } return .standardButtonShadowColor(for: context) } /** The action's standard button text. */ var standardButtonText: String? { switch self { case .character(let char): return char case .emoji(let emoji): return emoji.char case .emojiCategory(let cat): return cat.fallbackDisplayEmoji.char case .keyboardType(let type): return type.standardButtonText default: return nil } } /** The action's standard button text style. */ var standardButtonTextStyle: UIFont.TextStyle { if hasMultiCharButtonText { return .body } switch self { case .character(let char): return char.isLowercased ? .title1 : .title2 case .emoji: return .title1 case .emojiCategory: return .callout case .space: return .body default: return .title2 } } } private extension KeyboardAction { /** Whether or not the button text has multiple characters. */ var hasMultiCharButtonText: Bool { guard let text = standardButtonText else { return false } return text.count > 1 } func standardButtonBackgroundColorForAllStates() -> Color? { if case .none = self { return .clear } if case .emoji = self { return .clearInteractable } if case .emojiCategory = self { return .clearInteractable } return nil } func standardButtonBackgroundColorForIdleState(for context: KeyboardContext) -> Color { if isPrimaryAction { return .blue } if isSystemAction { return .standardDarkButton(for: context) } return .standardButton(for: context) } func standardButtonBackgroundColorForPressedState(for context: KeyboardContext) -> Color { if isPrimaryAction { return context.colorScheme == .dark ? .standardDarkButton(for: context) : .white } if isSystemAction { return .white } return .standardDarkButton(for: context) } func standardButtonForegroundColorForIdleState(for context: KeyboardContext) -> Color { if isPrimaryAction { return .white } return .standardButtonTint(for: context) } func standardButtonForegroundColorForPressedState(for context: KeyboardContext) -> Color { if isPrimaryAction { return context.colorScheme == .dark ? .white : .standardButtonTint(for: context) } return .standardButtonTint(for: context) } }
f893b412d177358514b05fdabfb15199
33.437086
111
0.651346
false
false
false
false
madewithray/ray-broadcast
refs/heads/master
RayBroadcast/Pulse.swift
mit
1
// // LFTPulseAnimation.swift // // Created by Christoffer Tews on 18.12.14. // Copyright (c) 2014 Christoffer Tews. All rights reserved. // // Swift clone of: https://github.com/shu223/PulsingHalo/blob/master/PulsingHalo/PulsingHaloLayer.m import UIKit class LFTPulseAnimation: CALayer { var radius: CGFloat = 200.0 var fromValueForRadius: Float = 0.0 var fromValueForAlpha: Float = 0.45 var keyTimeForHalfOpacity: Float = 0.2 var animationDuration: NSTimeInterval = 3.0 var pulseInterval: NSTimeInterval = 0.0 var useTimingFunction: Bool = true var animationGroup: CAAnimationGroup = CAAnimationGroup() var repetitions: Float = Float.infinity // Need to implement that, because otherwise it can't find // the constructor init(layer:AnyObject!) // Doesn't seem to look in the super class override init!(layer: AnyObject!) { super.init(layer: layer) } init(repeatCount: Float=Float.infinity, radius: CGFloat, position: CGPoint) { super.init() self.contentsScale = UIScreen.mainScreen().scale self.opacity = 0.0 self.backgroundColor = UIColor(red: 88/255, green: 143/255, blue: 180/255, alpha: 1.0).CGColor self.radius = radius; self.repetitions = repeatCount; self.position = position let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0)) { self.setupAnimationGroup() self.setPulseRadius(self.radius) if (self.pulseInterval != Double.infinity) { dispatch_async(dispatch_get_main_queue()) { self.addAnimation(self.animationGroup, forKey: "pulse") } } } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setPulseRadius(radius: CGFloat) { self.radius = radius var tempPos = self.position var diameter = self.radius * 2 self.bounds = CGRect(x: 0.0, y: 0.0, width: diameter, height: diameter) self.cornerRadius = self.radius self.position = tempPos } func setupAnimationGroup() { self.animationGroup = CAAnimationGroup() self.animationGroup.duration = self.animationDuration + self.pulseInterval self.animationGroup.repeatCount = self.repetitions self.animationGroup.removedOnCompletion = false if self.useTimingFunction { var defaultCurve = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) self.animationGroup.timingFunction = defaultCurve } self.animationGroup.animations = [createScaleAnimation(), createOpacityAnimation()] } func createScaleAnimation() -> CABasicAnimation { var scaleAnimation = CABasicAnimation(keyPath: "transform.scale.xy") scaleAnimation.fromValue = NSNumber(float: self.fromValueForRadius) scaleAnimation.toValue = NSNumber(float: 1.0) scaleAnimation.duration = self.animationDuration return scaleAnimation } func createOpacityAnimation() -> CAKeyframeAnimation { var opacityAnimation = CAKeyframeAnimation(keyPath: "opacity") opacityAnimation.duration = self.animationDuration opacityAnimation.values = [self.fromValueForAlpha, 0.8, 0] opacityAnimation.keyTimes = [0, self.keyTimeForHalfOpacity, 1] opacityAnimation.removedOnCompletion = false return opacityAnimation } }
87f8bd729de958ac4fcea40625e0277f
36.642857
102
0.645432
false
false
false
false
eleks/digital-travel-book
refs/heads/master
src/Swift/Weekend In Lviv/ViewControllers/Article/WLArticleVCSw.swift
mit
1
// // WLArticleVCSw.swift // Weekend In Lviv // // Created by Admin on 13.06.14. // Copyright (c) 2014 rnd. All rights reserved. // import UIKit import QuartzCore class WLArticleVCSw: UIViewController, UIPopoverControllerDelegate, WLDetailBlockDelegate { // Outlets @IBOutlet weak var btnAddToFavourites:UIButton? @IBOutlet weak var scrollDetail:UIScrollView? @IBOutlet weak var lblFirst:WLCoreTextLabelSw? @IBOutlet weak var swipeLayer:UIView? @IBOutlet weak var lblSwipe:UILabel? @IBOutlet weak var imgTop:UIImageView? @IBOutlet weak var lblPlaceTitle:UILabel? @IBOutlet weak var btnPlayAudio:UIButton? var textBlocks = Dictionary<Int, WLArticleBlockSw>() var pointBlocks = Dictionary<Int, WLPointBlockViewSw>() var galleryPresented:Bool = false weak var _place:WLPlace? = nil weak var place:WLPlace? { get { return _place } set (place) { _place = place self.setupSwipeTip() } } // Instance methods override func viewDidLoad() { super.viewDidLoad() self.scrollDetail!.contentInset = UIEdgeInsetsMake(64, 0, 0, 0) self.galleryPresented = false self.lblSwipe!.font = WLFontManager.sharedManager.gentiumItalic15 self.lblFirst!.font = WLFontManager.sharedManager.palatinoRegular20 self.lblPlaceTitle!.font = WLFontManager.sharedManager.bebasRegular100 self.btnPlayAudio!.titleLabel!.font = WLFontManager.sharedManager.bebasRegular16 self.lblPlaceTitle!.text = self.place!.title var moPlace:Place = WLDataManager.sharedManager.placeWithIdentifier(self.place!.moIdentificator) if moPlace.favourite.boolValue { self.btnAddToFavourites!.setImage(UIImage(named:"BtnFavoriteBkg"), forState: UIControlState.Normal) } else { self.btnAddToFavourites!.setImage(UIImage(named:"BtnFavoriteBkg_inactive"), forState:UIControlState.Normal) } self.setupSwipeTip() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.setScrollLayoutForOrientation(UIApplication.sharedApplication().statusBarOrientation) } override func viewWillLayoutSubviews() { self.setScrollLayoutForOrientation(UIApplication.sharedApplication().statusBarOrientation) } /* Unavailable on Swift override func shouldAutorotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation) -> Bool { return true }*/ override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { NSNotificationCenter.defaultCenter().postNotificationName(kRotateNotification, object: nil) } override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { self.setScrollLayoutForOrientation(toInterfaceOrientation) } func setScrollLayoutForOrientation(orientation:UIInterfaceOrientation) { var topImage:UIImage? = WLDataManager.sharedManager.imageWithPath(self.place!.placeTopImagePath) if let topImage_ = topImage? { self.imgTop!.image = topImage_ } if (UIInterfaceOrientationIsLandscape(orientation)) { self.view.frame = CGRectMake(0, 0, 1024, 768) self.imgTop!.frame = CGRectMake(0, 0, 1024, 452) self.lblPlaceTitle!.frame = CGRectMake(self.lblPlaceTitle!.frame.origin.x, 40, self.lblPlaceTitle!.frame.size.width, self.lblPlaceTitle!.frame.size.height) self.btnPlayAudio!.frame = CGRectMake(self.btnPlayAudio!.frame.origin.x, 340, self.btnPlayAudio!.frame.size.width, self.btnPlayAudio!.frame.size.height) } else { self.view.frame = CGRectMake(0, 0, 768, 1024); self.imgTop!.frame = CGRectMake(0, 0, 768, 452 * 0.75) self.lblPlaceTitle!.frame = CGRectMake(self.lblPlaceTitle!.frame.origin.x, 20, self.lblPlaceTitle!.frame.size.width, self.lblPlaceTitle!.frame.size.height) self.btnPlayAudio!.frame = CGRectMake(self.btnPlayAudio!.frame.origin.x, 270, self.btnPlayAudio!.frame.size.width, self.btnPlayAudio!.frame.size.height) } self.lblFirst!.frame = CGRectMake(self.lblFirst!.frame.origin.x, self.imgTop!.frame.size.height + 40, self.lblFirst!.frame.size.width, self.lblFirst!.frame.size.height); let textBoundingRec:CGRect = (self.lblPlaceTitle!.text! as NSString).boundingRectWithSize(self.lblPlaceTitle!.frame.size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName : self.lblPlaceTitle!.font], context: nil) let textSize:CGSize = !CGRectIsNull(textBoundingRec) ? textBoundingRec.size : CGSizeZero let textRect:CGRect = CGRectMake(self.lblPlaceTitle!.frame.origin.x, self.lblPlaceTitle!.frame.origin.y, self.lblPlaceTitle!.frame.size.width, textSize.height) self.lblPlaceTitle!.frame = textRect self.lblPlaceTitle!.setNeedsDisplay() self.setDescriptionText(self.place!.placeText) let rowsCount:Int = self.place!.placesTextBlocks.count let thumbWidth:CGFloat = self.scrollDetail!.frame.size.width let x = CGFloat(0) var y = CGFloat(self.lblFirst!.frame.origin.y + self.lblFirst!.frame.size.height + 40) if rowsCount > 0 { for i:Int in 1...rowsCount { var itemView:WLArticleBlockSw? = self.textBlocks[i] if let itemView_ = itemView? { itemView_.layout() } else { var textBlock:WLTextBlock? = (self.place!.placesTextBlocks)[i - 1] itemView = NSBundle.mainBundle().loadNibNamed("WLArticleBlockSw", owner: nil, options: nil)[0] as? WLArticleBlockSw itemView!.setLayoutWithTextBlock(textBlock!) itemView!.delegate = self self.textBlocks[i] = itemView! } itemView!.frame = CGRectMake(x, y, thumbWidth, itemView!.frame.size.height) self.scrollDetail!.addSubview(itemView!) y += itemView!.frame.size.height } } let pointBlockCount:Int = self.place!.placesPointBlocks.count if pointBlockCount > 0 { for i:Int in 1...pointBlockCount { var itemView:WLPointBlockViewSw? = self.pointBlocks[i] if let itemView_ = itemView? { itemView_.layout() } else { var pointBlock:WLPointBlock = (self.place!.placesPointBlocks)[i - 1] itemView = NSBundle.mainBundle().loadNibNamed("WLPointBlockViewSw", owner: nil, options: nil)[0] as? WLPointBlockViewSw itemView!.setLayoutWithPointBlock(pointBlock) self.pointBlocks[i] = itemView! } itemView!.frame = CGRectMake(x, y, thumbWidth, itemView!.frame.size.height) self.scrollDetail!.addSubview(itemView!) y += itemView!.frame.size.height } } self.swipeLayer!.frame = CGRectMake(0, y, self.swipeLayer!.frame.size.width, self.swipeLayer!.frame.size.height) y += self.swipeLayer!.frame.size.height; let contentWidth:CGFloat = self.scrollDetail!.frame.size.width let contentHeight:CGFloat = y self.scrollDetail!.contentSize = CGSizeMake(contentWidth, contentHeight) } func setDescriptionText(text:String) { if text.utf16Count > 0 { var lblWidth:CGFloat if (UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication().statusBarOrientation)) { lblWidth = CGFloat(944) } else{ lblWidth = CGFloat(688) } let firstSize:CGSize = (text as NSString).boundingRectWithSize(CGSizeMake(lblWidth / 2 - 40, CGFloat(MAXFLOAT)), options:NSStringDrawingOptions.UsesLineFragmentOrigin, attributes:[NSFontAttributeName : self.lblFirst!.font], context:nil).size self.lblFirst!.text = text self.lblFirst!.frame = CGRectMake(self.lblFirst!.frame.origin.x, self.lblFirst!.frame.origin.y, lblWidth, firstSize.height / 2 + 40) } else { self.lblFirst!.text = "" } } func pushControllerWithAnimation(controller:UIViewController, view:UIView) { weak var weakSelf = self var transitionView:UIImageView = UIImageView(frame:view.frame) transitionView.image = (view as UIImageView).image view.superview!.addSubview(transitionView) view.hidden = true UIView.animateWithDuration(kPushAnimationDuration, animations: { let moveY:CATransform3D = CATransform3DMakeTranslation (0, 0, transitionView.frame.size.height) let rotateView:CATransform3D = CATransform3DMakeRotation(CGFloat(Float(0.0174532925) * -90), 1, 0, 0) let finishedTransform:CATransform3D = CATransform3DConcat(rotateView, moveY) transitionView.layer.transform = finishedTransform }, completion: {(value: Bool) in let strongSelf = weakSelf let viewTransform:CATransform3D = transitionView.layer.transform let controllerScale:CATransform3D = CATransform3DMakeScale(transitionView.frame.size.width / controller.view.frame.size.width, transitionView.frame.size.height / controller.view.frame.size.height, 0) let controllerFinishedTransform:CATransform3D = CATransform3DConcat(viewTransform, controllerScale) controller.view.layer.transform = controllerFinishedTransform let viewRect:CGRect = transitionView.convertRect(transitionView.bounds, toView:strongSelf!.view) let controllerRect:CGRect = controller.view.frame let controllerTransY:CGFloat = viewRect.origin.y - controllerRect.origin.y let controllerTransX:CGFloat = viewRect.origin.x - controllerRect.origin.x let controllerTranslate:CATransform3D = CATransform3DMakeTranslation(controllerTransX, controllerTransY, 0) let controllerTransform:CATransform3D = CATransform3DConcat(controller.view.layer.transform, controllerTranslate) controller.view.layer.transform = controllerTransform strongSelf!.view.addSubview(controller.view) UIView.animateWithDuration(kPushAnimationDuration, animations:{ controller.view.layer.transform = CATransform3DIdentity }, completion:{(value: Bool) in strongSelf!.navigationController!.pushViewController(controller, animated:false) strongSelf!.view.userInteractionEnabled = true strongSelf!.galleryPresented = false view.hidden = false }) }) } func tapOnImageWithPath(imagePath:String, imageContainer imageView:UIImageView) { if (!self.galleryPresented) { self.view.userInteractionEnabled = false self.galleryPresented = true var photoVC:WLPhotoGalleryVCSw? = WLPhotoGalleryVCSw(nibName: "WLPhotoGalleryVCSw", bundle: nil) photoVC!.imagePathList = WLDataManager.sharedManager.imageListWithPlace(self.place!) let index:Int? = (photoVC!.imagePathList as NSArray).indexOfObject(imagePath) if let index_ = index? { photoVC!.selectedImageIndex = UInt(index_) } photoVC!.view.frame = self.view.frame NSNotificationCenter.defaultCenter().postNotificationName("HidePlayer", object:nil) self.pushControllerWithAnimation(photoVC!, view:imageView) } } func setupSwipeTip() { let index:Int = (WLDataManager.sharedManager.placesList as NSArray).indexOfObject(self.place!) if let swipeLabel = self.lblSwipe? { if index == 0 { swipeLabel.text = "swipe right" } else if (index == WLDataManager.sharedManager.placesList.count - 1) { swipeLabel.text = "swipe left" } } } func scrollToTop() { self.scrollDetail!.contentOffset = CGPointMake(0, -64) } // Actions @IBAction func btnPlayAudioTouch(sender:UIButton) { NSNotificationCenter.defaultCenter().postNotificationName("playAudioFile", object: self, userInfo: ["file": self.place!.placeAudioPath]) } @IBAction func btnBackwardTouch(sender:AnyObject) { var detailController:WLDetailVCSw? = self.parentViewController!.parentViewController as? WLDetailVCSw if let detailController_ = detailController? { detailController_.switchToPreviousViewControllerAnimated(true) } } @IBAction func btnForwardTouch(sender:AnyObject) { var detailController:WLDetailVCSw? = self.parentViewController!.parentViewController as? WLDetailVCSw if let detailController_ = detailController? { detailController_.switchToNextViewControllerAnimated(true) } } @IBAction func btnAddToFavouriteTouch(sender:AnyObject) { var moPlace:Place? = WLDataManager.sharedManager.placeWithIdentifier(self.place!.moIdentificator) if let moPlace_ = moPlace? { if moPlace_.favourite.boolValue { moPlace_.favourite = NSNumber(bool: false) self.place!.placeFavourite = false self.btnAddToFavourites!.setImage(UIImage(named:"BtnFavoriteBkg_inactive"), forState:UIControlState.Normal) } else { moPlace_.favourite = NSNumber(bool: true) self.place!.placeFavourite = true self.btnAddToFavourites!.setImage(UIImage(named:"BtnFavoriteBkg"), forState:UIControlState.Normal) } WLDataManager.sharedManager.saveContext() NSNotificationCenter.defaultCenter().postNotificationName("ArticleStatusChanged", object:nil) } } }
0cc4bd691023da6e4badd5bd4aeb5cb8
43.412568
159
0.581667
false
false
false
false
simplysparsh/prime-factors-kata
refs/heads/master
Sources/Core/PrimeFactors.swift
mit
1
public class PrimeFactors { static public func generate(number: Int) -> Array<Int> { var factors: [Int] = [] var num = number var divisor = 2 while num > 1 { while (num % divisor) == 0 { factors.append(divisor) num = num/divisor } divisor = divisor + 1 } if num > 1 { factors.append(num) } return factors } }
a75851f8308a35b3273d6e703e6c1104
16.863636
58
0.529262
false
false
false
false
kickstarter/ios-oss
refs/heads/main
Library/ViewModels/DashboardReferrerRowStackViewViewModelTests.swift
apache-2.0
1
@testable import KsApi @testable import Library import Prelude import ReactiveExtensions import ReactiveExtensions_TestHelpers import ReactiveSwift import XCTest internal final class DashboardReferrersRowStackViewViewModelTests: TestCase { internal let vm = DashboardReferrerRowStackViewViewModel() internal let backersText = TestObserver<String, Never>() internal let pledgedText = TestObserver<String, Never>() internal let sourceText = TestObserver<String, Never>() internal let textColor = TestObserver<UIColor, Never>() internal override func setUp() { super.setUp() self.vm.outputs.backersText.observe(self.backersText.observer) self.vm.outputs.pledgedText.observe(self.pledgedText.observer) self.vm.outputs.sourceText.observe(self.sourceText.observer) self.vm.outputs.textColor.observe(self.textColor.observer) } func testReferrerRowDataEmits() { let referrer = .template |> ProjectStatsEnvelope.ReferrerStats.lens.backersCount .~ 50 |> ProjectStatsEnvelope.ReferrerStats.lens.percentageOfDollars .~ 0.125 |> ProjectStatsEnvelope.ReferrerStats.lens.pledged .~ 100.0 |> ProjectStatsEnvelope.ReferrerStats.lens.referrerName .~ "search" |> ProjectStatsEnvelope.ReferrerStats.lens.referrerType .~ .internal let country = Project.Country.us self.vm.inputs.configureWith(country: country, referrer: referrer) self.backersText.assertValues(["50"]) self.pledgedText.assertValues(["$100 (12%)"]) self.sourceText.assertValues(["search"]) self.textColor.assertValues([.ksr_create_700]) } }
3ff125b4ba9c2408d98710ecfe83147c
39.666667
77
0.766709
false
true
false
false
shabib87/SHVideoPlayer
refs/heads/master
SHVideoPlayer/Classes/SHVideoPlayerUtils.swift
mit
1
// // SHVideoPlayerUtils.swift // Pods // // Created by shabib hossain on 2/11/17. // // import Foundation struct SHVideoPlayerConstants { static let duration = "durationKey" static let playable = "playable" } final class SHVideoPlayerUtils: NSObject { class func resourceImagePath(_ fileName: String) -> UIImage? { let podBundle = Bundle(for: self.classForCoder()) if let bundleURL = podBundle.url(forResource: "SHVideoPlayer", withExtension: "bundle") { if let bundle = Bundle(url: bundleURL) { let image = UIImage(named: fileName, in: bundle, compatibleWith: nil) return image } else { assertionFailure("Could not load the bundle") } } else { assertionFailure("Could not create a path to the bundle") } return nil } } public extension UIColor { class func progressBarTintColor() -> UIColor { return UIColor(red: 1.0, green: 0.8, blue: 0.8, alpha: 1.0) } class func progressTrackTintColor() -> UIColor { return UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 0.3) } class func blackShadeColor() -> UIColor { return UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.3) } class func grayShadeColor() -> UIColor { return UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 0.3) } }
8dd59b27ee14fcf6971aa78bebb9cb7e
26.5
97
0.590909
false
false
false
false
changjianfeishui/iOS_Tutorials_Of_Swift
refs/heads/master
UIKit Dynamics and Motion Effects/SandwichFlow/SandwichFlow/AppDelegate.swift
mit
1
// // AppDelegate.swift // SandwichFlow // // Created by XB on 16/5/6. // Copyright © 2016年 XB. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? lazy var sandwiches:NSArray = { var path = NSBundle.mainBundle().pathForResource("Sandwiches", ofType: "json") var data = try! NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding) var dataResult:NSData = data.dataUsingEncoding(NSUTF8StringEncoding)! var result = try! NSJSONSerialization.JSONObjectWithData(dataResult, options: NSJSONReadingOptions.MutableContainers) as! NSArray return result; }() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. 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:. } }
e6f92ba57acc61d69a8fb654e6de314e
45.589286
285
0.74128
false
false
false
false
tassiahmed/SplitScreen
refs/heads/master
OSX/SplitScreen/File.swift
apache-2.0
1
// // File.swift // SplitScreen // // Created by Tausif Ahmed on 4/26/16. // Copyright © 2016 SplitScreen. All rights reserved. // import Foundation import AppKit class File: Equatable { fileprivate var path: URL fileprivate var file_name: String /** Inits the `File` with the `dirPath` and `name` - Parameter dirPath: `NSURL` that is where the file will be located - Parameter name: `String` that to the name of the `File` */ init(dirPath: URL, name: String) { file_name = name path = dirPath.appendingPathComponent(name) } /** Returns `file_name` - Returns: `String` that is the name of the `File` */ func getFileName() -> String { return file_name } /** Returns `path` - Returns: `String` representation of the `NSURL` for the `File` */ func getPathString() -> String { return path.path } /** Parses the contents of a file from a text file to an `array` of `arrays` of `Int` values - Parameter height: `Int` that corresponds to screen's height - Parameter width: `Int` that corresponds to screen's width - Returns: `array` of `arrays` of `Int` that contains values for a `SnapPoint` for each `array` */ func parseFileContent(_ height: Int, width: Int) -> [[Int]] { var text: String = String() var snap_params: [[Int]] = [] // Attempt to get text from file do { try text = String(contentsOfFile: path.path, encoding: String.Encoding.utf8) } catch _ { print("Could not read from \(file_name)") } // Split the text into lines let lines = text.split(separator: "\n").map(String.init) for line in lines { // Split line into the different values of a SnapPoint let components = line.split(separator: ",").map(String.init) var snap_param: [Int] = [] for component in components { // General values if component == "HEIGHT" { snap_param.append(height) } else if component == "WIDTH" { snap_param.append(width) } else if component == "0" { snap_param.append(0) } else if component != components.last { if component.range(of: "/") != nil { let dividends = component.split(separator: "/").map(String.init) if dividends[0] == "HEIGHT" { snap_param.append(height/Int(dividends[1])!) } else { snap_param.append(width/Int(dividends[1])!) } } else if component.range(of: "-") != nil { let dividends = component.split(separator: "-").map(String.init) if dividends[0] == "HEIGHT" { snap_param.append(height - Int(dividends[1])!) } else { snap_param.append(width - Int(dividends[1])!) } } // For the snap points that are stored as pairs } else { let snap_points = component.split(separator: ":").map(String.init) for snap_point in snap_points { var xCoord: Int var yCoord: Int var tuple: String = snap_point tuple.remove(at: tuple.startIndex) tuple.remove(at: tuple.index(before: tuple.endIndex)) let coords = tuple.split(separator: ";").map(String.init) if coords[0] == "0" { xCoord = 0 } else if coords[0].range(of: "-") != nil { let dividends = coords[0].split(separator: "-").map(String.init) xCoord = width - Int(dividends[1])! } else if coords[0].range(of: "/") != nil { let dividends = coords[0].split(separator: "/").map(String.init) xCoord = width/Int(dividends[1])! } else { xCoord = width } if coords[1] == "0" { yCoord = 0 } else if coords[1].range(of: "-") != nil { let dividends = coords[1].split(separator: "-").map(String.init) yCoord = height - Int(dividends[1])! } else if coords[1].range(of: "/") != nil { let dividends = coords[1].split(separator: "/").map(String.init) yCoord = height/Int(dividends[1])! } else { yCoord = height } snap_param.append(xCoord) snap_param.append(yCoord) } } } snap_params.append(snap_param) } return snap_params } } /** Creates an equality function for files based on their `path` and `file_name` - Parameter lhs: `File` that is the left hand `File` - Parameter rhs: `File` that is the right hand `File` - Returns: `Bool` that teels whether or not the 2 `File` objects are the same */ func ==(lhs: File, rhs: File) -> Bool { return lhs.getPathString() == rhs.getPathString() && lhs.getFileName() == rhs.getFileName() }
44d7d96972dbce29d9f12573c2c6bc5d
27.628205
97
0.611509
false
false
false
false
huangboju/Moots
refs/heads/master
算法学习/数据结构/DataStructures/DataStructures/Classes/BitSet.swift
mit
1
public struct BitSet { private (set) public var size: Int private let N = 64 public typealias Word = UInt64 fileprivate(set) public var words: [Word] public init(size: Int) { precondition(size > 0) self.size = size let n = (size + (N - 1)) / N words = [Word](repeating: 0, count: n) } }
cb34d8efb1bbf44294cb269acbb62d7d
20.266667
43
0.61442
false
false
false
false
TheBrewery/Hikes
refs/heads/master
WorldHeritage/AppDelegate.swift
mit
1
// // AppDelegate.swift // Hikes // // Created by James Hildensperger on 8/19/15. // Copyright (c) 2015 The Brewery. All rights reserved. // import UIKit import RealmSwift import MapKit import ObjectMapper import FBAnnotationClusteringSwift let RealmDataBaseDidLoadNotification = "RealmDataBaseDidLoadNotification" @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let statusBarView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.ExtraLight)) func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { TBLocationManager.authorize() customizeAppearance() executeOn(.Background) { if let path = NSBundle.mainBundle().pathForResource("sorted_sites", ofType: "json") { do { let jsonData = try NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe) let jsonResult = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments) as! [[String: AnyObject]] let _realm = try Realm() guard _realm.objects(Site).count == 0 else { return NSNotificationCenter.defaultCenter().postNotificationName(RealmDataBaseDidLoadNotification, object: nil) } try jsonResult.generate().forEach({ (dictionary) -> () in try _realm.write({ _realm.create(Site.self, value: Mapper<Site>().map(dictionary)!, update: true) }) }) NSNotificationCenter.defaultCenter().postNotificationName(RealmDataBaseDidLoadNotification, object: nil) } catch { print("LOAD ERROR") } } } return true } func customizeAppearance() { statusBarView.frame = UIApplication.sharedApplication().statusBarFrame window?.addSubview(statusBarView) UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont.regularFontOfSize(11.0)], forState: UIControlState.Normal) UITabBar.appearance().tintColor = UIColor.whDarkBlueColor() FBAnnotationClusterView.appearance().font = UIFont.semiboldFontOfSize(16.0) FBAnnotationClusterView.appearance().colors = [UIColor.whDarkBlueColor(), UIColor.whDarkBlueColor().lighterColorForColor(0.1)] FBAnnotationClusterView.appearance().size = CGSizeMake(25, 25) } 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:. } }
94b8cf255e667763a105aca039655ea8
46.230769
285
0.699162
false
false
false
false
ennioma/arek
refs/heads/develop
code/Classes/Core/Utilities/ArekPopupData.swift
mit
1
// // ArekPopupData.swift // Arek // // Copyright (c) 2016 Ennio Masi // // 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 public enum ArekPopupType { case codeido case native } public struct ArekPopupData { var title: String! var message: String! var image: String! var allowButtonTitle: String! var denyButtonTitle: String! var type: ArekPopupType! var styling: ArekPopupStyle? public init(title: String = "", message: String = "", image: String = "", allowButtonTitle: String = "", denyButtonTitle: String = "", type: ArekPopupType = .codeido, styling: ArekPopupStyle? = nil) { self.title = title self.message = message self.image = image self.allowButtonTitle = allowButtonTitle self.denyButtonTitle = denyButtonTitle self.type = type self.styling = styling } }
4e6a8ba254ad73d39966b009f553810d
34.103448
81
0.675344
false
false
false
false
aranasaurus/flingInvaders
refs/heads/master
flingInvaders/GameScene.swift
apache-2.0
1
// // GameScene.swift // flingInvaders // // Created by Ryan Arana on 7/12/14. // Copyright (c) 2014 aranasaurus.com. All rights reserved. // import SpriteKit enum ColliderType: UInt32 { case Ship = 1 case Meteor = 2 case Laser = 4 case Wall = 8 } extension SKSpriteNode { func lookAt(location: CGPoint) { let dx = location.x - self.position.x let dy = location.y - self.position.y self.zRotation = atan2(dy, dx) - M_PI_2 } } func randFloat(min:CGFloat, max:CGFloat) -> CGFloat { return (CGFloat(arc4random())/0x100000000) * (max-min) + min } func randPoint(bounds:CGRect) -> CGPoint { return CGPoint(x: randFloat(CGRectGetMinX(bounds), CGRectGetMaxX(bounds)), y: randFloat(CGRectGetMinY(bounds), CGRectGetMaxY(bounds))) } func randVector(min:CGFloat, max:CGFloat) -> CGVector { return CGVectorMake(randFloat(min, max), randFloat(min, max)) } class GameScene: SKScene, SKPhysicsContactDelegate { var lastTime = NSDate().timeIntervalSinceReferenceDate var bg:Background var player:Player var unlocked = false var flingBegan = CGPointZero var meteors = [Meteor]() init(coder aDecoder: NSCoder!) { bg = Background() player = Player() super.init(coder: aDecoder) } init(size: CGSize) { bg = Background() player = Player() super.init(size: size) } override func didMoveToView(view: SKView) { /* Setup your scene here */ self.backgroundColor = UIColor.blackColor() bg.zPosition = 0 bg.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame)) self.addChild(bg) player.zPosition = 10 player.position = CGPoint(x:CGRectGetMidX(self.frame), y:player.size.height + 10) self.addChild(player) var flingRecognizer = UIPanGestureRecognizer(target: self, action:"fling:") self.view.addGestureRecognizer(flingRecognizer) self.physicsWorld.contactDelegate = self self.physicsWorld.gravity = CGVectorMake(0, 0) let walls = SKPhysicsBody(edgeLoopFromRect: self.frame) walls.friction = 0 walls.categoryBitMask = ColliderType.Wall.toRaw() self.physicsBody = walls for _ in 1...4 { var meteor = Meteor(bounds: self.frame) self.addChild(meteor) meteor.activate() } } func fling(recognizer:UIPanGestureRecognizer) { let touchLocation = self.convertPointFromView(recognizer.locationInView(recognizer.view)) let touchVelocity = recognizer.velocityInView(self.view) let mag = fabs(touchVelocity.x) + fabs(touchVelocity.y) switch recognizer.state { case .Began: self.flingBegan = touchLocation case .Ended: // don't fire when velocity is too low if mag < 650 { break } player.fire(self.flingBegan, targetLoc: touchLocation, touchVelocity: touchVelocity) unlocked = false self.flingBegan = CGPointZero case .Cancelled, .Failed: unlocked = false case .Changed: if touchLocation.y > CGRectGetMaxY(self.frame) * 0.4 || mag < 300 { unlocked = true } if unlocked { player.lookAt(touchLocation) } default: break } } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { for touch: AnyObject in touches { let touchLocation = touch.locationInNode(self) self.player.lookAt(touchLocation) let m = Meteor(position: touchLocation, meteorType: .Big) self.addChild(m) m.activate() } } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ bg.update(currentTime) player.update(currentTime - self.lastTime) self.lastTime = currentTime } func didBeginContact(contact: SKPhysicsContact) { switch contact.bodyA.categoryBitMask { case ColliderType.Meteor.toRaw(): if contact.bodyB.categoryBitMask == ColliderType.Laser.toRaw() { (contact.bodyA.node as Meteor).hit() contact.bodyB.node.removeFromParent() contact.bodyB.categoryBitMask = 0 } case ColliderType.Laser.toRaw(): if contact.bodyB.categoryBitMask == ColliderType.Meteor.toRaw() { (contact.bodyB.node as Meteor).hit() contact.bodyA.node.removeFromParent() contact.bodyA.categoryBitMask = 0 } default: break } } }
992868c5d1a89bc24dfd3c55a647b8da
30.090909
97
0.609231
false
false
false
false
jblorenzo/BSImagePicker
refs/heads/master
Pod/Classes/View/AlbumCell.swift
mit
3
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // 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 /** Cell for photo albums in the albums drop down menu */ final class AlbumCell: UITableViewCell { @IBOutlet weak var firstImageView: UIImageView! @IBOutlet weak var secondImageView: UIImageView! @IBOutlet weak var thirdImageView: UIImageView! @IBOutlet weak var albumTitleLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Add a little shadow to images views for imageView in [firstImageView, secondImageView, thirdImageView] { imageView.layer.shadowColor = UIColor.whiteColor().CGColor imageView.layer.shadowRadius = 1.0 imageView.layer.shadowOffset = CGSize(width: 0.5, height: -0.5) imageView.layer.shadowOpacity = 1.0 } } override var selected: Bool { didSet { // Selection checkmark if selected == true { accessoryType = .Checkmark } else { accessoryType = .None } } } }
e98da01e9caf6d539ee7f7a6dfd7643f
37.946429
81
0.687299
false
false
false
false
pennlabs/penn-mobile-ios
refs/heads/main
PennMobile/Dining/SwiftUI/Views/Venue/Detail View/DiningVenueDetailHoursView.swift
mit
1
// // DiningVenueDetailHoursView.swift // PennMobile // // Created by CHOI Jongmin on 23/6/2020. // Copyright © 2020 PennLabs. All rights reserved. // import SwiftUI struct DiningVenueDetailHoursView: View { init(for venue: DiningVenue) { self.venue = venue } let venue: DiningVenue var body: some View { // TODO: Add level of business using public APIs Penn Dining will provide VStack(alignment: .leading, spacing: 7) { ForEach(0..<7) { duration in let dateInt = (7 - Date().integerDayOfWeek + duration) % 7 let date = Date().dateIn(days: dateInt) Text("\(date.dayOfWeek)") .font(duration == Date().integerDayOfWeek ? .system(size: 18, weight: .bold): .system(size: 18, weight: .regular)) HStack { ForEach(venue.formattedHoursArrayFor(date), id: \.self) { hours in Text(hours) .padding(.vertical, 3) .padding(.horizontal, 4) .font(.system(size: 14, weight: .light, design: .default)) .background(Color.grey5) .clipShape(RoundedRectangle(cornerRadius: 6)) } Spacer() }.offset(y: -4) } } } }
511c8736a675071a17cf234199e701d1
30.886364
134
0.506771
false
false
false
false
Mars182838/WJCycleScrollView
refs/heads/master
ScaledPageView/Pods/EZSwiftExtensions/Sources/UITextViewExtensions.swift
mit
2
// // UITextViewExtensions.swift // EZSwiftExtensions // // Created by Goktug Yilmaz on 15/07/15. // Copyright (c) 2015 Goktug Yilmaz. All rights reserved. // import UIKit extension UITextView { /// EZSwiftExtensions: Automatically sets these values: backgroundColor = clearColor, textColor = ThemeNicknameColor, clipsToBounds = true, /// textAlignment = Left, userInteractionEnabled = true, editable = false, scrollEnabled = false, font = ThemeFontName, fontsize = 17 public convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) { self.init(x: x, y: y, w: w, h: h, fontSize: 17) } /// EZSwiftExtensions: Automatically sets these values: backgroundColor = clearColor, textColor = ThemeNicknameColor, clipsToBounds = true, /// textAlignment = Left, userInteractionEnabled = true, editable = false, scrollEnabled = false, font = ThemeFontName public convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat, fontSize: CGFloat) { self.init(frame: CGRect(x: x, y: y, width: w, height: h)) font = UIFont.HelveticaNeue(type: FontType.None, size: fontSize) backgroundColor = UIColor.clearColor() clipsToBounds = true textAlignment = NSTextAlignment.Left userInteractionEnabled = true #if os(iOS) editable = false #endif scrollEnabled = false } #if os(iOS) /// EZSE: Automatically adds a toolbar with a done button to the top of the keyboard. Tapping the button will dismiss the keyboard. public func addDoneButton(barStyle: UIBarStyle = .Default, title: String? = nil) { let keyboardToolbar = UIToolbar() keyboardToolbar.items = [ UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil), UIBarButtonItem(title: title ?? "Done", style: .Done, target: self, action: #selector(resignFirstResponder)) ] keyboardToolbar.barStyle = barStyle keyboardToolbar.sizeToFit() inputAccessoryView = keyboardToolbar } #endif }
3b5d6d40dbe7c4dd2c6654f86ae979a7
38.574074
143
0.6584
false
false
false
false